<?php

namespace App\Modules\HR\EmployeeSelfService\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Attendance\Models\AttendanceCorrectionRequest;
use App\Modules\HR\Attendance\Repositories\AttendanceCorrectionRequestRepository;
use App\Modules\HR\Attendance\Repositories\AttendanceRecordRepository;
use App\Modules\HR\Attendance\Services\AttendanceCorrectionSubmissionService;
use App\Modules\HR\Attendance\Support\AttendanceCorrectionType;
use App\Modules\HR\EmployeeSelfService\Requests\MeStoreAttendanceCorrectionRequest;
use App\Modules\HR\EmployeeSelfService\Services\SelfEmployeeContextService;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MeAttendanceCorrectionController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private readonly SelfEmployeeContextService $context,
        private readonly AttendanceCorrectionRequestRepository $corrections,
        private readonly AttendanceRecordRepository $records,
        private readonly AttendanceCorrectionSubmissionService $submission,
    ) {}

    public function index(): View
    {
        $this->authorize('create', AttendanceCorrectionRequest::class);
        $employee = $this->context->employee();
        $tenant = $this->tenant();
        $paginator = $this->corrections->paginateForEmployee((int) $tenant->id, (int) $employee->id);

        return view('pages.me.attendance.corrections.index', compact('paginator'));
    }

    public function create(Request $request): View
    {
        $this->authorize('create', AttendanceCorrectionRequest::class);
        $employee = $this->context->employee();
        $tenant = $this->tenant();
        $to = CarbonImmutable::now()->toDateString();
        $from = CarbonImmutable::now()->subDays(60)->toDateString();
        $recordOptions = $this->records
            ->forEmployeeInRange((int) $tenant->id, (int) $employee->id, $from, $to)
            ->mapWithKeys(fn ($r) => [
                $r->id => $r->attendance_date?->format('Y-m-d').' — #'.$r->id,
            ])
            ->all();
        $selectedRecordId = array_key_exists((int) $request->integer('record'), $recordOptions)
            ? (int) $request->integer('record')
            : null;
        $selectedType = in_array($request->query('type'), AttendanceCorrectionType::all(), true)
            ? (string) $request->query('type')
            : null;

        return view('pages.me.attendance.corrections.create', [
            'recordOptions' => $recordOptions,
            'types' => AttendanceCorrectionType::all(),
            'selectedRecordId' => $selectedRecordId,
            'selectedType' => $selectedType,
        ]);
    }

    public function store(MeStoreAttendanceCorrectionRequest $request): RedirectResponse
    {
        $this->authorize('create', AttendanceCorrectionRequest::class);
        $this->submission->submit($request->user(), $request->validated());

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

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

        return $t;
    }
}
