<?php

namespace App\Http\Controllers\Teacher;

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

class LeaveRequestController extends Controller
{
    /** Teacher views their own leave history */
    public function index()
    {
        $profile = Auth::user()->staffProfile;

        if (!$profile) {
            return view('teacher.leaves.index', ['leaves' => collect(), 'hasProfile' => false]);
        }

        $leaves = $profile->leaveRequests()->orderByDesc('created_at')->paginate(10);

        return view('teacher.leaves.index', compact('leaves'))->with('hasProfile', true);
    }

    /** Teacher submits a new leave request */
    public function store(Request $request)
    {
        $profile = Auth::user()->staffProfile;

        if (!$profile) {
            return back()->with('error', 'Your staff profile has not been set up yet. Please contact your school administrator.');
        }

        $data = $request->validate([
            'leave_type' => 'required|in:sick,annual,maternity,paternity,emergency,other',
            'start_date' => 'required|date|after_or_equal:today',
            'end_date'   => 'required|date|after_or_equal:start_date',
            'reason'     => 'required|string|max:1000',
        ]);

        $start = \Carbon\Carbon::parse($data['start_date']);
        $end   = \Carbon\Carbon::parse($data['end_date']);
        $days  = $start->diffInWeekdays($end) + 1;

        $profile->leaveRequests()->create([
            'leave_type'    => $data['leave_type'],
            'start_date'    => $data['start_date'],
            'end_date'      => $data['end_date'],
            'days_requested'=> $days,
            'reason'        => $data['reason'],
            'status'        => 'pending',
        ]);

        return redirect()->route('teacher.leaves.index')
            ->with('success', 'Leave request submitted. The school admin will review it shortly.');
    }
}
