<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\LeaveType;
use App\Support\FormTextRules;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LeaveTypeController extends Controller
{
    public function index()
    {
        $leaveTypes = LeaveType::orderBy('name')->paginate(15);
        return view('leave-types.index', compact('leaveTypes'));
    }

    public function create()
    {
        return view('leave-types.create');
    }

    public function store(Request $request)
    {
        $companyId = Auth::user()?->company_id;
        $validated = $request->validate([
            'name' => FormTextRules::notNumericOnly(true, 191),
            'is_paid' => 'boolean',
            'total_leaves' => 'required|integer|min:0',
            'count_type' => 'nullable|string|in:same_for_all,by_grade,unlimited',
        ], FormTextRules::messages());
        $validated['is_paid'] = $request->boolean('is_paid');
        $validated['count_type'] = $validated['count_type'] ?? 'same_for_all';
        $validated['company_id'] = $companyId;
        LeaveType::create($validated);
        return redirect()->route('leave-types.index')->with('success', 'Leave type created successfully.');
    }
}
