<?php
/**
 * api/timetable-notify.php
 * ─────────────────────────────────────────────────────────────────────
 * Timetable-based Web Push Notifications
 *
 * Run this via cron every minute:
 *   * * * * * php /path/to/studytrack/api/timetable-notify.php >> /var/log/tt-notify.log 2>&1
 *
 * OR call via HTTPS with a secret key (for shared-hosting cron):
 *   https://yourdomain.com/studytrack/api/timetable-notify.php?cron_key=YOUR_CRON_KEY
 *
 * Sends TWO notifications per timetable slot:
 *   1. 15 minutes before start  → "⏰ Upcoming: <label> in 15 min"
 *   2. At exact start time      → "📚 Starting now: <label>"
 *
 * Uses timetable_notify_log to prevent duplicate sends.
 * ─────────────────────────────────────────────────────────────────────
 */

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/push-send.php';  // sendWebPush(), notifyUser(), encryptAesgcm()

// ── Auth guard ───────────────────────────────────────────────────────
$isCLI  = (php_sapi_name() === 'cli');
$isHTTP = isset($_GET['cron_key'])
       && defined('CRON_KEY')
       && $_GET['cron_key'] === CRON_KEY;

if (!$isCLI && !$isHTTP) {
    http_response_code(403);
    exit('Forbidden');
}

if (!$isCLI) {
    header('Content-Type: application/json');
}

// ── Ensure log table exists ──────────────────────────────────────────
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS timetable_notify_log (
            id         INT AUTO_INCREMENT PRIMARY KEY,
            user_id    INT NOT NULL,
            slot_id    INT NOT NULL,
            notify_type ENUM('reminder','start') NOT NULL,
            slot_date  DATE NOT NULL,
            sent_at    DATETIME DEFAULT CURRENT_TIMESTAMP,
            UNIQUE KEY uniq_slot_day_type (slot_id, slot_date, notify_type),
            INDEX idx_user (user_id),
            INDEX idx_date (slot_date)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (PDOException $e) { /* table already exists */ }

// ── Current time (Asia/Colombo) ──────────────────────────────────────
$tz       = new DateTimeZone('Asia/Colombo');
$now      = new DateTime('now', $tz);
$today    = $now->format('l');          // e.g. "Monday"
$today_date = $now->format('Y-m-d');
$hhmm     = $now->format('H:i');       // e.g. "08:45"

// Time 15 minutes ahead
$in15 = (clone $now)->modify('+15 minutes')->format('H:i');

$log = function(string $msg) use ($now, $isCLI) {
    $line = '[' . $now->format('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;
    if ($isCLI) echo $line;
};

$log("=== Timetable Notify Check | today={$today} now={$hhmm} in15={$in15} ===");

// ── Query active timetable slots for today ───────────────────────────
$slotsStmt = $pdo->prepare("
    SELECT
        t.id,
        t.user_id,
        t.start_time,
        t.end_time,
        t.label,
        t.color,
        s.name  AS subject_name
    FROM timetable t
    LEFT JOIN subjects s ON s.id = t.subject_id
    WHERE t.is_active = 1
      AND t.day_of_week = ?
      AND t.user_id IN (SELECT DISTINCT user_id FROM push_subscriptions)
    ORDER BY t.start_time
");
$slotsStmt->execute([$today]);
$slots = $slotsStmt->fetchAll(PDO::FETCH_ASSOC);

$log("Found " . count($slots) . " active slot(s) for {$today}");

$totalSent = 0;

foreach ($slots as $slot) {
    $slotStart  = date('H:i', strtotime($slot['start_time']));
    $slotEnd    = date('H:i', strtotime($slot['end_time']));
    $slotLabel  = $slot['label'] ?: ($slot['subject_name'] ?: 'Study Session');
    $userId     = (int) $slot['user_id'];
    $slotId     = (int) $slot['id'];

    // Friendly time display
    $startDisp  = date('g:i A', strtotime($slot['start_time']));
    $endDisp    = date('g:i A', strtotime($slot['end_time']));

    // Duration
    $durMins = (strtotime($slot['end_time']) - strtotime($slot['start_time'])) / 60;
    $durStr  = $durMins >= 60
        ? floor($durMins / 60) . 'h' . ($durMins % 60 ? ' ' . ($durMins % 60) . 'm' : '')
        : $durMins . 'm';

    // ── 1. REMINDER — 15 minutes before ─────────────────────────────
    if ($slotStart === $in15) {
        // Check already sent today
        $alreadySent = $pdo->prepare("
            SELECT id FROM timetable_notify_log
            WHERE slot_id=? AND slot_date=? AND notify_type='reminder'
        ");
        $alreadySent->execute([$slotId, $today_date]);

        if (!$alreadySent->fetch()) {
            $payload = [
                'title'  => '⏰ Coming up in 15 min',
                'body'   => "📖 {$slotLabel}\n🕐 {$startDisp} – {$endDisp}  ({$durStr})",
                'icon'   => SITE_URL . '/images/studytrack.png',
                'badge'  => SITE_URL . '/images/studytrack.png',
                'url'    => SITE_URL . '/timetable.php',
                'tag'    => "tt-reminder-{$slotId}-{$today_date}",
                'renotify' => false,
            ];

            $n = notifyUser($pdo, $userId, $payload);
            $totalSent += $n;
            $log("  REMINDER sent to user#{$userId} for slot#{$slotId} '{$slotLabel}' (sent={$n})");

            // Log to prevent duplicates
            try {
                $pdo->prepare("
                    INSERT IGNORE INTO timetable_notify_log (user_id, slot_id, notify_type, slot_date)
                    VALUES (?, ?, 'reminder', ?)
                ")->execute([$userId, $slotId, $today_date]);
            } catch (PDOException $e) { /* ignore duplicate */ }
        } else {
            $log("  REMINDER already sent for slot#{$slotId} today — skipping");
        }
    }

    // ── 2. START — at exact start time ──────────────────────────────
    if ($slotStart === $hhmm) {
        $alreadySent = $pdo->prepare("
            SELECT id FROM timetable_notify_log
            WHERE slot_id=? AND slot_date=? AND notify_type='start'
        ");
        $alreadySent->execute([$slotId, $today_date]);

        if (!$alreadySent->fetch()) {
            $payload = [
                'title'  => '📚 Starting now!',
                'body'   => "🎯 {$slotLabel}\n⏱ {$startDisp} – {$endDisp}  ({$durStr})",
                'icon'   => SITE_URL . '/images/studytrack.png',
                'badge'  => SITE_URL . '/images/studytrack.png',
                'url'    => SITE_URL . '/timetable.php',
                'tag'    => "tt-start-{$slotId}-{$today_date}",
                'renotify' => true,
                'requireInteraction' => false,
            ];

            $n = notifyUser($pdo, $userId, $payload);
            $totalSent += $n;
            $log("  START sent to user#{$userId} for slot#{$slotId} '{$slotLabel}' (sent={$n})");

            try {
                $pdo->prepare("
                    INSERT IGNORE INTO timetable_notify_log (user_id, slot_id, notify_type, slot_date)
                    VALUES (?, ?, 'start', ?)
                ")->execute([$userId, $slotId, $today_date]);
            } catch (PDOException $e) { /* ignore duplicate */ }
        } else {
            $log("  START already sent for slot#{$slotId} today — skipping");
        }
    }
}

$log("=== Done. Total push notifications sent: {$totalSent} ===");

if (!$isCLI) {
    echo json_encode([
        'success'  => true,
        'date'     => $today_date,
        'day'      => $today,
        'time'     => $hhmm,
        'slots'    => count($slots),
        'sent'     => $totalSent,
    ]);
}