<?php

namespace App\Modules\HR\EmploymentStatuses\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\EmploymentStatuses\DTOs\EmploymentStatusWriteData;
use App\Modules\HR\EmploymentStatuses\Models\EmploymentStatus;
use App\Modules\HR\EmploymentStatuses\Requests\StoreEmploymentStatusRequest;
use App\Modules\HR\EmploymentStatuses\Requests\UpdateEmploymentStatusRequest;
use App\Modules\HR\EmploymentStatuses\Services\EmploymentStatusService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class EmploymentStatusPageController extends Controller
{
    public function __construct(
        private readonly EmploymentStatusService $service,
    ) {}

    public function index(): View
    {
        return view('pages.hr.employment-statuses.index', [
            'statuses' => $this->service->list(),
        ]);
    }

    public function create(): View
    {
        return view('pages.hr.employment-statuses.create', [
            'colorOptions' => $this->colorOptions(),
        ]);
    }

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

        return redirect()
            ->route('hr.employment-statuses.index')
            ->with('status', __('employment_statuses.flash.created'));
    }

    public function edit(EmploymentStatus $employmentStatus): View
    {
        return view('pages.hr.employment-statuses.edit', [
            'status' => $employmentStatus,
            'colorOptions' => $this->colorOptions(),
        ]);
    }

    public function update(UpdateEmploymentStatusRequest $request, EmploymentStatus $employmentStatus): RedirectResponse
    {
        $this->service->update($employmentStatus, EmploymentStatusWriteData::fromValidated($request->validated()));

        return redirect()
            ->route('hr.employment-statuses.index')
            ->with('status', __('employment_statuses.flash.updated'));
    }

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

        return redirect()
            ->route('hr.employment-statuses.index')
            ->with('status', __('employment_statuses.flash.deactivated'));
    }

    /**
     * @return array<string, string>
     */
    private function colorOptions(): array
    {
        $colors = config('hr_employment_statuses.allowed_colors', []);
        $options = [];
        foreach ($colors as $color) {
            $options[$color] = __('employment_statuses.colors.'.$color);
        }

        return $options;
    }
}
