<?php
/**
 * Calendar Event Reminder Script
 * This script should be run periodically (e.g., daily) via cron job
 * to send reminders for upcoming calendar events.
 */

// Set default timezone to Africa Central Time (CAT, UTC+2) for Harare, Zimbabwe
date_default_timezone_set('Africa/Harare');

require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'config/rbac.php';
require_once 'includes/functions.php';
require_once 'includes/middleware.php';
require_once 'includes/notifications.php';

try {
    $db = getDB();

    // Get events that need reminders (events in the next 24 hours)
    $tomorrow = date('Y-m-d', strtotime('+1 day'));
    $stmt = $db->prepare("
        SELECT id, title, event_date, event_time
        FROM calendar_events
        WHERE event_date = ?
        ORDER BY event_time ASC
    ");
    $stmt->execute([$tomorrow]);
    $upcomingEvents = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($upcomingEvents)) {
        echo "No upcoming events found for tomorrow.\n";
        exit;
    }

    $remindersSent = 0;
    foreach ($upcomingEvents as $event) {
        echo "Sending reminder for event: {$event['title']} on {$event['event_date']} at {$event['event_time']}\n";

        // Send reminder notification
        if (sendCalendarNotification('event_reminder', $event['id'])) {
            $remindersSent++;
            echo "✓ Reminder sent for event ID: {$event['id']}\n";
        } else {
            echo "✗ Failed to send reminder for event ID: {$event['id']}\n";
        }
    }

    echo "\nSummary: Sent {$remindersSent} reminders out of " . count($upcomingEvents) . " upcoming events.\n";

} catch (Exception $e) {
    echo "Error sending calendar reminders: " . $e->getMessage() . "\n";
    exit(1);
}
?>