<?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 CustomerController extends Controller
{
    public function getAllCustomers()
    {
        try {
            $customers = User::where('role', 'pelanggan')
                ->with(['customerBookings', 'preferredSpecializations', 'givenRatings'])
                ->get()
                ->map(function ($customer) {
                    return [
                        'id' => $customer->id,
                        'name' => $customer->name,
                        'email' => $customer->email,
                        'phone_number' => $customer->phone_number,
                        'address' => $customer->address,
                        'profile_photo' => $customer->profile_photo,
                        'location' => [
                            'latitude' => $customer->latitude,
                            'longitude' => $customer->longitude
                        ],
                        'preferred_specializations' => $customer->preferredSpecializations->map(function ($spec) {
                            return [
                                'id' => $spec->id,
                                'name' => $spec->name,
                                'photo' => $spec->photo
                            ];
                        }),
                        'bookings' => [
                            'total' => $customer->customerBookings->count(),
                            'completed' => $customer->customerBookings->where('status', 'completed')->count(),
                            'recent' => $customer->customerBookings->take(5)->map(function ($booking) {
                                return [
                                    'id' => $booking->id,
                                    'tailor_name' => $booking->tailor->name ?? 'Unknown',
                                    'status' => $booking->status,
                                    'appointment_date' => $booking->appointment_date,
                                    'total_price' => $booking->total_price
                                ];
                            })
                        ],
                        'ratings_given' => [
                            'total' => $customer->givenRatings->count(),
                            'average_rating' => round($customer->givenRatings->avg('rating') ?? 0, 1),
                            'recent' => $customer->givenRatings->take(5)->map(function ($rating) {
                                return [
                                    'rating' => $rating->rating,
                                    'review' => $rating->review,
                                    'tailor_name' => $rating->tailor->name ?? 'Unknown',
                                    'created_at' => $rating->created_at
                                ];
                            })
                        ],
                        'created_at' => $customer->created_at,
                        'updated_at' => $customer->updated_at
                    ];
                });

            return response()->json([
                'status' => 'success',
                'data' => $customers
            ]);

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

    public function getCustomerDetail($id)
    {
        try {
            $customer = User::where('role', 'pelanggan')
                ->with(['customerBookings.tailor', 'preferredSpecializations', 'givenRatings.tailor'])
                ->findOrFail($id);

            $data = [
                'id' => $customer->id,
                'name' => $customer->name,
                'email' => $customer->email,
                'phone_number' => $customer->phone_number,
                'address' => $customer->address,
                'profile_photo' => $customer->profile_photo,
                'location' => [
                    'latitude' => $customer->latitude,
                    'longitude' => $customer->longitude
                ],
                'preferred_specializations' => $customer->preferredSpecializations->map(function ($spec) {
                    return [
                        'id' => $spec->id,
                        'name' => $spec->name,
                        'photo' => $spec->photo
                    ];
                }),
                'bookings' => [
                    'total' => $customer->customerBookings->count(),
                    'completed' => $customer->customerBookings->where('status', 'completed')->count(),
                    'history' => $customer->customerBookings->map(function ($booking) {
                        return [
                            'id' => $booking->id,
                            'tailor_name' => $booking->tailor->name ?? 'Unknown',
                            'status' => $booking->status,
                            'appointment_date' => $booking->appointment_date,
                            'total_price' => $booking->total_price,
                            'service_type' => $booking->service_type,
                            'notes' => $booking->notes,
                            'created_at' => $booking->created_at
                        ];
                    })
                ],
                'ratings_given' => [
                    'total' => $customer->givenRatings->count(),
                    'average_rating' => round($customer->givenRatings->avg('rating') ?? 0, 1),
                    'history' => $customer->givenRatings->map(function ($rating) {
                        return [
                            'rating' => $rating->rating,
                            'review' => $rating->review,
                            'tailor_name' => $rating->tailor->name ?? 'Unknown',
                            'created_at' => $rating->created_at
                        ];
                    })
                ],
                'created_at' => $customer->created_at,
                'updated_at' => $customer->updated_at
            ];

            return response()->json([
                'status' => 'success',
                'data' => $data
            ]);

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

    public function getCustomerTransactions($id)
    {
        try {
            $customer = User::where('role', 'pelanggan')
                ->with(['customerBookings.tailor'])
                ->findOrFail($id);

            $transactions = $customer->customerBookings->map(function ($booking) {
                return [
                    'booking_id' => $booking->id,
                    'tailor_name' => $booking->tailor->name ?? 'Unknown',
                    'status' => $booking->status,
                    'appointment_date' => $booking->appointment_date,
                    'service_type' => $booking->service_type,
                    'total_price' => $booking->total_price,
                    'payment_status' => $booking->payment_status,
                    'notes' => $booking->notes,
                    'created_at' => $booking->created_at
                ];
            });

            return response()->json([
                'status' => 'success',
                'data' => [
                    'customer_id' => $customer->id,
                    'customer_name' => $customer->name,
                    'total_transactions' => $transactions->count(),
                    'total_spent' => $transactions->where('payment_status', 'paid')->sum('total_price'),
                    'transactions' => $transactions
                ]
            ]);

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

    public function updateCustomerSpecializations(Request $request, $id)
    {
        try {
            // Validasi input
            $request->validate([
                'specialization_ids' => 'required|array',
                'specialization_ids.*' => 'exists:tailor_specializations,id'
            ]);

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

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

            // Sync specializations
            $customer->preferredSpecializations()->sync($request->specialization_ids);

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

            return response()->json([
                'status' => 'success',
                'message' => 'Spesialisasi pelanggan berhasil diperbarui',
                'data' => [
                    'customer_id' => $customer->id,
                    'customer_name' => $customer->name,
                    'specializations' => $customer->preferredSpecializations->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 spesialisasi pelanggan',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function deleteCustomer($id)
    {
        try {
            $customer = User::where('role', 'pelanggan')->find($id);

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

            // Hapus relasi spesialisasi terlebih dahulu
            $customer->preferredSpecializations()->detach();

            // Hapus customer
            $customer->delete();

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

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