<?php
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/helpers/notification.php';

$db = Database::getInstance();

try {
    // Find scheduled appointments starting within the next hour that have not yet received a reminder
    $rows = $db->getAll(
        "SELECT id
         FROM appointments
         WHERE status = 'scheduled'
           AND zoom_start_time IS NOT NULL
           AND zoom_start_time BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 1 HOUR)
           AND (reminder_sent_at IS NULL)",
        []
    );

    $processed = 0;

    foreach ($rows as $row) {
        $appointmentId = (int)$row['id'];

        if ($appointmentId <= 0) {
            continue;
        }

        if (function_exists('sendAppointmentReminderNotification')) {
            sendAppointmentReminderNotification($appointmentId);
        }

        $db->update('appointments', [
            'reminder_sent_at' => formatDate(),
        ], 'id = ?', [$appointmentId]);

        $processed++;
    }

    echo json_encode(['success' => true, 'processed' => $processed]);
    exit;
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    exit;
}
