<?php

namespace App\Modules\HR\Payroll\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Payroll\DTOs\SalaryStructureWriteData;
use App\Modules\HR\Payroll\Models\SalaryStructure;
use App\Modules\HR\Payroll\Requests\StoreSalaryStructureRequest;
use App\Modules\HR\Payroll\Requests\UpdateSalaryStructureRequest;
use App\Modules\HR\Payroll\Services\SalaryStructureService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SalaryStructurePageController extends Controller
{
    public function __construct(
        private readonly SalaryStructureService $service,
    ) {}

    public function index(Request $request): View
    {
        $this->authorize('viewAny', SalaryStructure::class);

        return view('pages.hr.salary-structures.index', [
            'structures' => $this->service->paginateForIndex($request),
        ]);
    }

    public function create(): View
    {
        $this->authorize('create', SalaryStructure::class);

        return view('pages.hr.salary-structures.create');
    }

    public function store(StoreSalaryStructureRequest $request): RedirectResponse
    {
        $this->service->store(SalaryStructureWriteData::fromValidated($request->validated()));

        return redirect()
            ->route('hr.salary-structures.index')
            ->with('status', __('salary_structures.flash.created'));
    }

    public function edit(SalaryStructure $salary_structure): View
    {
        $this->authorize('update', $salary_structure);

        $salary_structure->load('components');

        return view('pages.hr.salary-structures.edit', [
            'structure' => $salary_structure,
        ]);
    }

    public function update(UpdateSalaryStructureRequest $request, SalaryStructure $salary_structure): RedirectResponse
    {
        $this->service->update($salary_structure, SalaryStructureWriteData::fromValidated($request->validated()));

        return redirect()
            ->route('hr.salary-structures.index')
            ->with('status', __('salary_structures.flash.updated'));
    }

    public function deactivate(SalaryStructure $salary_structure): RedirectResponse
    {
        $this->authorize('deactivate', $salary_structure);
        $this->service->deactivate($salary_structure);

        return redirect()
            ->route('hr.salary-structures.index')
            ->with('status', __('salary_structures.flash.deactivated'));
    }
}
