<?php

namespace App\Modules\HR\Positions\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Departments\Repositories\DepartmentRepository;
use App\Modules\HR\Organization\Repositories\JobGradeRepository;
use App\Modules\HR\Positions\DTOs\PositionWriteData;
use App\Modules\HR\Positions\Models\Position;
use App\Modules\HR\Positions\Requests\StorePositionRequest;
use App\Modules\HR\Positions\Requests\UpdatePositionRequest;
use App\Modules\HR\Positions\Services\PositionService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PositionPageController extends Controller
{
    public function __construct(
        private readonly PositionService $service,
        private readonly DepartmentRepository $departments,
        private readonly JobGradeRepository $jobGrades,
    ) {}

    public function index(Request $request): View
    {
        return view('pages.hr.positions.index', [
            'positions' => $this->service->paginateForIndex($request),
        ]);
    }

    public function create(): View
    {
        return view('pages.hr.positions.create', [
            'departmentOptions' => $this->departments->listForSelect(),
            'jobGradeOptions' => $this->jobGrades->listForSelect(),
        ]);
    }

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

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

    public function edit(Position $position): View
    {
        return view('pages.hr.positions.edit', [
            'position' => $position,
            'departmentOptions' => $this->departments->listForSelect(),
            'jobGradeOptions' => $this->jobGrades->listForSelect(),
        ]);
    }

    public function update(UpdatePositionRequest $request, Position $position): RedirectResponse
    {
        $this->service->update($position, PositionWriteData::fromValidated($request->validated()));

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

    public function deactivate(Position $position): RedirectResponse
    {
        $this->service->deactivate($position);

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