<?php

namespace App\Http\Controllers\Provider;

use App\Http\Controllers\Controller;
use App\Http\Requests\AppointmentStoreRequest;
use App\Http\Requests\AppointmentStepperRequest;
use App\Http\Requests\AppointmentUpdateRequest;
use App\Models\Appointment;
use Illuminate\Http\Request;

class AppointmentController extends Controller
{
    public function calendar(Request $request)
    {
        $provider = auth()->user()->provider;
        $date = $request->get('date', now()->format('Y-m-d'));
        $view = $request->get('view', 'day');
        
        if ($view === 'month') {
            $parsedDate = now()->parse($date);
            $startDate = $parsedDate->copy()->startOfMonth();
            $endDate = $parsedDate->copy()->endOfMonth();
            
            $appointments = $provider->appointments()
                ->with(['client', 'service', 'payments'])
                ->whereBetween('start_time', [$startDate, $endDate])
                ->orderBy('start_time')
                ->get();
        } elseif ($view === 'year') {
            $parsedDate = now()->parse($date);
            $startDate = $parsedDate->copy()->startOfYear();
            $endDate = $parsedDate->copy()->endOfYear();
            
            $appointments = $provider->appointments()
                ->with(['client', 'service', 'payments'])
                ->whereBetween('start_time', [$startDate, $endDate])
                ->orderBy('start_time')
                ->get();
        } elseif ($view === 'day') {
            $startDate = now()->parse($date)->startOfDay();
            $endDate = now()->parse($date)->endOfDay();
            
            $appointments = $provider->appointments()
                ->with(['client', 'service', 'payments'])
                ->whereBetween('start_time', [$startDate, $endDate])
                ->orderBy('start_time')
                ->get();
        } else {
            $startDate = now()->parse($date)->startOfWeek();
            $endDate = now()->parse($date)->endOfWeek();
            
            $appointments = $provider->appointments()
                ->with(['client', 'service', 'payments'])
                ->whereBetween('start_time', [$startDate, $endDate])
                ->orderBy('start_time')
                ->get();
        }
            
        return view('provider.appointments.calendar', compact('appointments', 'date', 'view'));
    }

    public function index(Request $request)
    {
        $provider = auth()->user()->provider;
        
        $query = $provider->appointments()
            ->with(['client', 'service'])
            ->when($request->search, function ($q, $search) {
                $q->where(function ($subQuery) use ($search) {
                    $subQuery->where('notes', 'like', "%{$search}%")
                        ->orWhereHas('client', function ($clientQuery) use ($search) {
                            $clientQuery->where('first_name', 'like', "%{$search}%")
                                ->orWhere('last_name', 'like', "%{$search}%");
                        });
                });
            })
            ->when($request->status, function ($q, $status) {
                $q->where('status', $status);
            })
            ->when($request->client_id, function ($q, $clientId) {
                $q->where('client_id', $clientId);
            })
            ->when($request->service_id, function ($q, $serviceId) {
                $q->where('service_id', $serviceId);
            })
            ->when($request->date_from, function ($q, $dateFrom) {
                $q->where('start_time', '>=', $dateFrom);
            })
            ->when($request->date_to, function ($q, $dateTo) {
                $q->where('start_time', '<=', $dateTo . ' 23:59:59');
            })
            ->orderBy('start_time', 'desc');

        $appointments = $query->paginate(15);
        
        $clients = $provider->clients()->orderBy('first_name')->get();
        $services = $provider->services()->where('is_active', true)->orderBy('name')->get();

        return view('provider.appointments.index', compact('appointments', 'clients', 'services'));
    }

    public function create(Request $request)
    {
        $provider = auth()->user()->provider;
        
        $clients = $provider->clients()->orderBy('first_name')->get();
        $services = $provider->services()->where('is_active', true)->orderBy('name')->get();
        
        $defaultDate = $request->get('date', now()->format('Y-m-d'));
        
        // Arrondir l'heure aux 15 minutes suivantes
        $now = now();
        $minutes = $now->minute;
        $roundedMinutes = ceil($minutes / 15) * 15;
        
        if ($roundedMinutes >= 60) {
            $now->addHour();
            $roundedMinutes = 0;
        }
        
        $defaultTime = $request->get('time', $now->format('H') . ':' . str_pad($roundedMinutes, 2, '0', STR_PAD_LEFT));
        $appointment = null;
        
        return view('provider.appointments.stepper', compact('clients', 'services', 'defaultDate', 'defaultTime', 'appointment'));
    }

    public function checkOverlap(Request $request)
    {
        $provider = auth()->user()->provider;
        
        $startDateTime = $request->date . ' ' . $request->start_time;
        $endDateTime = $request->date . ' ' . $request->end_time;
        
        $overlapping = $provider->appointments()
            ->with(['client', 'service'])
            ->when($request->appointment_id, function ($query, $appointmentId) {
                $query->where('id', '!=', $appointmentId);
            })
            ->where(function ($query) use ($startDateTime, $endDateTime) {
                $query->where('start_time', '<', $endDateTime)
                      ->where('end_time', '>', $startDateTime);
            })
            ->first();
        
        if ($overlapping) {
            return response()->json([
                'overlap' => true,
                'details' => [
                    'client' => $overlapping->client ? $overlapping->client->first_name . ' ' . $overlapping->client->last_name : 'N/A',
                    'service' => $overlapping->service ? $overlapping->service->name : 'N/A',
                    'time' => $overlapping->start_time->format('H:i') . ' - ' . $overlapping->end_time->format('H:i')
                ]
            ]);
        }
        
        return response()->json(['overlap' => false]);
    }
    
    public function store(AppointmentStepperRequest $request)
    {
        $provider = auth()->user()->provider;
        
        $data = $request->validated();
        $data['provider_id'] = $provider->id;
        $data['start_time'] = $data['date'] . ' ' . $data['start_time'];
        $data['end_time'] = $data['date'] . ' ' . $data['end_time'];
        $data['price_at_booking'] = $data['price'];
        
        $service = $provider->services()->find($data['service_id']);
        $data['currency'] = $service->currency ?? 'TND';
        
        unset($data['date'], $data['price']);
        
        $appointment = Appointment::create($data);

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'appointment' => $appointment]);
        }

        return redirect()->route('provider.appointments.calendar', [
            'date' => $appointment->start_time->format('Y-m-d'),
            'highlight' => $appointment->uuid
        ])->with('success', 'Rendez-vous créé avec succès.');
    }

    public function edit($appointment_uuid)
    {
        $appointment = $this->findAppointmentByUuid($appointment_uuid);
        $provider = auth()->user()->provider;
        
        $clients = $provider->clients()->orderBy('first_name')->get();
        $services = $provider->services()->where('is_active', true)->orderBy('name')->get();
        
        $defaultDate = $appointment->start_time->format('Y-m-d');
        $defaultTime = $appointment->start_time->format('H:i');
        
        return view('provider.appointments.stepper', compact('appointment', 'clients', 'services', 'defaultDate', 'defaultTime'));
    }

    public function update(AppointmentStepperRequest $request, $appointment_uuid)
    {
        $appointment = $this->findAppointmentByUuid($appointment_uuid);
        $provider = auth()->user()->provider;
        
        $data = $request->validated();
        $data['start_time'] = $data['date'] . ' ' . $data['start_time'];
        $data['end_time'] = $data['date'] . ' ' . $data['end_time'];
        $data['price_at_booking'] = $data['price'];
        
        $service = $provider->services()->find($data['service_id']);
        $data['currency'] = $service->currency ?? 'TND';
        
        unset($data['date'], $data['price']);
        
        $appointment->update($data);
        $appointment->refresh();

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'appointment' => $appointment]);
        }

        $redirectDate = $appointment->start_time->format('Y-m-d');
        $redirectUuid = $appointment->uuid;
        
        \Log::info('Redirect params', ['date' => $redirectDate, 'uuid' => $redirectUuid]);

        return redirect()->route('provider.appointments.calendar', [
            'date' => $redirectDate,
            'highlight' => $redirectUuid
        ])->with('success', 'Rendez-vous modifié avec succès.');
    }

    public function destroy($appointment_uuid)
    {
        $appointment = $this->findAppointmentByUuid($appointment_uuid);
        
        $appointment->delete();

        return redirect()->route('provider.appointments.calendar')
            ->with('success', 'Rendez-vous supprimé avec succès.');
    }

    private function findAppointmentByUuid($appointment_uuid)
    {
        $provider = auth()->user()->provider;
        
        return $provider->appointments()
            ->where('uuid', $appointment_uuid)
            ->firstOrFail();
    }
}