<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Appointment;
use App\Models\User;
use App\Models\LegalCase;

class AppointmentController extends Controller
{
    public function index()
    {
        // 1. Get Appointments
        $query = Appointment::with(['client', 'case'])->latest();
        if (!auth()->user()->hasRole('super_admin')) {
            $query->where('user_id', auth()->id());
        }
        $appointments = $query->get();

        // 2. Get Court Dates (New Feature)
        $courtDates = LegalCase::whereNotNull('court_date')
            ->select('id', 'case_number', 'court_date', 'court_name', 'title') // optimized select
            ->get();

        // 3. Data for Modal
        $clients = User::role('client')->get();
        $cases = LegalCase::where('status', 'open')->get();

        return view('admin.appointments.index', compact('appointments', 'courtDates', 'clients', 'cases'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string',
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
            'client_id' => 'nullable|exists:users,id',
        ]);

        Appointment::create([
            'user_id' => auth()->id(),
            'title' => $request->title,
            'start_time' => $request->start_time,
            'end_time' => $request->end_time,
            'client_id' => $request->client_id,
            'legal_case_id' => $request->legal_case_id,
            'location' => $request->location,
            'notes' => $request->notes,
        ]);

        return back()->with('success', 'Appointment scheduled successfully.');
    }

    public function update(Request $request, Appointment $appointment)
    {
        $appointment->update($request->only('status', 'notes'));
        return back()->with('success', 'Appointment updated.');
    }

    public function destroy(Appointment $appointment)
    {
        $appointment->delete();
        return back()->with('success', 'Appointment cancelled.');
    }
}
