<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\Booking;
use App\Models\User;
use App\Notifications\DoctorAssignedNotification;

class AdminBookingController extends Controller
{
    public function index(Request $request)
    {
        $request->validate([
            'type' => 'nullable|string|in:event,service,school-service',
        ]);

        $query = Booking::with('bookable', 'user', 'doctor')->latest();

        if ($request->filled('type')) {
            $type = $request->input('type');
            $bookableType = match ($type) {
                'event' => 'App\\Models\\Event',
                'service' => 'App\\Models\\Service',
                'school-service' => 'App\\Models\\SchoolService',
                default => null,
            };

            if ($bookableType) {
                $query->where('bookable_type', $bookableType);
            }
        }

        $bookings = $query->paginate(10)->withQueryString();

        return Inertia::render('Admin/Bookings/Index', [
            'bookings' => $bookings,
            'filter' => $request->input('type'),
        ]);
    }

    public function show(Booking $booking)
    {
        $booking->load('bookable', 'user', 'doctor');
        $doctors = [];
        if ($booking->bookable_type === 'App\\Models\\Service') {
            $doctors = User::where('role', 200)->get();
        }

        return Inertia::render('Admin/Bookings/Show', [
            'booking' => $booking,
            'doctors' => $doctors,
        ]);
    }

    public function assignDoctor(Request $request, Booking $booking)
    {
        $request->validate([
            'doctor_id' => 'required|exists:users,id',
        ]);

        $booking->update([
            'doctor_id' => $request->doctor_id,
        ]);

        // Eager load relationships for notification
        $booking->load('user', 'bookable');
        $doctor = User::find($request->doctor_id);

        if ($doctor) {
            $doctor->notify(new DoctorAssignedNotification($booking));
        }

        return redirect()->route('admin.bookings.show', $booking->id)->with('success', 'Doctor assigned successfully.');
    }
}
