<?php

namespace App\Http\Controllers;

use App\Models\LeaveRequest;
use App\Models\LeaveType;
use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LeaveRequestController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $user = Auth::user();
        $query = LeaveRequest::with(['employee', 'leaveType']);

        // If not admin, show only their own requests
        if (!$user->is_admin) {
            $employee = $user->employee;
            if ($employee) {
                $query->where('employee_id', $employee->id);
            } else {
                // If they are admin but don't have employee record, they see all
                // For now, let's just show all if no employee record is found (likely admin)
            }
        }

        $leaveRequests = $query->latest()->paginate(10);
        return view('leave_requests.index', compact('leaveRequests'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $employee = Auth::user()->employee;
        if (!$employee) {
            return redirect()->route('leave-requests.index')
                ->with('error', 'Only employees can request leave.');
        }

        $leaveTypes = LeaveType::where('active', true)->get();
        return view('leave_requests.create', compact('leaveTypes', 'employee'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $employee = Auth::user()->employee;
        if (!$employee) {
            return redirect()->route('leave-requests.index')
                ->with('error', 'Only employees can request leave.');
        }

        $request->validate([
            'leave_type_id' => 'required|exists:leave_types,id',
            'start_date' => 'required|date|after_or_equal:today',
            'end_date' => 'required|date|after_or_equal:start_date',
            'reason' => 'nullable|string',
        ]);

        $leaveRequest = new LeaveRequest($request->all());
        $leaveRequest->employee_id = $employee->id;
        $leaveRequest->status = 'pending';
        $leaveRequest->save();

        return redirect()->route('leave-requests.index')
            ->with('success', 'Leave request submitted successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(LeaveRequest $leaveRequest)
    {
        return view('leave_requests.show', compact('leaveRequest'));
    }

    /**
     * Update the specified resource in storage (for approval/rejection).
     */
    public function update(Request $request, LeaveRequest $leaveRequest)
    {
        $request->validate([
            'status' => 'required|in:approved,rejected',
        ]);

        $leaveRequest->update([
            'status' => $request->status,
            'approved_by' => Auth::id(),
            'approved_at' => now(),
        ]);

        return redirect()->route('leave-requests.index')
            ->with('success', 'Leave request ' . $request->status . ' successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(LeaveRequest $leaveRequest)
    {
        if ($leaveRequest->status !== 'pending') {
            return redirect()->route('leave-requests.index')
                ->with('error', 'Only pending leave requests can be deleted.');
        }

        $leaveRequest->delete();

        return redirect()->route('leave-requests.index')
            ->with('success', 'Leave request deleted successfully.');
    }
}
