<?php

namespace App\Modules\HR\Attendance\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\Requests\AttendanceCorrectionIndexRequest;
use App\Modules\HR\Attendance\Requests\ReviewAttendanceCorrectionRequest;
use App\Modules\HR\Attendance\Services\AttendanceCorrectionReviewService;
use App\Modules\HR\Attendance\Support\AttendanceCorrectionStatus;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class AttendanceCorrectionRequestsPageController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private readonly AttendanceCorrectionRequestRepository $corrections,
        private readonly AttendanceCorrectionReviewService $reviews,
    ) {}

    public function index(AttendanceCorrectionIndexRequest $request): View
    {
        $this->authorize('viewAny', AttendanceCorrectionRequest::class);
        $tenant = $this->tenant();
        $status = $request->statusFilter();
        $paginator = $this->corrections->paginateForTenant((int) $tenant->id, $status);

        return view('pages.hr.attendance.corrections.index', [
            'paginator' => $paginator,
            'status' => (string) $request->input('status', AttendanceCorrectionStatus::PENDING),
        ]);
    }

    public function approve(ReviewAttendanceCorrectionRequest $request, int $correction): RedirectResponse
    {
        $tenant = $this->tenant();
        $row = $this->corrections->findForTenant((int) $tenant->id, $correction);
        abort_if($row === null, 404);
        $this->authorize('review', $row);
        $this->reviews->approve($row, $request->user(), $request->validated('reviewer_note'));

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

    public function reject(ReviewAttendanceCorrectionRequest $request, int $correction): RedirectResponse
    {
        $tenant = $this->tenant();
        $row = $this->corrections->findForTenant((int) $tenant->id, $correction);
        abort_if($row === null, 404);
        $this->authorize('review', $row);
        $this->reviews->reject($row, $request->user(), $request->validated('reviewer_note'));

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

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

        return $t;
    }
}
