<?php
/**
 * Process due appointment reminders (email / SMS).
 * CLI:  php tools/send_reminders.php
 * Web:  ' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . APP_BASE . '/tools/send_reminders.php?key=local-dev
 * Cron example (every 5 min): php E:\xampp\htdocs\barbershop\tools\send_reminders.php
 */
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/reminders.php';

$isCli = PHP_SAPI === 'cli';
if (!$isCli) {
    $key = $_GET['key'] ?? '';
    if ($key !== 'local-dev') {
        http_response_code(403);
        header('Content-Type: text/plain');
        echo "Forbidden. Use ?key=local-dev or run via CLI.\n";
        exit;
    }
    header('Content-Type: text/plain; charset=utf-8');
}

$tenantId = null;
if ($isCli) {
    foreach ($argv as $arg) {
        if (str_starts_with($arg, '--tenant=')) {
            $tenantId = (int) substr($arg, 9);
        }
    }
} elseif (isset($_GET['tenant_id'])) {
    $tenantId = (int) $_GET['tenant_id'];
}

$summary = reminder_process_due(100, $tenantId);
$line = sprintf(
    "[%s] processed=%d sent=%d skipped=%d failed=%d\n",
    date('c'),
    $summary['processed'],
    $summary['sent'],
    $summary['skipped'],
    $summary['failed']
);
echo $line;
foreach ($summary['details'] as $d) {
    echo sprintf(
        "  #%d %s %s%s\n",
        $d['id'],
        $d['channel'] ?? '?',
        $d['status'],
        isset($d['error']) ? ' — ' . $d['error'] : ''
    );
}
