<?php

namespace App\Modules\HR\Dashboard\Repositories;

use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeDocument;
use Carbon\CarbonImmutable;

class HrDashboardRepository
{
    public function totalEmployees(int $tenantId): int
    {
        return Employee::query()->where('tenant_id', $tenantId)->count();
    }

    public function activeEmployees(int $tenantId): int
    {
        return Employee::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->count();
    }

    public function expiringDocumentsCount(int $tenantId, int $withinDays = 30): int
    {
        $from = CarbonImmutable::now()->toDateString();
        $to = CarbonImmutable::now()->addDays($withinDays)->toDateString();

        return EmployeeDocument::query()
            ->whereHas('employee', fn ($q) => $q->where('tenant_id', $tenantId))
            ->whereNotNull('expires_at')
            ->whereDate('expires_at', '>=', $from)
            ->whereDate('expires_at', '<=', $to)
            ->count();
    }

    public function onProbationCount(int $tenantId): int
    {
        $today = CarbonImmutable::now()->toDateString();

        return Employee::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->whereNotNull('probation_end_date')
            ->whereDate('probation_end_date', '>=', $today)
            ->count();
    }
}
