<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StorePayrollStructureRequest;
use App\Http\Requests\Admin\UpdatePayrollStructureRequest;
use App\Models\PayrollStructure;
use App\Models\SalaryComponent;
use Inertia\Inertia;
use Inertia\Response;

class PayrollStructureController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Admin/Payroll/Structures/Index', [
            'structures' => PayrollStructure::with('components.salaryComponent')->get(),
            'salaryComponents' => SalaryComponent::where('status', 'active')->get(),
        ]);
    }

    public function store(StorePayrollStructureRequest $request)
    {
        $structure = PayrollStructure::create($request->only('name', 'description'));

        foreach ($request->validated()['components'] as $component) {
            $structure->components()->create($component);
        }

        return back()->with('success', 'Payroll structure created successfully.');
    }

    public function update(UpdatePayrollStructureRequest $request, PayrollStructure $structure)
    {
        $structure->update($request->only('name', 'description'));

        $structure->components()->delete();

        foreach ($request->validated()['components'] as $component) {
            $structure->components()->create($component);
        }

        return back()->with('success', 'Payroll structure updated successfully.');
    }

    public function destroy(PayrollStructure $structure)
    {
        if ($structure->salaryAssignments()->exists()) {
            return back()->with('error', 'Cannot delete a structure assigned to employees.');
        }

        $structure->delete();

        return back()->with('success', 'Payroll structure deleted successfully.');
    }
}
