<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BookingController extends Controller
{
    public function getClinic()
    {
        return response()->json(\App\Models\Clinic::first());
    }

    public function getServices()
    {
        return response()->json(\App\Models\Service::all());
    }

    public function getDoctors()
    {
        return response()->json(\App\Models\Doctor::with('holidays', 'recurringHolidays')->get());
    }

    public function getDoctorsByService($serviceId)
    {
        $service = \App\Models\Service::with([
            'doctors' => function ($q) {
                $q->with('holidays', 'recurringHolidays');
            }
        ])->findOrFail($serviceId);
        return response()->json($service->doctors);
    }

    public function getAvailableSlots(Request $request)
    {
        $request->validate([
            'doctor_id' => 'required',
            'service_id' => 'required',
            'date' => 'required|date|after_or_equal:today',
        ]);

        $doctor = \App\Models\Doctor::findOrFail($request->doctor_id);
        $service = \App\Models\Service::findOrFail($request->service_id);
        $date = $request->date;

        // Check if doctor is on holiday (specific date)
        if ($doctor->holidays()->where('holiday_date', $date)->exists()) {
            return response()->json([]);
        }

        // Check if doctor has a recurring holiday on this day of the week
        $dayOfWeek = date('w', strtotime($date));
        if ($doctor->recurringHolidays()->where('day_of_week', $dayOfWeek)->exists()) {
            return response()->json([]);
        }

        // Logic for slots: 9 AM to 6 PM, 10 min slots? 
        // Let's assume clinic hours are 9:00 to 18:00
        $startTime = strtotime("09:00");
        $endTime = strtotime("18:00");
        $duration = $service->duration * 60; // in seconds

        $slots = [];
        $current = $startTime;

        $existingAppointments = \App\Models\Appointment::where('doctor_id', $doctor->id)
            ->where('appointment_date', $date)
            ->where('status', '!=', 'cancelled')
            ->get();

        while ($current + $duration <= $endTime) {
            $slotStart = date("H:i:s", $current);
            $slotEnd = date("H:i:s", $current + $duration);

            $isBooked = $existingAppointments->contains(function ($appointment) use ($slotStart, $slotEnd) {
                return ($slotStart < $appointment->end_time && $slotEnd > $appointment->start_time);
            });

            if (!$isBooked) {
                // Also check if slot is in the past for today - using Asia/Kolkata timezone
                $now = \Carbon\Carbon::now('Asia/Kolkata');
                $isToday = $date == $now->format('Y-m-d');

                if (!$isToday || $current > strtotime($now->format('H:i:s'))) {
                    $slots[] = [
                        'start' => date("h:i A", $current),
                        'end' => date("h:i A", $current + $duration),
                        'value' => $slotStart
                    ];
                }
            }
            $current += 600; // Increment by 10 minutes for next slot start (standard check)
        }

        return response()->json($slots);
    }

    public function bookAppointment(Request $request)
    {
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'customer_mobile' => 'required|string|max:20',
            'doctor_id' => 'required|exists:doctors,id',
            'service_id' => 'required|exists:services,id',
            'appointment_date' => 'required|date|after_or_equal:today',
            'start_time' => 'required',
        ]);

        $service = \App\Models\Service::findOrFail($request->service_id);
        $startTime = strtotime($request->start_time);
        $endTime = date("H:i:s", $startTime + ($service->duration * 60));

        $appointment = \App\Models\Appointment::create([
            'customer_name' => $request->customer_name,
            'customer_mobile' => $request->customer_mobile,
            'doctor_id' => $request->doctor_id,
            'service_id' => $request->service_id,
            'appointment_date' => $request->appointment_date,
            'start_time' => date("H:i:s", $startTime),
            'end_time' => $endTime,
            'status' => 'pending',
        ]);

        return response()->json([
            'message' => 'Appointment booked successfully',
            'appointment' => $appointment
        ], 201);
    }
}
