<?php

namespace App\Http\Controllers\Admin;

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

class DoctorController extends Controller
{
    public function index()
    {
        return response()->json(Doctor::with([
            'services',
            'holidays' => function ($query) {
                $query->orderBy('holiday_date', 'asc');
            },
            'recurringHolidays'
        ])->get());
    }

    public function store(Request $request)
    {
        $doctor = Doctor::create($request->all());
        if ($request->has('services')) {
            $doctor->services()->sync($request->services);
        }
        return response()->json($doctor->load('services'));
    }

    public function update(Request $request, $id)
    {
        $doctor = Doctor::findOrFail($id);
        $doctor->update($request->all());
        if ($request->has('services')) {
            $doctor->services()->sync($request->services);
        }
        return response()->json($doctor->load('services'));
    }

    public function destroy($id)
    {
        Doctor::destroy($id);
        return response()->json(['message' => 'Doctor deleted']);
    }

    public function addHoliday(Request $request, $id)
    {
        $request->validate([
            'holiday_date' => 'required|date'
        ]);

        $doctor = Doctor::findOrFail($id);
        $holiday = $doctor->holidays()->create([
            'holiday_date' => $request->holiday_date
        ]);
        return response()->json($holiday);
    }

    public function removeHoliday($id, $holidayId)
    {
        \App\Models\DoctorHoliday::destroy($holidayId);
        return response()->json(['message' => 'Holiday removed']);
    }

    public function getRecurring($id)
    {
        $doctor = Doctor::findOrFail($id);
        return response()->json($doctor->recurringHolidays);
    }

    public function syncRecurring(Request $request, $id)
    {
        $request->validate([
            'days' => 'array',
            'days.*' => 'integer|min:0|max:6'
        ]);

        $doctor = Doctor::findOrFail($id);
        $doctor->recurringHolidays()->delete();

        $data = array_map(fn($day) => ['day_of_week' => $day], $request->days);
        $doctor->recurringHolidays()->createMany($data);

        return response()->json($doctor->load('recurringHolidays'));
    }
}
