<?php

namespace App\Console\Commands;

use App\Models\SubscriptionVisit;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('app:auto-mark-absent-visits {--hours=24}')]
#[Description('Auto-mark visits as absent if partner did not mark attendance within N hours of scheduled date')]
class AutoMarkAbsentVisits extends Command
{
    public function handle()
    {
        $hours = (int) $this->option('hours');
        $cutoff = now()->subHours($hours)->startOfDay();

        $count = 0;
        SubscriptionVisit::where('attendance_status', 'pending')
            ->where('scheduled_date', '<', $cutoff)
            ->where('scheduled_date', '<', now()->startOfDay())
            ->chunkById(100, function ($visits) use (&$count) {
                foreach ($visits as $v) {
                    $v->update([
                        'attendance_status' => 'absent',
                        'auto_absent_marked' => true,
                        'auto_absent_at' => now(),
                        'attendance_note' => 'Auto-marked absent — partner did not mark attendance within 24 hours',
                    ]);
                    $count++;
                }
            });

        $this->info("Auto-marked $count visits as absent.");
        return 0;
    }
}
