<?php
// ─────────────────────────────────────────────────────────────
//  cron.php — Appointment reminder sender
//  Called by server cron or Namecheap cPanel cron job.
//
//  SETUP (Namecheap cPanel → Cron Jobs):
//    Command : curl -s "https://yourdomain.com/formbuilder/cron.php?key=YOUR_CRON_SECRET" > /dev/null
//    Schedule: Every 30 minutes  →  */30 * * * *
//
//  Set CRON_SECRET in config.php:
//    define('CRON_SECRET', 'replace-with-a-long-random-string');
//
//  To test manually: visit /cron.php?key=YOUR_CRON_SECRET in your browser.
// ─────────────────────────────────────────────────────────────

require_once __DIR__ . '/lib.php';
require_once __DIR__ . '/lib/BookingEngine.php';

// ── Auth ─────────────────────────────────────────────────────
$key = $_GET['key'] ?? '';
if (!defined('CRON_SECRET') || !$key || !hash_equals(CRON_SECRET, $key)) {
    http_response_code(403);
    die('Forbidden');
}

// ── Init booking tables (idempotent) ─────────────────────────
init_booking_db();

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

// ── 24h reminders ────────────────────────────────────────────
// Appointments starting in 23–25 hours that haven't been reminded yet
$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
     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) {
    $fmtDate = date('D, d M Y \a\t g:ia', strtotime($appt['start_datetime']));
    $html = "
        <h2>Reminder: Your appointment tomorrow</h2>
        <p>Hi {$appt['customer_name']},</p>
        <p>This is a reminder that you have an appointment tomorrow.</p>
        <table>
            <tr><td><strong>Service:</strong></td><td>{$appt['service_name']}</td></tr>
            <tr><td><strong>Provider:</strong></td><td>{$appt['provider_name']}</td></tr>
            <tr><td><strong>Date &amp; Time:</strong></td><td>{$fmtDate}</td></tr>
            <tr><td><strong>Reference:</strong></td><td>{$appt['ref']}</td></tr>
        </table>
        <p>Need to cancel or reschedule? Visit your <a href=\"" . APP_URL . "/customer/dashboard.php\">Member Portal</a>.</p>";
    $text = "Reminder: {$appt['service_name']} with {$appt['provider_name']} — {$fmtDate} (Ref: {$appt['ref']})";
    try {
        send_mail($appt['customer_email'], $appt['customer_name'],
            "Reminder: Your appointment tomorrow — {$appt['service_name']}", $html, $text);
        db()->prepare('UPDATE bk_appointments SET reminder_24h_sent=1 WHERE id=?')
            ->execute([$appt['id']]);
        $sent24++;
        $log[] = "24h: {$appt['ref']} → {$appt['customer_email']}";
    } catch (\Throwable $e) {
        $errors++;
        $log[] = "24h ERROR {$appt['ref']}: " . $e->getMessage();
        error_log("Cron 24h reminder error [{$appt['ref']}]: " . $e->getMessage());
    }
}

// ── 1h reminders ─────────────────────────────────────────────
// Appointments starting in 55–65 minutes that haven't been reminded yet
$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) {
    $fmtDate = date('D, d M Y \a\t g:ia', strtotime($appt['start_datetime']));
    $html = "
        <h2>Your appointment is in 1 hour</h2>
        <p>Hi {$appt['customer_name']},</p>
        <p>Just a heads-up — your appointment starts in about an hour.</p>
        <table>
            <tr><td><strong>Service:</strong></td><td>{$appt['service_name']}</td></tr>
            <tr><td><strong>Provider:</strong></td><td>{$appt['provider_name']}</td></tr>
            <tr><td><strong>Time:</strong></td><td>{$fmtDate}</td></tr>
            <tr><td><strong>Reference:</strong></td><td>{$appt['ref']}</td></tr>
        </table>
        <p><a href=\"" . APP_URL . "/customer/dashboard.php\">View your booking →</a></p>";
    $text = "Starting in 1 hour: {$appt['service_name']} with {$appt['provider_name']} — {$fmtDate}";
    try {
        send_mail($appt['customer_email'], $appt['customer_name'],
            "Starting soon: {$appt['service_name']} in 1 hour", $html, $text);
        db()->prepare('UPDATE bk_appointments SET reminder_1h_sent=1 WHERE id=?')
            ->execute([$appt['id']]);
        $sent1h++;
        $log[] = " 1h: {$appt['ref']} → {$appt['customer_email']}";
    } catch (\Throwable $e) {
        $errors++;
        $log[] = " 1h ERROR {$appt['ref']}: " . $e->getMessage();
        error_log("Cron 1h reminder error [{$appt['ref']}]: " . $e->getMessage());
    }
}

// ── Response ─────────────────────────────────────────────────
$result = [
    'ok'       => true,
    'ran_at'   => date('Y-m-d H:i:s'),
    'sent_24h' => $sent24,
    'sent_1h'  => $sent1h,
    'errors'   => $errors,
    'log'      => $log,
];

header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
