<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreSalaryComponentRequest;
use App\Http\Requests\Admin\UpdateSalaryComponentRequest;
use App\Models\SalaryComponent;
use Inertia\Inertia;
use Inertia\Response;

class SalaryComponentController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Admin/Payroll/Components/Index', [
            'components' => SalaryComponent::orderBy('type')->orderBy('name')->get(),
        ]);
    }

    public function store(StoreSalaryComponentRequest $request)
    {
        SalaryComponent::create($request->validated());

        return back()->with('success', 'Salary component created successfully.');
    }

    public function update(UpdateSalaryComponentRequest $request, SalaryComponent $salaryComponent)
    {
        $data = $request->validated();

        if ($salaryComponent->status === 'active' && $data['status'] === 'inactive') {
            if ($salaryComponent->isUsedInAnyStructure()) {
                return back()->with('error', 'Cannot deactivate a component that is used in a payroll structure.');
            }
        }

        $salaryComponent->update($data);

        return back()->with('success', 'Salary component updated successfully.');
    }

    public function destroy(SalaryComponent $salaryComponent)
    {
        if ($salaryComponent->isUsedInAnyStructure()) {
            return back()->with('error', 'Cannot delete a component that is used in a payroll structure.');
        }

        $salaryComponent->delete();

        return back()->with('success', 'Salary component deleted successfully.');
    }
}
