<?php
/**
 * Configuration partagée pour l'interface web
 */

// Chemins absolus
define('BASE_DIR', '/home/fasoon5');
define('SITES_FILE', BASE_DIR . '/sites.json');
define('STATE_FILE', BASE_DIR . '/sites_state.json');
define('LOG_FILE', BASE_DIR . '/monitor.log');
define('TELEGRAM_CONFIG', BASE_DIR . '/.telegram_config.php');
define('MONITOR_SCRIPT', BASE_DIR . '/monitor.php');

// Charger la config Telegram sécurisée
if (file_exists(TELEGRAM_CONFIG)) {
    $telegramConfig = require TELEGRAM_CONFIG;
    define('TELEGRAM_TOKEN', $telegramConfig['telegram_token'] ?? '');
    define('TELEGRAM_CHAT_ID', $telegramConfig['telegram_chat_id'] ?? '');
    define('ADMIN_PASSWORD', $telegramConfig['admin_password'] ?? '');
} else {
    define('TELEGRAM_TOKEN', '');
    define('TELEGRAM_CHAT_ID', '');
    define('ADMIN_PASSWORD', '');
}

// Démarrer la session pour l'authentification
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Vérifier si l'utilisateur est authentifié
 */
function requireAuth() {
    if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
        header('Location: index.php?login=required');
        exit;
    }
}

/**
 * Lire les sites depuis le fichier JSON
 */
function getSites() {
    if (!file_exists(SITES_FILE)) {
        return [];
    }
    $content = file_get_contents(SITES_FILE);
    $sites = json_decode($content, true);
    return is_array($sites) ? $sites : [];
}

/**
 * Sauvegarder les sites dans le fichier JSON
 */
function saveSites(array $sites) {
    file_put_contents(SITES_FILE, json_encode($sites, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

/**
 * Lire l'état des sites
 */
function getStates() {
    if (!file_exists(STATE_FILE)) {
        return [];
    }
    $content = file_get_contents(STATE_FILE);
    $states = json_decode($content, true);
    return is_array($states) ? $states : [];
}

/**
 * Valider une URL
 */
function isValidUrl($url) {
    return filter_var($url, FILTER_VALIDATE_URL) && 
           (stripos($url, 'http://') === 0 || stripos($url, 'https://') === 0);
}

/**
 * Formater une date pour l'affichage
 */
function formatDate($timestamp) {
    return date('d/m/Y H:i:s', $timestamp);
}

/**
 * Obtenir la couleur du statut pour l'UI
 */
function getStatusColor($status) {
    return match($status) {
        'OK' => 'success',
        'BLOCKED' => 'warning',
        'DOWN', 'ERROR' => 'danger',
        default => 'secondary'
    };
}

/**
 * Obtenir l'icône du statut
 */
function getStatusIcon($status) {
    return match($status) {
        'OK' => '✅',
        'BLOCKED' => '⚠️',
        'DOWN' => '🔴',
        'ERROR' => '❌',
        default => '❓'
    };
}
?>