<?php
// uptime_monitor.php - Upload to BACKUP SERVER
// Checks if Main Site is alive and alerts Telegram on status change.

// --- CONFIGURATION ---
$target_url = "http://system.fon2fix.com.my/login.php"; // We check the login page specifically
$telegram_config = [
    'enabled'   => true, 
    'bot_token' => '8583824773:AAFT7kQCPtMGfOWswFTkiwtWddxUEzmaanU',
    'chat_id'   => '-5047381830' // <--- PUT YOUR GROUP ID HERE
];

// File to remember the last status (Stored on server)
$status_file = __DIR__ . '/monitor_status.txt';

// --- TELEGRAM FUNCTION ---
function sendTelegram($msg, $cfg) {
    if (!$cfg['enabled']) return;
    $url = "https://api.telegram.org/bot{$cfg['bot_token']}/sendMessage?chat_id={$cfg['chat_id']}&text=" . urlencode($msg);
    @file_get_contents($url);
}

// --- CHECK LOGIC ---
function checkSite($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);    // We need headers
    curl_setopt($ch, CURLOPT_NOBODY, true);    // Don't download body (faster)
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);     // Give up after 10 seconds
    curl_setopt($ch, CURLOPT_USERAGENT, "Fon2FixWatchdog/1.0"); 
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Consider "Up" if code is 200 (OK) or 302 (Redirect)
    return ($httpCode >= 200 && $httpCode < 400);
}

// --- MAIN EXECUTION ---
$is_currently_up = checkSite($target_url);

// Read previous status
$last_status = "unknown";
if (file_exists($status_file)) {
    $last_status = trim(file_get_contents($status_file));
}

// Compare and Alert
if ($is_currently_up && $last_status === "down") {
    // SCENARIO: RECOVERY
    // It was down, now it is up.
    sendTelegram("✅ <b>SYSTEM RECOVERY</b>\n\nMain Site is back ONLINE.\nURL: $target_url", $telegram_config);
    file_put_contents($status_file, "up");
    echo "Status changed to UP.";

} elseif (!$is_currently_up && $last_status === "up") {
    // SCENARIO: CRASH
    // It was up, now it is down.
    sendTelegram("🚨 <b>CRITICAL ALERT</b>\n\nMain Site is DOWN!\nIt is not responding to ping.", $telegram_config);
    file_put_contents($status_file, "down");
    echo "Status changed to DOWN.";

} elseif ($last_status === "unknown") {
    // First run initialization
    $status = $is_currently_up ? "up" : "down";
    file_put_contents($status_file, $status);
    echo "Initialized status as: $status";
} else {
    // No change
    echo "No change. Site is still " . ($is_currently_up ? "UP" : "DOWN") . ".";
}
?>