<?php
// cron_reminders.php - Run via system cron job
if (php_sapi_name() !== 'cli' && !isset($_GET['run_cron'])) {
    header("HTTP/1.1 403 Forbidden");
    exit("Direct access not allowed. Run via CLI.");
}

define('SECURE_ACCESS', true);
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/notification_helper.php';

try {
    // Query registrations starting within the next 24 hours that haven't had reminders sent
    $stmt_rem = $pdo->query("
        SELECT r.id as registration_id, r.user_id, e.title as event_title, e.location, e.start_date 
        FROM registrations r 
        JOIN events e ON r.event_id = e.id 
        WHERE r.reminder_sent = FALSE 
          AND e.start_date <= CURRENT_TIMESTAMP + INTERVAL '24 hours' 
          AND e.start_date > CURRENT_TIMESTAMP
    ");
    $pending_reminders = $stmt_rem->fetchAll();

    if (!empty($pending_reminders)) {
        $stmt_mark = $pdo->prepare("UPDATE registrations SET reminder_sent = TRUE WHERE id = ?");
        
        foreach ($pending_reminders as $rem) {
            // Mark as sent first to avoid race conditions or duplicates
            $stmt_mark->execute([$rem['registration_id']]);

            // Dispatch multichannel notification
            sendMultichannelNotification($rem['user_id'], 'event_reminder', [
                'event_title' => $rem['event_title'],
                'location' => $rem['location'],
                'start_date' => date('M d, H:i', strtotime($rem['start_date']))
            ]);
        }
    }
} catch (PDOException $e) {
    error_log("Reminder Intervention Error: " . $e->getMessage());
}
