<?php

namespace App\Modules\HR\Attendance\Repositories;

use App\Modules\HR\Attendance\Models\AttendanceRecord;
use App\Modules\HR\Attendance\Support\AttendanceRecordStatus;
use App\Modules\HR\Leave\Models\LeaveRequest;
use App\Modules\HR\Leave\Support\LeaveRequestStatus;
use Carbon\CarbonImmutable;

class AttendanceDashboardRepository
{
    public function presentTodayCount(int $tenantId): int
    {
        $date = CarbonImmutable::now()->toDateString();

        $v = AttendanceRecord::query()
            ->where('tenant_id', $tenantId)
            ->whereDate('attendance_date', $date)
            ->whereIn('status', [
                AttendanceRecordStatus::PRESENT,
                AttendanceRecordStatus::LATE,
                AttendanceRecordStatus::HALF_DAY,
            ])
            ->selectRaw('COUNT(DISTINCT employee_id) as c')
            ->value('c');

        return (int) ($v ?? 0);
    }

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

        $v = AttendanceRecord::query()
            ->where('tenant_id', $tenantId)
            ->whereDate('attendance_date', $date)
            ->where('status', AttendanceRecordStatus::ABSENT)
            ->selectRaw('COUNT(DISTINCT employee_id) as c')
            ->value('c');

        return (int) ($v ?? 0);
    }

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

        $v = AttendanceRecord::query()
            ->where('tenant_id', $tenantId)
            ->whereDate('attendance_date', $date)
            ->where('status', AttendanceRecordStatus::LATE)
            ->selectRaw('COUNT(DISTINCT employee_id) as c')
            ->value('c');

        return (int) ($v ?? 0);
    }

    public function pendingLeaveRequestsCount(int $tenantId): int
    {
        return LeaveRequest::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('status', [LeaveRequestStatus::PENDING, LeaveRequestStatus::MANAGER_APPROVED])
            ->count();
    }

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

        return LeaveRequest::query()
            ->where('tenant_id', $tenantId)
            ->where('status', LeaveRequestStatus::HR_APPROVED)
            ->whereDate('start_date', '<=', $date)
            ->whereDate('end_date', '>=', $date)
            ->count();
    }
}
