<?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\AttendanceRecord;
use App\Modules\HR\Attendance\Requests\AttendanceMonthlyReportRequest;
use App\Modules\HR\Attendance\Services\AttendanceMonthlyReportService;
use App\Modules\HR\Employees\Models\Employee;
use Carbon\CarbonImmutable;
use Illuminate\View\View;

class AttendanceMonthlyReportPageController extends Controller
{
    public function index(
        AttendanceMonthlyReportRequest $request,
        AttendanceMonthlyReportService $reports,
    ): View {
        $this->authorize('viewAny', AttendanceRecord::class);
        $tenant = $this->tenant();
        $month = CarbonImmutable::parse($request->monthOrDefault())->startOfMonth();
        $employeeId = $request->employeeIdOrNull();
        $summary = null;
        $employee = null;
        if ($employeeId !== null) {
            $employee = Employee::query()
                ->where('tenant_id', $tenant->id)
                ->whereKey($employeeId)
                ->firstOrFail();
            $summary = $reports->employeeMonthSummary($tenant, $employeeId, $month);
        }

        return view('pages.hr.attendance.monthly-report', [
            'month' => $month->format('Y-m'),
            'employeeId' => $employeeId,
            'employee' => $employee,
            'summary' => $summary,
        ]);
    }

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

        return $t;
    }
}
