<?php

namespace App\Http\Controllers\SchoolAdmin\Staff;

use App\Http\Controllers\Controller;
use App\Models\LeaveRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LeaveController extends Controller
{
    public function index(Request $request)
    {
        $schoolId = Auth::user()->school_id;

        $query = LeaveRequest::with('staffProfile.user')
            ->whereHas('staffProfile', fn($q) => $q->where('school_id', $schoolId))
            ->orderByDesc('created_at');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('leave_type')) {
            $query->where('leave_type', $request->leave_type);
        }

        $leaves       = $query->paginate(15)->withQueryString();
        $pendingCount = LeaveRequest::whereHas('staffProfile', fn($q) => $q->where('school_id', $schoolId))
            ->where('status', 'pending')->count();

        return view('schooladmin.staff.leaves.index', compact('leaves', 'pendingCount'));
    }

    public function show(LeaveRequest $leave)
    {
        $leave->load('staffProfile.user', 'reviewer');
        return view('schooladmin.staff.leaves.show', compact('leave'));
    }

    public function approve(Request $request, LeaveRequest $leave)
    {
        $request->validate(['admin_notes' => 'nullable|string|max:500']);

        $leave->update([
            'status'      => 'approved',
            'admin_notes' => $request->admin_notes,
            'reviewed_by' => Auth::id(),
            'reviewed_at' => now(),
        ]);

        return redirect()->route('schooladmin.staff.leaves.index')
            ->with('success', "Leave request approved for {$leave->staffProfile->full_name}.");
    }

    public function reject(Request $request, LeaveRequest $leave)
    {
        $request->validate(['admin_notes' => 'required|string|max:500']);

        $leave->update([
            'status'      => 'rejected',
            'admin_notes' => $request->admin_notes,
            'reviewed_by' => Auth::id(),
            'reviewed_at' => now(),
        ]);

        return redirect()->route('schooladmin.staff.leaves.index')
            ->with('error', "Leave request rejected.");
    }
}
