<?php

namespace App\Modules\HR\EmployeeSelfService\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Attendance\Services\SelfAttendancePunchService;
use App\Modules\HR\EmployeeSelfService\Requests\MeAttendanceIndexRequest;
use App\Modules\HR\EmployeeSelfService\Requests\SelfAttendancePunchRequest;
use App\Modules\HR\EmployeeSelfService\Services\SelfAttendancePageService;
use App\Modules\HR\EmployeeSelfService\Services\SelfEmployeeContextService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class MeAttendanceController extends Controller
{
    public function __construct(
        private readonly SelfEmployeeContextService $context,
        private readonly SelfAttendancePageService $page,
        private readonly SelfAttendancePunchService $punches,
    ) {}

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

        return view('pages.me.attendance.index', $this->page->data($tenant, $employee, $request));
    }

    public function checkIn(SelfAttendancePunchRequest $request): RedirectResponse
    {
        $this->punches->checkIn($request->user(), $this->tenant(), $this->context->employee());

        return back()->with('status', __('attendance.self.checked_in'));
    }

    public function checkOut(SelfAttendancePunchRequest $request): RedirectResponse
    {
        $this->punches->checkOut($request->user(), $this->tenant(), $this->context->employee());

        return back()->with('status', __('attendance.self.checked_out'));
    }

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

        return $t;
    }
}
