<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreEmployeeSalaryAssignmentRequest;
use App\Models\EmployeeSalaryAssignment;
use App\Models\PayrollStructure;
use App\Models\User;
use App\Services\PayrollGenerationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class EmployeeSalaryAssignmentController extends Controller
{
    public function __construct(protected PayrollGenerationService $payrollService) {}

    public function index(): Response
    {
        $employees = User::where('type', 'employee')
            ->where('status', 'active')
            ->with(['employeeProfile.departmentRel', 'salaryAssignment.payrollStructure'])
            ->get();

        return Inertia::render('Admin/Payroll/Assignment/Index', [
            'employees' => $employees,
            'structures' => PayrollStructure::with('components.salaryComponent')->get(),
        ]);
    }

    /**
     * Live preview endpoint: returns calculated breakdown without persisting.
     */
    public function preview(Request $request): JsonResponse
    {
        $request->validate([
            'employee_id' => ['required', 'exists:users,id'],
            'payroll_structure_id' => ['required', 'exists:payroll_structures,id'],
            'gross_salary' => ['required', 'numeric', 'min:1'],
        ]);

        $structure = PayrollStructure::with('components.salaryComponent')->findOrFail($request->payroll_structure_id);

        $fakeAssignment = new EmployeeSalaryAssignment([
            'employee_id' => $request->employee_id,
            'payroll_structure_id' => $structure->id,
            'gross_salary' => $request->gross_salary,
        ]);
        $fakeAssignment->setRelation('payrollStructure', $structure);

        $breakdown = $this->payrollService->calculateBreakdown($fakeAssignment, now()->toDateString());

        return response()->json($breakdown);
    }

    public function store(StoreEmployeeSalaryAssignmentRequest $request)
    {
        $data = $request->validated();

        EmployeeSalaryAssignment::updateOrCreate(
            ['employee_id' => $data['employee_id']],
            $data
        );

        return back()->with('success', 'Salary assignment saved successfully.');
    }
}
