<?php
// uptime_monitor.php - v5: SSL verify on, token-gated, secrets from config.

// --- ACCESS GATE ----------------------------------------------------------
// Requires ?access_token=... matching config.backup_sync.monitor_token (or
// env FONFIX_MONITOR_TOKEN). CLI runs are always allowed.
$is_cli = (php_sapi_name() === 'cli');
$config = [];
if (file_exists(__DIR__ . '/config.php')) {
    $loaded = @require __DIR__ . '/config.php';
    if (is_array($loaded)) { $config = $loaded; }
}

$expected_token = getenv('FONFIX_MONITOR_TOKEN') ?: ($config['backup_sync']['monitor_token'] ?? '');
if (!$is_cli) {
    $provided = $_GET['access_token'] ?? '';
    if (!$expected_token || !is_string($provided) || !hash_equals((string)$expected_token, (string)$provided)) {
        http_response_code(403);
        header('Content-Type: text/plain; charset=utf-8');
        die("Access Denied.");
    }
}

// --- CONFIGURATION -------------------------------------------------------
$target_url = $config['backup_sync']['target_url']
    ?? 'https://systembackup.spartanmnc.com/restore_from_sync.php';

$telegram_config = [
    'enabled'   => (bool)($config['telegram']['enabled']    ?? true),
    'bot_token' => (string)($config['telegram']['bot_token'] ?? getenv('FONFIX_TELEGRAM_BOT_TOKEN') ?: ''),
    'chat_id'   => (string)($config['telegram']['chat_id']   ?? getenv('FONFIX_TELEGRAM_CHAT_ID') ?: ''),
];

$status_file = __DIR__ . '/monitor_backup_status.txt';

// --- TELEGRAM (via cURL) -------------------------------------------------
function sendTelegram($msg, $cfg) {
    if (empty($cfg['enabled']) || empty($cfg['bot_token']) || empty($cfg['chat_id'])) {
        return;
    }
    $url = "https://api.telegram.org/bot{$cfg['bot_token']}/sendMessage";
    $data = [
        'chat_id'    => $cfg['chat_id'],
        'text'       => $msg,
        'parse_mode' => 'HTML',
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_exec($ch);
    curl_close($ch);
}

// --- CHECK LOGIC ---------------------------------------------------------
function checkSite($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_USERAGENT, "Fon2FixMain/1.0");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    echo "Target: " . htmlspecialchars($url) . "<br>";
    echo "HTTP Code: <b>" . (int)$httpCode . "</b><br>";

    // Accept 200 (OK), 401/403 (protected) as "up"
    if ($httpCode == 200 || $httpCode == 401 || $httpCode == 403) {
        return ['up' => true, 'code' => $httpCode];
    }
    return ['up' => false, 'code' => $httpCode];
}

// --- EXECUTION -----------------------------------------------------------
$check = checkSite($target_url);
$is_currently_up = $check['up'];
$httpCode = $check['code'];

$last_status = "unknown";
if (file_exists($status_file)) {
    $last_status = trim((string) file_get_contents($status_file));
}

if ($is_currently_up && $last_status === "down") {
    sendTelegram("✅ <b>BACKUP SERVER RECOVERY</b>\n\nBackup Server is back ONLINE.", $telegram_config);
    @file_put_contents($status_file, "up");
    echo "<h3>Result: RECOVERY (Message Sent)</h3>";

} elseif (!$is_currently_up && $last_status === "up") {
    sendTelegram("⚠️ <b>BACKUP SERVER ALERT</b>\n\nBackup Server is failing (HTTP $httpCode).", $telegram_config);
    @file_put_contents($status_file, "down");
    echo "<h3>Result: CRASH (Message Sent)</h3>";

} elseif ($last_status === "unknown") {
    $status = $is_currently_up ? "up" : "down";
    @file_put_contents($status_file, $status);
    echo "<h3>Result: First Run (Initialized as $status)</h3>";

    if (!$is_currently_up) {
        sendTelegram("⚠️ <b>BACKUP SERVER WARNING</b>\n\nMonitor started, but target is unreachable.", $telegram_config);
    }
} else {
    echo "<h3>Result: No Change (" . htmlspecialchars($last_status) . ")</h3>";
}
