<?php
declare(strict_types=1);

namespace App\Services;

use App\Repositories\Container;

/**
 * Auto-cancels appointments that are past their date and still PENDING (never confirmed).
 * Called on hub dashboard load — lightweight check, skips if already ran today.
 */
class AppointmentCleanup
{
    public static function autoCancelExpired(): int
    {
        // Throttle: only run once per hour via a simple session flag
        $lastRun = $_SESSION['_cleanup_ran'] ?? 0;
        if (time() - $lastRun < 3600) return 0;
        $_SESSION['_cleanup_ran'] = time();

        $appts = Container::appointments();
        $now   = (new \DateTimeImmutable('now'))->format(\DateTimeInterface::ATOM);
        $canceled = 0;

        $pending = $appts->byStatus('PENDING');
        foreach ($pending as $a) {
            $startAt = $a['start_at'] ?? '';
            if (!$startAt || $startAt >= $now) continue;

            // This appointment's time has passed and was never approved
            $appts->save(array_merge($a, [
                'status'           => 'CANCELED',
                'canceled_at'      => now_iso(),
                'canceled_by_id'   => 'SYSTEM',
                'canceled_by_name' => 'System (expired)',
            ]));
            Container::audit()->log('SYSTEM', 'AUTO_CANCEL_EXPIRED', 'appointment', $a['id']);
            $canceled++;
        }

        return $canceled;
    }
}
