<?php

namespace App\Jobs;

use App\Enums\Permission;
use App\Models\Attendance;
use App\Models\LeaveRequest;
use App\Models\User;
use App\Services\NotificationService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendAttendanceReminderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;

    public function handle(): void
    {
        $today = now()->toDateString();

        $users = User::query()
            ->select(['id'])
            ->active()
            ->whereHas('roles', function ($q) {
                $q->whereHas('permissions', fn($pq) => $pq->where('name', Permission::ATTENDANCES_CREATE->value));
            })
            ->whereHas('employee')
            ->get();

        $eligibleUsers = $users->filter(function (User $user) use ($today) {
            $employee = $user->employee;

            if (! $employee) {
                return false;
            }

            $hasAttendedToday = Attendance::where('employee_id', $employee->id)
                ->where('attendance_date', $today)
                ->exists();

            if ($hasAttendedToday) {
                return false;
            }

            $isOnLeave = LeaveRequest::approved()
                ->where('employee_id', $employee->id)
                ->where('start_date', '<=', $today)
                ->where('end_date', '>=', $today)
                ->exists();

            return ! $isOnLeave;
        });

        if ($eligibleUsers->isEmpty()) {
            return;
        }

        NotificationService::notifyUsers(
            $eligibleUsers,
            'Reminder Presensi',
            'Selamat pagi! Jangan lupa untuk melakukan presensi masuk hari ini.',
            route('admin.hr.attendances.index'),
        );
    }
}
