<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreLeaveRequest;
use App\Models\LeaveRequest;
use App\Models\LeaveType;
use App\Services\LeaveService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class LeaveRequestController extends Controller
{
    public function __construct(protected LeaveService $leaveService) {}

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): Response
    {
        $user = $request->user();
        $year = $request->get('year', now()->year);

        $leaveTypes = LeaveType::where('status', true)->get();

        $balances = $leaveTypes->map(function ($type) use ($user, $year) {
            $balance = $this->leaveService->getBalance($user, $type->id, $year);

            return [
                'id' => $type->id,
                'name' => $type->name,
                'color' => $type->color,
                'icon' => $type->icon,
                'total_allowance' => $balance->total_allowance,
                'used' => $balance->used,
                'remaining' => $balance->remaining,
            ];
        });

        $requests = LeaveRequest::with('leaveType')
            ->where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return Inertia::render('Employee/LeaveRequest/Index', [
            'balances' => $balances,
            'requests' => $requests,
            'leaveTypes' => $leaveTypes,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreLeaveRequest $request)
    {
        try {
            $this->leaveService->createRequest($request->validated(), $request->user());

            return back()->with('success', 'Leave request submitted successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
