<?php

namespace App\Modules\HR\Attendance\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Attendance\Repositories\AttendanceImportRepository;
use App\Modules\HR\Attendance\Requests\AttendanceImportUploadRequest;
use App\Modules\HR\Attendance\Services\AttendanceImportService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class AttendanceImportController extends Controller
{
    public function index(): View
    {
        return view('pages.hr.attendance.import');
    }

    public function preview(
        AttendanceImportUploadRequest $request,
        AttendanceImportService $service,
    ): RedirectResponse {
        $import = $service->preview(
            $this->tenantId(),
            (int) $request->user()->id,
            $request->file('file'),
        );

        return redirect()->route('hr.attendance.import.show', $import);
    }

    public function show(int $import, AttendanceImportRepository $imports): View
    {
        $row = $imports->find($this->tenantId(), $import);
        abort_if($row === null, 404);

        return view('pages.hr.attendance.import', ['import' => $row]);
    }

    public function commit(
        int $import,
        AttendanceImportRepository $imports,
        AttendanceImportService $service,
    ): RedirectResponse {
        $row = $imports->find($this->tenantId(), $import);
        abort_if($row === null, 404);
        $service->commit($row, (int) request()->user()->id);

        return redirect()->route('hr.attendance.index')->with('status', __('attendance.import.committed'));
    }

    private function tenantId(): int
    {
        $id = auth()->user()?->tenant_id;
        abort_if($id === null, 403);

        return (int) $id;
    }
}
