<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LeaveRequest;
use App\Models\LeaveType;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class LeaveRequestController extends Controller
{
    /**
     * Display a listing of all leave requests.
     */
    public function index(Request $request): Response
    {
        $query = LeaveRequest::with(['user', 'leaveType']);

        // Basic Filtering
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        if ($request->has('leave_type_id')) {
            $query->where('leave_type_id', $request->leave_type_id);
        }

        $requests = $query->orderBy('created_at', 'desc')->paginate(15);

        return Inertia::render('Admin/Leave/Index', [
            'requests' => $requests,
            'leaveTypes' => LeaveType::all(),
            'filters' => $request->only(['status', 'leave_type_id']),
        ]);
    }

    /**
     * Display a calendar view of leave requests.
     */
    public function calendar(Request $request): Response
    {
        $month = $request->get('month', now()->month);
        $year = $request->get('year', now()->year);

        $requests = LeaveRequest::with(['user', 'leaveType'])
            ->where(function ($q) use ($month, $year) {
                $q->whereMonth('start_date', $month)->whereYear('start_date', $year)
                    ->orWhereMonth('end_date', $month)->whereYear('end_date', $year);
            })
            ->where('status', 'approved')
            ->get();

        return Inertia::render('Admin/Leave/Calendar', [
            'requests' => $requests,
            'currentMonth' => (int) $month,
            'currentYear' => (int) $year,
        ]);
    }
}
