<?php

namespace App\Modules\HR\Overtime\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Overtime\DTOs\OvertimeRequestSubmitData;
use App\Modules\HR\Overtime\Models\OvertimeRequest;
use App\Modules\HR\Overtime\Repositories\OvertimeRequestRepository;
use App\Modules\HR\Overtime\Requests\StoreOvertimeRequestRequest;
use App\Modules\HR\Overtime\Services\OvertimeRequestService;
use App\Modules\HR\Overtime\Services\OvertimeReviewService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class OvertimeRequestsPageController extends Controller
{
    public function __construct(
        private readonly OvertimeRequestRepository $requests,
        private readonly OvertimeRequestService $submit,
        private readonly OvertimeReviewService $review,
    ) {}

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

        return view('pages.hr.overtime.index', [
            'requests' => $this->requests->paginateForTenant((int) $this->tenant()->id),
        ]);
    }

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

        return view('pages.hr.overtime.create', [
            'employees' => Employee::query()->where('tenant_id', $tenant->id)->orderBy('full_name')->get(),
        ]);
    }

    public function store(StoreOvertimeRequestRequest $request): RedirectResponse
    {
        $this->submit->submit(
            $this->tenant(),
            OvertimeRequestSubmitData::fromValidated($request->validated()),
            (int) $request->user()->id,
        );

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

    public function approve(int $overtimeRequest): RedirectResponse
    {
        $row = $this->findOrFail($overtimeRequest);
        $this->authorize('review', $row);
        $this->review->approve($row, request()->user());

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

    public function reject(int $overtimeRequest): RedirectResponse
    {
        $row = $this->findOrFail($overtimeRequest);
        $this->authorize('review', $row);
        $this->review->reject($row, request()->user());

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

    private function findOrFail(int $id): OvertimeRequest
    {
        $row = $this->requests->findForTenant((int) $this->tenant()->id, $id);
        abort_if($row === null, 404);

        return $row;
    }

    private function tenant(): \App\Modules\Admin\Tenancy\Models\Tenant
    {
        $t = auth()->user()?->tenant;
        abort_if($t === null, 403);

        return $t;
    }
}
