<?php
// Filename: cron_notifications.php
// RUN THIS EVERY MINUTE VIA CRON JOB

// --- SECURITY CONFIGURATION ---
$cron_secret = 'BabahmmgHensom2025'; // Ensure this matches your URL parameter

// Check if the secret key matches the URL parameter
if (!isset($_GET['key']) || $_GET['key'] !== $cron_secret) {
    http_response_code(403);
    die("Access Denied: Invalid Secret Key.");
}

// 1. Setup Environment
define('CONFIG_LOADED', true);
if (session_status() === PHP_SESSION_NONE) session_start();

$host = 'localhost'; 
$dbname = 'school_attendance'; 
$user = 'attendance'; 
$pass = 'Amni2012$'; 

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) { die("DB Error: " . $e->getMessage()); }

// SET TIMEZONE EXPLICITLY TO MATCH YOUR SCHOOL LOCATION
date_default_timezone_set('Asia/Kuala_Lumpur'); 

// 2. Telegram Helper
function sendCronTelegram($pdo, $chat_id, $message) {
    // Fetch Token manually
    $stmt = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'telegram_bot_token'");
    $token = $stmt->fetchColumn();

    if ($token && $chat_id) {
        $url = "https://api.telegram.org/bot$token/sendMessage";
        $data = ['chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'HTML'];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Increased timeout slightly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $result = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            echo " [cURL Error: $error] ";
            return false;
        }
        
        // Check if Telegram API returned ok: true
        $json = json_decode($result, true);
        if (!$json || $json['ok'] !== true) {
            echo " [Telegram API Error: " . ($json['description'] ?? 'Unknown') . "] ";
            return false;
        }

        return true;
    }
    echo " [Missing Token or Chat ID] ";
    return false;
}

// --- 3. MAIN LOGIC ---

$current_day = date('N'); // 1 = Mon, 7 = Sun
$today_date = date('Y-m-d');
$current_timestamp = date('Y-m-d H:i:s'); // PHP Time

// Debug Output for Manual Run
echo "<strong>Cron Debug Info:</strong><br>";
echo "PHP Time: " . $current_timestamp . " (Asia/Kuala_Lumpur)<br>";
echo "Day Index: " . $current_day . "<br><hr>";

// QUERY A: REGULAR TEACHERS
// We use ? for the timestamp to inject PHP time, ensuring sync with MySQL
$sql_regular = "
    SELECT 
        t.id as timetable_id, t.start_time, t.end_time, t.subject,
        c.class_name,
        u.full_name, u.telegram_chat_id, u.reminder_minutes
    FROM timetable t
    JOIN classes c ON t.class_id = c.id
    JOIN users u ON t.teacher_id = u.id
    LEFT JOIN relief_assignments r ON t.id = r.timetable_id AND r.assignment_date = ?
    WHERE t.day_of_week = ? 
    AND r.id IS NULL -- Ensure no relief is assigned
    AND u.reminder_enabled = 1
    AND u.telegram_chat_id IS NOT NULL
    -- Compare start time against (PHP Time + User Reminder Minutes)
    AND t.start_time = DATE_FORMAT(DATE_ADD(?, INTERVAL u.reminder_minutes MINUTE), '%H:%i:00')
";

$stmt = $pdo->prepare($sql_regular);
// Params: [Relief Date Check, Day of Week, Current PHP Timestamp]
$stmt->execute([$today_date, $current_day, $current_timestamp]);
$regular_classes = $stmt->fetchAll();

// QUERY B: RELIEF TEACHERS
$sql_relief = "
    SELECT 
        t.id as timetable_id, t.start_time, t.end_time, t.subject,
        c.class_name,
        u.full_name, u.telegram_chat_id, u.reminder_minutes
    FROM relief_assignments r
    JOIN timetable t ON r.timetable_id = t.id
    JOIN classes c ON t.class_id = c.id
    JOIN users u ON r.reliever_id = u.id
    WHERE r.assignment_date = ?
    AND u.reminder_enabled = 1
    AND u.telegram_chat_id IS NOT NULL
    -- Compare start time against (PHP Time + User Reminder Minutes)
    AND t.start_time = DATE_FORMAT(DATE_ADD(?, INTERVAL u.reminder_minutes MINUTE), '%H:%i:00')
";

$stmt = $pdo->prepare($sql_relief);
// Params: [Assignment Date, Current PHP Timestamp]
$stmt->execute([$today_date, $current_timestamp]);
$relief_classes = $stmt->fetchAll();

// --- 4. SEND ALERTS ---

// Process Regular
if (count($regular_classes) > 0) {
    foreach ($regular_classes as $cls) {
        $msg = "🔔 <b>CLASS REMINDER</b>\n\n";
        $msg .= "Hi <b>{$cls['full_name']}</b>,\n";
        $msg .= "You have a class in <b>{$cls['reminder_minutes']} minutes</b>.\n\n";
        $msg .= "🏫 <b>Class:</b> {$cls['class_name']}\n";
        $msg .= "📚 <b>Subject:</b> {$cls['subject']}\n";
        $msg .= "⏰ <b>Time:</b> " . substr($cls['start_time'], 0, 5) . "\n";
        
        echo "Attempting to send to: {$cls['full_name']}... ";
        if (sendCronTelegram($pdo, $cls['telegram_chat_id'], $msg)) {
            echo "<span style='color:green'>SUCCESS</span><br>";
        } else {
            echo "<span style='color:red'>FAILED</span><br>";
        }
    }
}

// Process Relief
if (count($relief_classes) > 0) {
    foreach ($relief_classes as $cls) {
        $msg = "🔔 <b>RELIEF REMINDER</b>\n\n";
        $msg .= "Hi <b>{$cls['full_name']}</b>,\n";
        $msg .= "Your relief class starts in <b>{$cls['reminder_minutes']} minutes</b>.\n\n";
        $msg .= "🏫 <b>Class:</b> {$cls['class_name']}\n";
        $msg .= "📚 <b>Subject:</b> {$cls['subject']}\n";
        $msg .= "⏰ <b>Time:</b> " . substr($cls['start_time'], 0, 5) . "\n";
        
        echo "Attempting to send Relief Alert to: {$cls['full_name']}... ";
        if (sendCronTelegram($pdo, $cls['telegram_chat_id'], $msg)) {
            echo "<span style='color:green'>SUCCESS</span><br>";
        } else {
            echo "<span style='color:red'>FAILED</span><br>";
        }
    }
}

if (empty($regular_classes) && empty($relief_classes)) {
    echo "No matching classes found for reminder at this specific minute.<br>";
    echo "<em>(Looking for classes starting at exactly [Current Time + Reminder Mins])</em>";
}
?>