<?php
/**
 * WhatsApp Reminder & Escalation Cron
 * Run every 5 minutes: */5 * * * * php /path/to/cron/whatsapp_reminders.php
 */
require __DIR__ . '/../api/bootstrap.php';
require __DIR__ . '/../api/services/WhatsAppService.php';

$pdo = db();
$config = $GLOBALS['CONFIG'];

echo date('Y-m-d H:i:s') . " — Running WhatsApp reminders...\n";

// Find overdue tickets
$stmt = $pdo->query("
    SELECT st.*, u.name AS assigned_name, sp.phone AS staff_phone
    FROM service_tickets st
    LEFT JOIN users u ON u.id = st.assigned_to
    LEFT JOIN staff_profiles sp ON sp.user_id = st.assigned_to
    WHERE st.status IN ('pending','assigned','in_progress')
    AND st.created_at < DATE_SUB(NOW(), INTERVAL 15 MINUTE)
    AND (st.last_reminder_at IS NULL OR st.last_reminder_at < DATE_SUB(NOW(), INTERVAL 15 MINUTE))
    ORDER BY FIELD(st.priority,'urgent','high','medium','low')
    LIMIT 20
");

$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
$reminded = 0;

foreach ($tickets as $ticket) {
    $minutesElapsed = round((time() - strtotime($ticket['created_at'])) / 60);

    // Determine escalation level
    $level = 0;
    if ($minutesElapsed >= 120) $level = 4;
    elseif ($minutesElapsed >= 60) $level = 3;
    elseif ($minutesElapsed >= 30) $level = 2;
    elseif ($minutesElapsed >= 15) $level = 1;

    // Update reminder timestamp and escalation
    $update = $pdo->prepare("UPDATE service_tickets SET last_reminder_at=NOW(), escalation_level=? WHERE id=?");
    $update->execute([$level, $ticket['id']]);

    // Send WhatsApp reminder if staff phone exists
    if ($ticket['staff_phone']) {
        $wa = new WhatsAppService($pdo, $config, $ticket['property_id']);
        $wa->sendReminder($ticket['staff_phone'], $ticket['assigned_name'], $ticket, $minutesElapsed);
    }

    $reminded++;
    echo "  Reminded: #{$ticket['ticket_number']} ({$minutesElapsed}m elapsed, level {$level})\n";
}

echo "Done. Reminded {$reminded} tickets.\n";
