<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TailorController extends Controller
{
    public function getAllTailors()
    {
        try {
            $tailors = User::where('role', 'penjahit')
                ->withAvg('ratings as average_rating', 'rating')
                ->having('average_rating', '>', 2.5)
                ->orWhereNull('average_rating')
                ->with(['specializations', 'services', 'ratings'])
                ->get()
                ->map(function ($tailor) {
                    return [
                        'id' => $tailor->id,
                        'name' => $tailor->name,
                        'email' => $tailor->email,
                        'phone' => $tailor->phone_number,
                        'profile' => [
                            'shop_name' => $tailor->name,
                            'address' => $tailor->address,
                            'description' => $tailor->shop_description,
                            'photo' => $tailor->profile_photo,
                            'latitude' => $tailor->latitude,
                            'longitude' => $tailor->longitude
                        ],
                        'specializations' => $tailor->specializations->map(function ($specialization) {
                            return [
                                'id' => $specialization->id,
                                'name' => $specialization->name,
                                'photo' => $specialization->photo
                            ];
                        }),
                        'services' => $tailor->services->map(function ($service) {
                            return [
                                'id' => $service->id,
                                'name' => $service->name,
                                'price' => $service->price,
                                'description' => $service->description,
                                'is_available' => $service->is_available
                            ];
                        }),
                        'ratings' => [
                            'average_rating' => round($tailor->average_rating ?? 0, 1),
                            'total_ratings' => $tailor->ratings->count(),
                            'reviews' => $tailor->ratings->map(function ($rating) {
                                return [
                                    'rating' => $rating->rating,
                                    'comment' => $rating->review,
                                    'created_at' => $rating->created_at
                                ];
                            })
                        ]
                    ];
                });

            return response()->json([
                'status' => 'success',
                'data' => $tailors
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to retrieve tailors data',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    // Method untuk mendapatkan semua penjahit tanpa filter rating
    public function getAllTailorsNoFilter()
    {
        try {
            $tailors = User::where('role', 'penjahit')
                ->withAvg('ratings as average_rating', 'rating')
                ->with(['specializations', 'services', 'ratings'])
                ->get()
                ->map(function ($tailor) {
                    return [
                        'id' => $tailor->id,
                        'name' => $tailor->name,
                        'email' => $tailor->email,
                        'phone' => $tailor->phone_number,
                        'profile' => [
                            'shop_name' => $tailor->name,
                            'address' => $tailor->address,
                            'description' => $tailor->shop_description,
                            'photo' => $tailor->profile_photo,
                            'latitude' => $tailor->latitude,
                            'longitude' => $tailor->longitude
                        ],
                        'specializations' => $tailor->specializations->map(function ($specialization) {
                            return [
                                'id' => $specialization->id,
                                'name' => $specialization->name,
                                'photo' => $specialization->photo
                            ];
                        }),
                        'services' => $tailor->services->map(function ($service) {
                            return [
                                'id' => $service->id,
                                'name' => $service->name,
                                'price' => $service->price,
                                'description' => $service->description,
                                'is_available' => $service->is_available
                            ];
                        }),
                        'ratings' => [
                            'average_rating' => round($tailor->average_rating ?? 0, 1),
                            'total_ratings' => $tailor->ratings->count(),
                            'reviews' => $tailor->ratings->map(function ($rating) {
                                return [
                                    'rating' => $rating->rating,
                                    'comment' => $rating->review,
                                    'created_at' => $rating->created_at
                                ];
                            })
                        ]
                    ];
                });

            return response()->json([
                'status' => 'success',
                'data' => $tailors
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to retrieve tailors data',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function deleteTailor($id)
    {
        try {
            $tailor = User::where('role', 'penjahit')->find($id);

            if (!$tailor) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Penjahit tidak ditemukan'
                ], 404);
            }

            // Hapus relasi spesialisasi terlebih dahulu
            $tailor->specializations()->detach();

            // Hapus relasi gallery
            $tailor->gallery()->delete();

            // Hapus relasi services
            $tailor->services()->delete();

            // Hapus relasi ratings
            $tailor->ratings()->delete();

            // Hapus penjahit
            $tailor->delete();

            return response()->json([
                'status' => 'success',
                'message' => 'Penjahit berhasil dihapus'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Gagal menghapus penjahit',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function updateTailor(Request $request, $id)
    {
        try {
            // Validasi input
            $request->validate([
                'name' => 'sometimes|string|max:255',
                'email' => 'sometimes|email|unique:users,email,' . $id,
                'phone_number' => 'sometimes|string|max:20',
                'address' => 'sometimes|string',
                'shop_description' => 'sometimes|string',
                'latitude' => 'sometimes|numeric',
                'longitude' => 'sometimes|numeric',
                'specialization_ids' => 'sometimes|array',
                'specialization_ids.*' => 'exists:tailor_specializations,id'
            ]);

            // Cari penjahit
            $tailor = User::where('role', 'penjahit')->find($id);

            if (!$tailor) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Penjahit tidak ditemukan'
                ], 404);
            }

            // Update data dasar
            $tailor->update($request->only([
                'name',
                'email',
                'phone_number',
                'address',
                'shop_description',
                'latitude',
                'longitude'
            ]));

            // Update spesialisasi jika ada
            if ($request->has('specialization_ids')) {
                $tailor->specializations()->sync($request->specialization_ids);
            }

            // Load ulang relasi untuk memastikan data terbaru
            $tailor->load('specializations');

            return response()->json([
                'status' => 'success',
                'message' => 'Data penjahit berhasil diperbarui',
                'data' => [
                    'id' => $tailor->id,
                    'name' => $tailor->name,
                    'email' => $tailor->email,
                    'phone_number' => $tailor->phone_number,
                    'address' => $tailor->address,
                    'shop_description' => $tailor->shop_description,
                    'profile_photo' => $tailor->profile_photo,
                    'location' => [
                        'latitude' => $tailor->latitude,
                        'longitude' => $tailor->longitude
                    ],
                    'specializations' => $tailor->specializations->map(function ($spec) {
                        return [
                            'id' => $spec->id,
                            'name' => $spec->name,
                            'icon' => $spec->icon
                        ];
                    })
                ]
            ]);

        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validasi gagal',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Gagal memperbarui data penjahit',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
