<?php
// Filename: check_alerts.php
require 'config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['alert' => false]);
    exit;
}

$user_id = $_SESSION['user_id'];
$day = date('N'); 
$now = date('H:i:s');

// 0. Fetch User Preferences
$stmt = $pdo->prepare("SELECT reminder_minutes, reminder_enabled FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$pref = $stmt->fetch();

// If reminders are disabled in profile, stop here.
if (!$pref || $pref['reminder_enabled'] == 0) {
    echo json_encode(['alert' => false]);
    exit;
}

$reminder_threshold = $pref['reminder_minutes'] ?? 15; // Use user setting or default to 15

// 1. Find CURRENT Active Slot
$sql = "
    SELECT t.id, t.end_time, c.class_name, t.subject 
    FROM timetable t 
    JOIN classes c ON t.class_id = c.id
    WHERE t.teacher_id = ? 
    AND t.day_of_week = ? 
    AND ? BETWEEN t.start_time AND t.end_time
    LIMIT 1
";

$stmt = $pdo->prepare($sql);
$stmt->execute([$user_id, $day, $now]);
$slot = $stmt->fetch();

if ($slot) {
    // 2. Check if already scanned
    $check = $pdo->prepare("SELECT id FROM attendance_logs WHERE timetable_id = ? AND DATE(scan_time) = CURRENT_DATE");
    $check->execute([$slot['id']]);
    
    if (!$check->fetch()) {
        // Not scanned yet!
        $endTime = strtotime($slot['end_time']);
        $currentTime = time();
        $diff = $endTime - $currentTime;
        $minutesLeft = floor($diff / 60);

        // Alert based on USER PREFERENCE (or if class is ending soon)
        // We alert if time left is less than the user's threshold
        // OR if it's the last 5 minutes (critical warning)
        if ($minutesLeft <= $reminder_threshold && $minutesLeft > -5) {
            echo json_encode([
                'alert' => true,
                'message' => "⚠️ Reminder: You haven't scanned for <strong>{$slot['class_name']}</strong> ({$slot['subject']})!<br>Class ends in $minutesLeft mins."
            ]);
            exit;
        }
    }
}

echo json_encode(['alert' => false]);
?>