<?php
// ─────────────────────────────────────────────────────────────
//  cron/send-reminders.php
//
//  Sends 24h and 1h appointment reminder emails.
//
//  HOW TO SET UP (cPanel Cron Jobs):
//  ──────────────────────────────────────────────────────────
//  Run every 15 minutes:
//    */15 * * * * php /home/youruser/public_html/formbuilder/cron/send-reminders.php >> /home/youruser/logs/reminders.log 2>&1
//
//  Or call via HTTP (protected by CRON_SECRET):
//    */15 * * * * curl -s "https://yourdomain.com/formbuilder/cron/send-reminders.php?secret=YOUR_SECRET"
//
//  Set CRON_SECRET in config.php:
//    define('CRON_SECRET', 'some_long_random_string_here');
// ─────────────────────────────────────────────────────────────

// Guard: only run from CLI or with correct secret
$isCli = php_sapi_name() === 'cli';
if (!$isCli) {
    require_once dirname(__DIR__) . '/config.php';
    $secret = defined('CRON_SECRET') ? CRON_SECRET : '';
    $given  = $_GET['secret'] ?? '';
    if (!$secret || !hash_equals($secret, $given)) {
        http_response_code(403);
        echo json_encode(['ok' => false, 'error' => 'Forbidden']);
        exit;
    }
}

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

$sent24 = 0;
$sent1h = 0;
$errors = 0;
$log    = [];

function log_line(string $msg): void {
    global $log;
    $line = '[' . date('Y-m-d H:i:s') . '] ' . $msg;
    $log[] = $line;
    echo $line . PHP_EOL;
}

log_line('Reminder cron started.');

// ── 24-hour reminders ─────────────────────────────────────────
// Appointments starting in 23–25 hours that haven't been reminded
$stmt24 = db()->query(
    "SELECT a.id, a.ref, a.start_datetime,
            c.name AS customer_name, c.email AS customer_email,
            s.name AS service_name,
            p.name AS provider_name, p.email AS provider_email
     FROM bk_appointments a
     JOIN bk_customers c ON c.id = a.customer_id
     JOIN bk_services  s ON s.id = a.service_id
     JOIN bk_providers p ON p.id = a.provider_id
     WHERE a.status IN ('pending','confirmed')
       AND a.start_datetime BETWEEN DATE_ADD(NOW(), INTERVAL 23 HOUR)
                                AND DATE_ADD(NOW(), INTERVAL 25 HOUR)
       AND a.reminder_24h_sent = 0"
);

foreach ($stmt24->fetchAll() as $appt) {
    $apptDate = date('D, d M Y \a\t g:ia', strtotime($appt['start_datetime']));
    $portalUrl = defined('APP_URL') ? APP_URL . '/customer/dashboard.php' : '#';
    $html = "
        <h2 style=\"font-family:sans-serif;color:#111\">Reminder: Your appointment is tomorrow</h2>
        <p style=\"font-family:sans-serif\">Hi {$appt['customer_name']},</p>
        <p style=\"font-family:sans-serif\">Just a friendly reminder about your upcoming appointment:</p>
        <table style=\"border-collapse:collapse;margin:16px 0\">
            <tr><td style=\"padding:6px 12px 6px 0;color:#666;font-family:sans-serif\"><strong>Service:</strong></td><td style=\"font-family:sans-serif\">{$appt['service_name']}</td></tr>
            <tr><td style=\"padding:6px 12px 6px 0;color:#666;font-family:sans-serif\"><strong>Provider:</strong></td><td style=\"font-family:sans-serif\">{$appt['provider_name']}</td></tr>
            <tr><td style=\"padding:6px 12px 6px 0;color:#666;font-family:sans-serif\"><strong>Date &amp; Time:</strong></td><td style=\"font-family:sans-serif\"><strong>{$apptDate}</strong></td></tr>
            <tr><td style=\"padding:6px 12px 6px 0;color:#666;font-family:sans-serif\"><strong>Reference:</strong></td><td style=\"font-family:mono,monospace\">{$appt['ref']}</td></tr>
        </table>
        <p style=\"font-family:sans-serif\">Need to cancel or reschedule?
           <a href=\"{$portalUrl}\" style=\"color:#e09500\">Visit your Member Portal →</a></p>
    ";
    $text = "Reminder: {$appt['service_name']} with {$appt['provider_name']} — {$apptDate} (Ref: {$appt['ref']}).\nManage at: {$portalUrl}";
    $subject = "Reminder: Your appointment tomorrow — {$appt['service_name']}";

    try {
        send_mail($appt['customer_email'], $appt['customer_name'], $subject, $html, $text);
        db()->prepare('UPDATE bk_appointments SET reminder_24h_sent=1 WHERE id=?')->execute([$appt['id']]);
        $sent24++;
        log_line("24h reminder sent to {$appt['customer_email']} for appt #{$appt['id']} ({$appt['ref']})");
    } catch (\Throwable $e) {
        $errors++;
        log_line("ERROR sending 24h reminder for appt #{$appt['id']}: " . $e->getMessage());
    }
}

// ── 1-hour reminders ──────────────────────────────────────────
// Appointments starting in 55–65 minutes that haven't had 1h reminder
$stmt1h = db()->query(
    "SELECT a.id, a.ref, a.start_datetime,
            c.name AS customer_name, c.email AS customer_email,
            s.name AS service_name,
            p.name AS provider_name
     FROM bk_appointments a
     JOIN bk_customers c ON c.id = a.customer_id
     JOIN bk_services  s ON s.id = a.service_id
     JOIN bk_providers p ON p.id = a.provider_id
     WHERE a.status IN ('pending','confirmed')
       AND a.start_datetime BETWEEN DATE_ADD(NOW(), INTERVAL 55 MINUTE)
                                AND DATE_ADD(NOW(), INTERVAL 65 MINUTE)
       AND a.reminder_1h_sent = 0"
);

foreach ($stmt1h->fetchAll() as $appt) {
    $apptDate = date('D, d M Y \a\t g:ia', strtotime($appt['start_datetime']));
    $html = "
        <h2 style=\"font-family:sans-serif;color:#111\">Starting in 1 hour</h2>
        <p style=\"font-family:sans-serif\">Hi {$appt['customer_name']},</p>
        <p style=\"font-family:sans-serif\">Your appointment starts in about <strong>1 hour</strong>.</p>
        <table style=\"border-collapse:collapse;margin:16px 0\">
            <tr><td style=\"padding:6px 12px 6px 0;color:#666;font-family:sans-serif\"><strong>Service:</strong></td><td style=\"font-family:sans-serif\">{$appt['service_name']}</td></tr>
            <tr><td style=\"padding:6px 12px 6px 0;color:#666;font-family:sans-serif\"><strong>Provider:</strong></td><td style=\"font-family:sans-serif\">{$appt['provider_name']}</td></tr>
            <tr><td style=\"padding:6px 12px 6px 0;color:#666;font-family:sans-serif\"><strong>Time:</strong></td><td style=\"font-family:sans-serif\"><strong>{$apptDate}</strong></td></tr>
        </table>
        <p style=\"font-family:sans-serif\">See you soon! 👋</p>
    ";
    $text = "Starting in 1 hour: {$appt['service_name']} with {$appt['provider_name']} — {$apptDate}";
    $subject = "Starting soon: {$appt['service_name']} in 1 hour";

    try {
        send_mail($appt['customer_email'], $appt['customer_name'], $subject, $html, $text);
        db()->prepare('UPDATE bk_appointments SET reminder_1h_sent=1 WHERE id=?')->execute([$appt['id']]);
        $sent1h++;
        log_line("1h reminder sent to {$appt['customer_email']} for appt #{$appt['id']} ({$appt['ref']})");
    } catch (\Throwable $e) {
        $errors++;
        log_line("ERROR sending 1h reminder for appt #{$appt['id']}: " . $e->getMessage());
    }
}

log_line("Done. sent_24h={$sent24} sent_1h={$sent1h} errors={$errors}");

if (!$isCli) {
    header('Content-Type: application/json');
    echo json_encode(['ok' => true, 'sent_24h' => $sent24, 'sent_1h' => $sent1h, 'errors' => $errors]);
}
