<?php

namespace App\Modules\HR\EmployeeSelfService\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\EmployeeSelfService\Requests\MeStoreOvertimeRequestRequest;
use App\Modules\HR\EmployeeSelfService\Services\SelfEmployeeContextService;
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\Services\OvertimeCreatePageService;
use App\Modules\HR\Overtime\Services\OvertimeRequestService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MeOvertimeController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private readonly SelfEmployeeContextService $context,
        private readonly OvertimeRequestRepository $requests,
        private readonly OvertimeRequestService $submit,
        private readonly OvertimeCreatePageService $createPage,
    ) {}

    public function index(): View
    {
        $employee = $this->context->employee();
        $tenant = $this->tenant();

        return view('pages.me.overtime.index', [
            'paginator' => $this->requests->paginateForEmployee((int) $tenant->id, (int) $employee->id),
        ]);
    }

    public function create(Request $request): View
    {
        $this->authorize('create', OvertimeRequest::class);
        $employee = $this->context->employee();
        $date = $request->filled('attendance_date') ? (string) $request->query('attendance_date') : null;
        $suggested = $this->createPage->suggestedMinutes(
            (int) $this->tenant()->id,
            (int) $employee->id,
            $date,
        );

        return view('pages.me.overtime.create', [
            'selectedAttendanceDate' => $date,
            'suggestedOvertimeMinutes' => $suggested,
        ]);
    }

    public function store(MeStoreOvertimeRequestRequest $request): RedirectResponse
    {
        $employee = $this->context->employee();
        $v = $request->validated();
        $this->submit->submit(
            $this->tenant(),
            OvertimeRequestSubmitData::fromValidated([
                'employee_id' => (int) $employee->id,
                'attendance_date' => $v['attendance_date'],
                'overtime_minutes' => $v['overtime_minutes'],
                'reason' => $v['reason'] ?? null,
            ]),
            (int) $request->user()->id,
        );

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

    private function tenant(): Tenant
    {
        $t = auth()->user()?->tenant;
        abort_if($t === null, 403);

        return $t;
    }
}
