<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\Hr\StoreGratuityRequest;
use App\Models\Employee;
use App\Models\EmployeeGratuity;
use App\Models\FinalSettlement;
use App\Services\GratuityService;
use Illuminate\Http\Request;

class GratuityController extends Controller
{
    public function __construct(protected GratuityService $gratuityService) {}

    public function index(Request $request)
    {
        $employees = Employee::where('status', 'active')->with('currentSalary')->orderBy('full_name')->get();
        $estimates = EmployeeGratuity::with('employee')->latest()->paginate(20);
        $settlements = FinalSettlement::with('employee')->latest()->limit(20)->get();

        return view('tenant.hr.gratuity.index', compact('employees', 'estimates', 'settlements'));
    }

    public function store(StoreGratuityRequest $request, int $employeeId)
    {
        $employee = Employee::findOrFail($employeeId);
        $this->gratuityService->estimate($employee, $request->validated(), $request->user());

        return back()->with('status', 'Gratuity estimate created for authorized HR review.');
    }

    public function approve(Request $request, int $id)
    {
        abort_unless($request->user()->hasPermission('gratuity.approve'), 403);
        $validated = $request->validate(['approved_amount' => ['required', 'numeric', 'min:0']]);
        $gratuity = EmployeeGratuity::findOrFail($id);
        $this->gratuityService->approve($gratuity, (float) $validated['approved_amount'], $request->user());

        return back()->with('status', 'Gratuity approved.');
    }

    public function settlement(Request $request, int $id)
    {
        abort_unless($request->user()->hasPermission('gratuity.approve'), 403);
        $validated = $request->validate([
            'salary_due' => ['nullable', 'numeric', 'min:0'],
            'leave_salary' => ['nullable', 'numeric', 'min:0'],
            'other_earnings' => ['nullable', 'numeric', 'min:0'],
            'other_deductions' => ['nullable', 'numeric', 'min:0'],
        ]);
        $gratuity = EmployeeGratuity::with('employee.loans')->findOrFail($id);
        $this->gratuityService->createFinalSettlement($gratuity, $validated, $request->user());

        return back()->with('status', 'Final settlement statement created.');
    }
}
