<?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\AttendanceException;
use App\Modules\HR\Attendance\Repositories\AttendanceExceptionRepository;
use App\Modules\HR\Attendance\Requests\AttendanceExceptionIndexRequest;
use App\Modules\HR\Attendance\Requests\ReviewAttendanceExceptionRequest;
use App\Modules\HR\Attendance\Services\AttendanceExceptionReviewService;
use App\Modules\HR\Employees\Models\Employee;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class AttendanceExceptionsPageController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private readonly AttendanceExceptionRepository $exceptions,
        private readonly AttendanceExceptionReviewService $reviews,
    ) {}

    public function index(AttendanceExceptionIndexRequest $request): View
    {
        $this->authorize('viewAny', AttendanceException::class);
        $tenant = $this->tenant();
        $filters = $request->filters();
        $paginator = $this->exceptions->paginateForTenant((int) $tenant->id, $filters);

        return view('pages.hr.attendance.exceptions.index', [
            'paginator' => $paginator,
            'filters' => $filters,
            'employees' => Employee::query()
                ->where('tenant_id', $tenant->id)
                ->where('is_active', true)
                ->orderBy('full_name')
                ->get(['id', 'full_name']),
        ]);
    }

    public function resolve(ReviewAttendanceExceptionRequest $request, int $exception): RedirectResponse
    {
        $tenant = $this->tenant();
        $row = $this->exceptions->findForTenant((int) $tenant->id, $exception);
        abort_if($row === null, 404);
        $this->authorize('review', $row);
        $this->reviews->resolve($row, $request->user(), $request->validated('resolution_note'), $request);

        return redirect()
            ->route('hr.attendance.exceptions.index')
            ->with('status', __('attendance_exceptions.flash.resolved'));
    }

    public function ignore(ReviewAttendanceExceptionRequest $request, int $exception): RedirectResponse
    {
        $tenant = $this->tenant();
        $row = $this->exceptions->findForTenant((int) $tenant->id, $exception);
        abort_if($row === null, 404);
        $this->authorize('review', $row);
        $this->reviews->ignore($row, $request->user(), $request->validated('resolution_note'), $request);

        return redirect()
            ->route('hr.attendance.exceptions.index')
            ->with('status', __('attendance_exceptions.flash.ignored'));
    }

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

        return $t;
    }
}
