<?php

namespace App\Http\Controllers\Admin;

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

class LeaveTypeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): Response
    {
        return Inertia::render('Admin/Leave/Types', [
            'leaveTypes' => LeaveType::all(),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:leave_types,name',
            'color' => 'required|string|max:7',
            'icon' => 'required|string|max:50',
            'is_paid' => 'required|boolean',
            'default_allowance' => 'required|integer|min:0',
        ]);

        LeaveType::create($validated);

        return back()->with('success', 'Leave type created successfully.');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, LeaveType $leaveType)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:leave_types,name,'.$leaveType->id,
            'color' => 'required|string|max:7',
            'icon' => 'required|string|max:50',
            'is_paid' => 'required|boolean',
            'default_allowance' => 'required|integer|min:0',
            'status' => 'required|boolean',
        ]);

        $leaveType->update($validated);

        return back()->with('success', 'Leave type updated successfully.');
    }

    /**
     * Remove the specified resource in storage.
     */
    public function destroy(LeaveType $leaveType)
    {
        // Check if there are any requests associated with this type
        if ($leaveType->leaveRequests()->exists()) {
            return back()->with('error', 'Cannot delete leave type that has associated requests. Deactivate it instead.');
        }

        $leaveType->delete();

        return back()->with('success', 'Leave type deleted successfully.');
    }
}
