<?php
/**
 * timetable-notify-debug.php
 * Upload to studytrack/api/ and run once to see what's happening.
 * Access via browser: https://studytrack.edurx.icu/studytrack/api/timetable-notify-debug.php?cron_key=YOUR_CRON_KEY
 * OR run via cron once and check the log.
 */

require_once __DIR__ . '/../includes/config.php';

header('Content-Type: text/plain; charset=utf-8');

$tz     = new DateTimeZone('Asia/Colombo');
$now    = new DateTime('now', $tz);
$today  = $now->format('l');
$hhmm   = $now->format('H:i');
$in15   = (clone $now)->modify('+15 minutes')->format('H:i');

echo "=== Timetable Notify Debug ===\n";
echo "Server time (Colombo): " . $now->format('Y-m-d H:i:s') . "\n";
echo "Today (day name)      : {$today}\n";
echo "Current time (H:i)    : {$hhmm}\n";
echo "15 min ahead          : {$in15}\n\n";

// 1. Check push_subscriptions table
echo "--- Push Subscriptions ---\n";
try {
    $subs = $pdo->query("SELECT id, user_id, LEFT(endpoint,60) as ep, created_at FROM push_subscriptions LIMIT 20")->fetchAll(PDO::FETCH_ASSOC);
    if (empty($subs)) {
        echo "⚠️  NO subscriptions found in push_subscriptions table!\n";
        echo "    → User needs to Allow notifications on the timetable page.\n";
    } else {
        echo "✅ Found " . count($subs) . " subscription(s):\n";
        foreach ($subs as $s) {
            echo "   user_id={$s['user_id']} | endpoint={$s['ep']}... | created={$s['created_at']}\n";
        }
    }
} catch (Exception $e) {
    echo "❌ Error reading push_subscriptions: " . $e->getMessage() . "\n";
}

echo "\n--- Timetable Slots (ALL active) ---\n";
try {
    $slots = $pdo->query("
        SELECT t.id, t.user_id, t.day_of_week, t.start_time, t.end_time, t.label, t.is_active,
               s.name as subject_name
        FROM timetable t
        LEFT JOIN subjects s ON s.id = t.subject_id
        ORDER BY t.day_of_week, t.start_time
        LIMIT 50
    ")->fetchAll(PDO::FETCH_ASSOC);

    if (empty($slots)) {
        echo "⚠️  NO timetable slots found!\n";
        echo "    → Add slots on the Timetable page first.\n";
    } else {
        echo "✅ Found " . count($slots) . " slot(s):\n";
        foreach ($slots as $sl) {
            $label = $sl['label'] ?: ($sl['subject_name'] ?: 'Study');
            $active = $sl['is_active'] ? '✅' : '❌ inactive';
            echo "   slot#{$sl['id']} user={$sl['user_id']} {$sl['day_of_week']} {$sl['start_time']}-{$sl['end_time']} '{$label}' {$active}\n";
        }
    }
} catch (Exception $e) {
    echo "❌ Error reading timetable: " . $e->getMessage() . "\n";
}

echo "\n--- Today's Slots ({$today}) with push subscribers ---\n";
try {
    $todaySlots = $pdo->prepare("
        SELECT t.id, t.user_id, t.start_time, t.end_time, t.label,
               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
    ");
    $todaySlots->execute([$today]);
    $rows = $todaySlots->fetchAll(PDO::FETCH_ASSOC);

    if (empty($rows)) {
        echo "⚠️  No active slots for {$today} with push subscribers.\n";
        echo "    Possible reasons:\n";
        echo "    1. No timetable slots for today ({$today})\n";
        echo "    2. Slots exist but user has no push subscription\n";
        echo "    3. Slots are marked inactive\n";
    } else {
        echo "✅ Found " . count($rows) . " slot(s) for today that can receive push:\n";
        foreach ($rows as $sl) {
            $label = $sl['label'] ?: ($sl['subject_name'] ?: 'Study');
            $start = date('H:i', strtotime($sl['start_time']));
            $match15  = ($start === $in15)  ? ' ← 🔔 WOULD SEND REMINDER NOW' : '';
            $matchNow = ($start === $hhmm)  ? ' ← 📚 WOULD SEND START NOW'    : '';
            echo "   slot#{$sl['id']} user={$sl['user_id']} {$start} '{$label}'{$match15}{$matchNow}\n";
        }
    }
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}

echo "\n--- timetable_notify_log (last 10 entries) ---\n";
try {
    $logs = $pdo->query("SELECT * FROM timetable_notify_log ORDER BY sent_at DESC LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);
    if (empty($logs)) {
        echo "(empty — no notifications sent yet)\n";
    } else {
        foreach ($logs as $l) {
            echo "   slot#{$l['slot_id']} user={$l['user_id']} type={$l['notify_type']} date={$l['slot_date']} sent={$l['sent_at']}\n";
        }
    }
} catch (Exception $e) {
    echo "(table may not exist yet: " . $e->getMessage() . ")\n";
}

echo "\n=== End Debug ===\n";
