<?php

namespace App\Modules\HR\Recruitment\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Recruitment\DTOs\HiringWizardData;
use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter;
use App\Modules\HR\Recruitment\Requests\CompleteHiringWizardRequest;
use App\Modules\HR\Recruitment\Services\HiringWizardPageService;
use App\Modules\HR\Recruitment\Services\HiringWizardService;
use App\Modules\HR\Recruitment\Support\OfferLetterHiringGate;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class HiringWizardPageController extends Controller
{
    public function __construct(
        private readonly HiringWizardPageService $pages,
        private readonly HiringWizardService $wizard,
    ) {}

    public function index(Request $request): View
    {
        $this->authorize('viewAny', \App\Modules\HR\Recruitment\Models\RecruitmentHiring::class);

        return view('pages.hr.recruitment.hiring.index', [
            'offers' => $this->pages->paginateAccepted([
                'q' => $request->string('q')->toString() ?: null,
            ]),
        ]);
    }

    public function create(RecruitmentOfferLetter $offerLetter): View
    {
        $this->authorize('hire', $offerLetter);
        OfferLetterHiringGate::assertAccepted((string) $offerLetter->status);
        abort_if($offerLetter->employee_id !== null, 404);

        return view('pages.hr.recruitment.hiring.wizard', $this->pages->wizardContext($offerLetter));
    }

    public function store(CompleteHiringWizardRequest $request, RecruitmentOfferLetter $offerLetter): RedirectResponse
    {
        $hiring = $this->wizard->complete(
            $offerLetter,
            HiringWizardData::fromValidated($request->validated()),
            (int) $request->user()->id,
        );

        return redirect()
            ->route('hr.employees.edit', $hiring->employee_id)
            ->with('status', __('recruitment.hiring.flash.completed', [
                'ref' => $hiring->reference_code,
                'employee' => $hiring->employee?->employee_code,
            ]));
    }
}
