<?php
require_once __DIR__ . '/includes/header.php';

/* =======================
   SECURITY
======================= */
if (!isset($_SESSION['role'], $_SESSION['name'])) {
    header("Location: index.php");
    exit;
}

$role_logada = $_SESSION['role'];

// Solo master puede gestionar backups
if ($role_logada !== 'master') {
    die('<div class="alert alert-danger">Acceso denegado - Solo el master puede gestionar backups</div>');
}

/* =======================
   CONFIGURACIÓN - USAR ARCHIVO JSON
======================= */
$configFile = __DIR__ . '/telegram_config.json';

// Cargar configuración desde archivo JSON
function loadTelegramConfig() {
    global $configFile;
    $default = [
        'bot_token' => '',
        'chat_id' => '',
        'enabled' => false
    ];
    
    if (file_exists($configFile)) {
        $content = file_get_contents($configFile);
        $config = json_decode($content, true);
        if ($config && is_array($config)) {
            return array_merge($default, $config);
        }
    }
    return $default;
}

// Guardar configuración en archivo JSON
function saveTelegramConfig($bot_token, $chat_id, $enabled) {
    global $configFile;
    $config = [
        'bot_token' => $bot_token,
        'chat_id' => $chat_id,
        'enabled' => $enabled,
        'updated_at' => date('Y-m-d H:i:s')
    ];
    file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT));
    return $config;
}

// Cargar configuración actual
$telegramConfig = loadTelegramConfig();
$TELEGRAM_BOT_TOKEN = $telegramConfig['bot_token'];
$TELEGRAM_CHAT_ID = $telegramConfig['chat_id'];
$TELEGRAM_ENABLED = $telegramConfig['enabled'];

// Rutas
$dbPath = __DIR__ . '/api/.db.db';
$backupDir = __DIR__ . '/backups';
$tempDir = __DIR__ . '/temp_restore';

// Crear carpetas necesarias
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

/* =======================
   FUNCIÓN: ENVIAR A TELEGRAM (SIN CURL)
======================= */
function sendToTelegram($filePath, $botToken, $chatId) {
    if (empty($botToken) || empty($chatId)) {
        return ['success' => false, 'message' => 'Token o Chat ID vacío'];
    }
    
    if (!file_exists($filePath)) {
        return ['success' => false, 'message' => 'Archivo no encontrado'];
    }
    
    // Usar file_get_contents con contexto (alternativa a cURL)
    $url = "https://api.telegram.org/bot{$botToken}/sendDocument";
    
    // Crear boundary para multipart/form-data
    $boundary = md5(time());
    $delimiter = '-------------' . $boundary;
    
    // Leer el contenido del archivo
    $fileContent = file_get_contents($filePath);
    
    // Construir el cuerpo del POST
    $postData = "--" . $delimiter . "\r\n";
    $postData .= 'Content-Disposition: form-data; name="chat_id"' . "\r\n\r\n";
    $postData .= $chatId . "\r\n";
    
    $postData .= "--" . $delimiter . "\r\n";
    $postData .= 'Content-Disposition: form-data; name="document"; filename="' . basename($filePath) . '"' . "\r\n";
    $postData .= 'Content-Type: application/zip' . "\r\n\r\n";
    $postData .= $fileContent . "\r\n";
    $postData .= "--" . $delimiter . "--\r\n";
    
    // Configurar contexto HTTP
    $options = [
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: multipart/form-data; boundary=" . $delimiter . "\r\n" .
                        "Content-Length: " . strlen($postData) . "\r\n",
            'content' => $postData,
            'timeout' => 60
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ];
    
    $context = stream_context_create($options);
    $result = @file_get_contents($url, false, $context);
    
    if ($result === false) {
        // Intentar con fsockopen si file_get_contents falla
        return sendToTelegramViaSocket($filePath, $botToken, $chatId);
    }
    
    $response = json_decode($result, true);
    
    if (isset($response['ok']) && $response['ok'] === true) {
        return ['success' => true, 'response' => $response];
    } else {
        $errorMsg = $response['description'] ?? 'Error desconocido';
        return ['success' => false, 'message' => $errorMsg];
    }
}

/* =======================
   FUNCIÓN: ENVIAR A TELEGRAM VÍA SOCKET (ALTERNATIVA)
======================= */
function sendToTelegramViaSocket($filePath, $botToken, $chatId) {
    $host = 'api.telegram.org';
    $port = 443;
    
    $fileContent = file_get_contents($filePath);
    $boundary = md5(time());
    $delimiter = '-------------' . $boundary;
    
    // Construir el cuerpo
    $body = "--" . $delimiter . "\r\n";
    $body .= "Content-Disposition: form-data; name=\"chat_id\"\r\n\r\n";
    $body .= $chatId . "\r\n";
    $body .= "--" . $delimiter . "\r\n";
    $body .= "Content-Disposition: form-data; name=\"document\"; filename=\"" . basename($filePath) . "\"\r\n";
    $body .= "Content-Type: application/zip\r\n\r\n";
    $body .= $fileContent . "\r\n";
    $body .= "--" . $delimiter . "--\r\n";
    
    $headers = "POST /bot{$botToken}/sendDocument HTTP/1.1\r\n";
    $headers .= "Host: {$host}\r\n";
    $headers .= "Content-Type: multipart/form-data; boundary={$delimiter}\r\n";
    $headers .= "Content-Length: " . strlen($body) . "\r\n";
    $headers .= "Connection: close\r\n\r\n";
    
    $fp = @fsockopen('ssl://' . $host, $port, $errno, $errstr, 30);
    
    if (!$fp) {
        return ['success' => false, 'message' => "Error de conexión: $errstr"];
    }
    
    fwrite($fp, $headers . $body);
    
    $response = '';
    while (!feof($fp)) {
        $response .= fgets($fp, 4096);
    }
    fclose($fp);
    
    // Extraer el JSON de la respuesta
    if (preg_match('/\r\n\r\n(.*)/s', $response, $matches)) {
        $json = $matches[1];
        $data = json_decode($json, true);
        
        if (isset($data['ok']) && $data['ok'] === true) {
            return ['success' => true, 'response' => $data];
        } else {
            $errorMsg = $data['description'] ?? 'Error desconocido';
            return ['success' => false, 'message' => $errorMsg];
        }
    }
    
    return ['success' => false, 'message' => 'Respuesta inválida del servidor'];
}

/* =======================
   FUNCIÓN: PROBAR CONEXIÓN TELEGRAM (SIN CURL)
======================= */
function testTelegramConnection($botToken, $chatId) {
    if (empty($botToken) || empty($chatId)) {
        return ['success' => false, 'message' => 'Token o Chat ID vacío'];
    }
    
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    
    $postData = http_build_query([
        'chat_id' => $chatId,
        'text' => "✅ *PRUEBA DE CONEXIÓN EXITOSA!*\n\n" .
                  "🤖 Bot funcionando correctamente\n" .
                  "📅 Fecha: " . date('Y-m-d H:i:s') . "\n\n" .
                  "Ahora puedes enviar backups a Telegram.",
        'parse_mode' => 'Markdown'
    ]);
    
    $options = [
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
                        "Content-Length: " . strlen($postData) . "\r\n",
            'content' => $postData,
            'timeout' => 30
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ];
    
    $context = stream_context_create($options);
    $result = @file_get_contents($url, false, $context);
    
    if ($result === false) {
        return ['success' => false, 'message' => 'No se pudo conectar a Telegram'];
    }
    
    $response = json_decode($result, true);
    
    if (isset($response['ok']) && $response['ok'] === true) {
        return ['success' => true, 'message' => 'Conexión exitosa'];
    } else {
        $errorMsg = $response['description'] ?? 'Error desconocido';
        return ['success' => false, 'message' => $errorMsg];
    }
}

/* =======================
   FUNCIÓN: CREAR BACKUP
======================= */
function createBackup($dbPath, $backupDir, $sendToTelegramFlag = false, $botToken = null, $chatId = null) {
    if (!file_exists($dbPath)) {
        return ['success' => false, 'message' => 'Base de datos no encontrada en: ' . $dbPath];
    }
    
    if (filesize($dbPath) == 0) {
        return ['success' => false, 'message' => 'La base de datos está vacía'];
    }
    
    if (!is_dir($backupDir)) {
        mkdir($backupDir, 0755, true);
    }
    
    $date = date('Y-m-d_H-i-s');
    $zipFile = $backupDir . '/backup_' . $date . '.zip';
    
    $zip = new ZipArchive();
    if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
        $zip->addFile($dbPath, 'database.db');
        $zip->close();
        
        $result = [
            'success' => true,
            'message' => 'Backup creado exitosamente',
            'file' => basename($zipFile),
            'size' => round(filesize($zipFile) / 1024, 2)
        ];
        
        if ($sendToTelegramFlag && $botToken && $chatId && !empty($botToken) && !empty($chatId)) {
            $telegramResult = sendToTelegram($zipFile, $botToken, $chatId);
            if ($telegramResult['success']) {
                $result['message'] .= ' y enviado a Telegram';
            } else {
                $result['message'] .= ' pero falló el envío a Telegram: ' . $telegramResult['message'];
            }
        } elseif ($sendToTelegramFlag) {
            $result['message'] .= ' pero NO se envió a Telegram (configuración incompleta)';
        }
        
        return $result;
    }
    
    return ['success' => false, 'message' => 'Error al comprimir el backup'];
}

/* =======================
   FUNCIÓN: RESTAURAR BACKUP
======================= */
function restoreBackup($zipPath, $dbPath) {
    global $tempDir;
    
    if (!is_dir($tempDir)) {
        mkdir($tempDir, 0755, true);
    }
    
    $zip = new ZipArchive();
    if ($zip->open($zipPath) === TRUE) {
        $zip->extractTo($tempDir);
        $zip->close();
        
        $extractedDb = $tempDir . '/database.db';
        
        if (file_exists($extractedDb)) {
            // Backup automático antes de restaurar
            $backupDir = dirname($zipPath);
            $autoBackup = $backupDir . '/auto_before_restore_' . date('Y-m-d_H-i-s') . '.zip';
            $autoZip = new ZipArchive();
            if ($autoZip->open($autoBackup, ZipArchive::CREATE) === TRUE) {
                $autoZip->addFile($dbPath, '.db.db');
                $autoZip->close();
            }
            
            if (copy($extractedDb, $dbPath)) {
                unlink($extractedDb);
                rmdir($tempDir);
                return ['success' => true, 'message' => 'Base de datos restaurada exitosamente'];
            } else {
                return ['success' => false, 'message' => 'Error al restaurar'];
            }
        }
        
        return ['success' => false, 'message' => 'El ZIP no contiene database.db'];
    }
    
    return ['success' => false, 'message' => 'No se pudo abrir el ZIP'];
}

/* =======================
   FUNCIÓN: LISTAR BACKUPS
======================= */
function listBackups($backupDir) {
    $backups = [];
    
    if (is_dir($backupDir)) {
        $files = scandir($backupDir);
        foreach ($files as $file) {
            if ($file !== '.' && $file !== '..' && pathinfo($file, PATHINFO_EXTENSION) == 'zip') {
                $backups[] = [
                    'name' => $file,
                    'size' => round(filesize($backupDir . '/' . $file) / 1024, 2),
                    'date' => date('Y-m-d H:i:s', filemtime($backupDir . '/' . $file)),
                    'timestamp' => filemtime($backupDir . '/' . $file)
                ];
            }
        }
        
        usort($backups, function($a, $b) {
            return $b['timestamp'] - $a['timestamp'];
        });
    }
    
    return $backups;
}

/* =======================
   FUNCIÓN: LIMPIAR BACKUPS ANTIGUOS
======================= */
function cleanOldBackups($backupDir, $daysToKeep = 30) {
    $deleted = 0;
    $files = glob($backupDir . '/backup_*.zip');
    
    foreach ($files as $file) {
        if (time() - filemtime($file) > $daysToKeep * 24 * 3600) {
            unlink($file);
            $deleted++;
        }
    }
    
    return $deleted;
}

/* =======================
   PROCESAR ACCIONES
======================= */
$result = null;
$backups = listBackups($backupDir);
$modalMessage = null;
$showModal = false;

// Guardar configuración de Telegram
if (isset($_POST['save_telegram_config'])) {
    $botToken = trim($_POST['bot_token']);
    $chatId = trim($_POST['chat_id']);
    $enabled = isset($_POST['telegram_enabled']);
    
    saveTelegramConfig($botToken, $chatId, $enabled);
    
    $telegramConfig = loadTelegramConfig();
    $TELEGRAM_BOT_TOKEN = $telegramConfig['bot_token'];
    $TELEGRAM_CHAT_ID = $telegramConfig['chat_id'];
    $TELEGRAM_ENABLED = $telegramConfig['enabled'];
    
    $result = ['success' => true, 'message' => 'Configuración guardada'];
}

// Probar conexión Telegram
if (isset($_POST['test_telegram'])) {
    $botToken = trim($_POST['bot_token']);
    $chatId = trim($_POST['chat_id']);
    
    $testResult = testTelegramConnection($botToken, $chatId);
    $modalMessage = $testResult;
    $showModal = true;
}

// Crear backup local
if (isset($_POST['create_backup'])) {
    $result = createBackup($dbPath, $backupDir, false);
    if ($result['success']) {
        $backups = listBackups($backupDir);
    }
}

// Crear backup + Telegram
if (isset($_POST['create_backup_telegram'])) {
    $result = createBackup($dbPath, $backupDir, true, $TELEGRAM_BOT_TOKEN, $TELEGRAM_CHAT_ID);
    if ($result['success']) {
        $backups = listBackups($backupDir);
    }
}

// Limpiar backups antiguos
if (isset($_POST['clean_backups'])) {
    $deleted = cleanOldBackups($backupDir, 30);
    $result = ['success' => true, 'message' => "Se eliminaron $deleted backups antiguos"];
    $backups = listBackups($backupDir);
}

// Subir backup
if (isset($_POST['upload_backup']) && isset($_FILES['backup_file']) && $_FILES['backup_file']['error'] == 0) {
    $filename = $_FILES['backup_file']['name'];
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    
    if (strtolower($ext) == 'zip') {
        $uploadFile = $backupDir . '/' . basename($filename);
        $counter = 1;
        $originalName = pathinfo($filename, PATHINFO_FILENAME);
        while (file_exists($uploadFile)) {
            $uploadFile = $backupDir . '/' . $originalName . '_' . $counter . '.zip';
            $counter++;
        }
        
        if (move_uploaded_file($_FILES['backup_file']['tmp_name'], $uploadFile)) {
            $result = ['success' => true, 'message' => 'Backup subido exitosamente'];
            $backups = listBackups($backupDir);
        } else {
            $result = ['success' => false, 'message' => 'Error al subir'];
        }
    } else {
        $result = ['success' => false, 'message' => 'Solo archivos ZIP'];
    }
}

// Restaurar backup
if (isset($_GET['restore'])) {
    $file = basename($_GET['restore']);
    $filePath = $backupDir . '/' . $file;
    
    if (file_exists($filePath)) {
        $result = restoreBackup($filePath, $dbPath);
        echo "<script>alert('{$result['message']}'); window.location='backup.php';</script>";
        exit;
    }
}

// Eliminar backup
if (isset($_GET['delete'])) {
    $file = basename($_GET['delete']);
    $filePath = $backupDir . '/' . $file;
    
    if (file_exists($filePath)) {
        unlink($filePath);
        echo "<script>alert('Backup eliminado'); window.location='backup.php';</script>";
        exit;
    }
}

// Descargar backup
if (isset($_GET['download'])) {
    $file = basename($_GET['download']);
    $filePath = $backupDir . '/' . $file;
    
    if (file_exists($filePath)) {
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    }
}
?>

<!-- Estilos para el modal personalizado -->
<style>
.custom-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.85);
    z-index: 10000;
    justify-content: center;
    align-items: center;
    backdrop-filter: blur(5px);
}

.custom-modal-content {
    background: linear-gradient(135deg, #1e1e2e, #2a2a3a);
    border-radius: 20px;
    width: 90%;
    max-width: 550px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
    border: 1px solid rgba(102, 126, 234, 0.3);
    animation: modalFadeIn 0.3s ease;
}

@keyframes modalFadeIn {
    from {
        opacity: 0;
        transform: translateY(-50px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.custom-modal-header {
    padding: 20px 25px;
    border-bottom: 1px solid rgba(102, 126, 234, 0.3);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.custom-modal-header h3 {
    margin: 0;
    color: #fff;
    font-size: 1.5rem;
}

.custom-modal-header h3 i {
    color: #0088cc;
    margin-right: 10px;
}

.custom-modal-close {
    background: none;
    border: none;
    color: #fff;
    font-size: 28px;
    cursor: pointer;
    transition: all 0.3s;
    line-height: 1;
}

.custom-modal-close:hover {
    color: #ff4757;
    transform: scale(1.1);
}

.custom-modal-body {
    padding: 25px;
}

.custom-modal-footer {
    padding: 15px 25px;
    border-top: 1px solid rgba(102, 126, 234, 0.3);
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.custom-modal-body .form-group {
    margin-bottom: 20px;
}

.custom-modal-body label {
    display: block;
    margin-bottom: 8px;
    color: #e0e0e0;
    font-weight: 500;
}

.custom-modal-body label i {
    margin-right: 8px;
    color: #667eea;
}

.custom-modal-body input[type="text"] {
    width: 100%;
    padding: 12px 15px;
    background: #0f0f1a;
    border: 1px solid rgba(102, 126, 234, 0.3);
    border-radius: 10px;
    color: #fff;
    font-size: 14px;
    transition: all 0.3s;
}

.custom-modal-body input[type="text"]:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.custom-modal-body .checkbox-group {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
}

.custom-modal-body .checkbox-group input {
    width: 18px;
    height: 18px;
    cursor: pointer;
}

.custom-modal-body .checkbox-group span {
    color: #e0e0e0;
}

.custom-modal-body .alert {
    padding: 12px 15px;
    border-radius: 10px;
    margin-bottom: 20px;
}

.custom-modal-body .alert-success {
    background: rgba(40, 167, 69, 0.2);
    border: 1px solid #28a745;
    color: #28a745;
}

.custom-modal-body .alert-danger {
    background: rgba(220, 53, 69, 0.2);
    border: 1px solid #dc3545;
    color: #dc3545;
}

.custom-modal-body .alert-info {
    background: rgba(23, 162, 184, 0.2);
    border: 1px solid #17a2b8;
    color: #17a2b8;
}

.custom-modal-body small {
    display: block;
    margin-top: 5px;
    font-size: 12px;
    color: #888;
}

.custom-modal-body small a {
    color: #667eea;
    text-decoration: none;
}

.custom-modal-body ol {
    margin-top: 10px;
    padding-left: 20px;
}

.custom-modal-body ol li {
    margin: 5px 0;
    color: #ccc;
}

.btn-custom {
    padding: 10px 20px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 500;
    transition: all 0.3s;
}

.btn-custom-secondary {
    background: #3a3a4a;
    color: #fff;
}

.btn-custom-secondary:hover {
    background: #4a4a5a;
}

.btn-custom-info {
    background: linear-gradient(135deg, #17a2b8, #138496);
    color: #fff;
}

.btn-custom-info:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(23, 162, 184, 0.3);
}

.btn-custom-success {
    background: linear-gradient(135deg, #28a745, #1e7e34);
    color: #fff;
}

.btn-custom-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
}
</style>

<!-- Modal personalizado -->
<div id="telegramModal" class="custom-modal">
    <div class="custom-modal-content">
        <div class="custom-modal-header">
            <h3>
                <i class="fa fa-telegram"></i> Configurar Telegram
            </h3>
            <button class="custom-modal-close" onclick="cerrarModal()">&times;</button>
        </div>
        <form method="post" id="telegramForm">
            <div class="custom-modal-body">
                <?php if ($modalMessage): ?>
                    <div class="alert alert-<?= $modalMessage['success'] ? 'alert-success' : 'alert-danger' ?>">
                        <?= htmlspecialchars($modalMessage['message']) ?>
                    </div>
                <?php endif; ?>
                
                <div class="form-group">
                    <label><i class="fa fa-key"></i> Bot Token</label>
                    <input type="text" 
                           name="bot_token" 
                           value="<?= htmlspecialchars($TELEGRAM_BOT_TOKEN) ?>"
                           placeholder="Ej: 1234567890:ABCdefGHIjklmNOPqrstUVwxyz"
                           required>
                    <small>Obténlo en <a href="https://t.me/BotFather" target="_blank">@BotFather</a></small>
                </div>
                
                <div class="form-group">
                    <label><i class="fa fa-id-card"></i> Chat ID</label>
                    <input type="text" 
                           name="chat_id" 
                           value="<?= htmlspecialchars($TELEGRAM_CHAT_ID) ?>"
                           placeholder="Ej: -1001234567890 (número negativo para canales)"
                           required>
                    <small>Chat ID del canal (número negativo como -100XXXXXXXXX)</small>
                </div>
                
                <div class="form-group">
                    <label class="checkbox-group">
                        <input type="checkbox" name="telegram_enabled" <?= $TELEGRAM_ENABLED ? 'checked' : '' ?>>
                        <span><i class="fa fa-check-circle"></i> Habilitar envío a Telegram</span>
                    </label>
                </div>
                
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>Configuración para CANAL:</strong>
                    <ol>
                        <li>Crea un canal en Telegram</li>
                        <li>Agrega el bot como <strong>ADMINISTRADOR</strong></li>
                        <li>El Chat ID será negativo (ej: <code>-1001234567890</code>)</li>
                        <li>Usa <a href="https://t.me/userinfobot" target="_blank">@userinfobot</a> para verificar</li>
                    </ol>
                </div>
            </div>
            <div class="custom-modal-footer">
                <button type="button" class="btn-custom btn-custom-secondary" onclick="cerrarModal()">
                    <i class="fa fa-times"></i> Cerrar
                </button>
                <button type="submit" name="test_telegram" class="btn-custom btn-custom-info">
                    <i class="fa fa-paper-plane"></i> Probar
                </button>
                <button type="submit" name="save_telegram_config" class="btn-custom btn-custom-success">
                    <i class="fa fa-save"></i> Guardar
                </button>
            </div>
        </form>
    </div>
</div>

<div class="col-md-10 mx-auto">
    <div class="card-body">
        
        <?php if ($result): ?>
            <div class="alert alert-<?= $result['success'] ? 'success' : 'danger' ?> alert-dismissible fade show">
                <i class="fa fa-<?= $result['success'] ? 'check-circle' : 'exclamation-triangle' ?>"></i>
                <?= htmlspecialchars($result['message']) ?>
                <?php if (isset($result['file'])): ?>
                    <br><small><?= $result['file'] ?> (<?= $result['size'] ?> KB)</small>
                <?php endif; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>

        <div class="card text-white ctluser-main">
            <div class="card-header ctheading text-center">
                <h2><i class="fa fa-database"></i> GESTIÓN DE BACKUPS</h2>
                <small>Base de datos: <strong>api/.db.db</strong></small>
                <?php if ($TELEGRAM_ENABLED && !empty($TELEGRAM_BOT_TOKEN) && !empty($TELEGRAM_CHAT_ID)): ?>
                    <span class="badge badge-success ml-2">
                        <i class="fa fa-telegram"></i> Telegram Activo
                    </span>
                <?php endif; ?>
            </div>

            <div class="card-body">
                
                <div class="text-right mb-3">
                    <button type="button" class="btn btn-info" onclick="abrirModal()">
                        <i class="fa fa-telegram"></i> Configurar Telegram
                    </button>
                </div>
                
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="card bg-secondary">
                            <div class="card-header">
                                <h5><i class="fa fa-cloud-upload"></i> Backup Local</h5>
                            </div>
                            <div class="card-body">
                                <form method="post">
                                    <button type="submit" name="create_backup" class="btn btn-success btn-block">
                                        <i class="fa fa-plus-circle"></i> CREAR BACKUP
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card bg-primary">
                            <div class="card-header">
                                <h5><i class="fa fa-telegram"></i> Backup + Telegram</h5>
                            </div>
                            <div class="card-body">
                                <form method="post">
                                    <button type="submit" name="create_backup_telegram" class="btn btn-info btn-block" <?= empty($TELEGRAM_BOT_TOKEN) || empty($TELEGRAM_CHAT_ID) ? 'disabled' : '' ?>>
                                        <i class="fa fa-paper-plane"></i> CREAR Y ENVIAR
                                    </button>
                                </form>
                                <?php if (empty($TELEGRAM_BOT_TOKEN) || empty($TELEGRAM_CHAT_ID)): ?>
                                    <small class="text-warning">⚠️ Configura Telegram primero</small>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card bg-warning">
                            <div class="card-header">
                                <h5><i class="fa fa-trash-o"></i> Mantenimiento</h5>
                            </div>
                            <div class="card-body">
                                <form method="post">
                                    <button type="submit" name="clean_backups" class="btn btn-warning btn-block" onclick="return confirm('¿Eliminar backups antiguos?')">
                                        <i class="fa fa-clock-o"></i> LIMPIAR ANTIGUOS
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card bg-secondary">
                            <div class="card-header">
                                <h5><i class="fa fa-upload"></i> Subir Backup</h5>
                            </div>
                            <div class="card-body">
                                <form method="post" enctype="multipart/form-data">
                                    <div class="form-row">
                                        <div class="col-md-8">
                                            <input type="file" name="backup_file" class="form-control-file" accept=".zip" required>
                                        </div>
                                        <div class="col-md-4">
                                            <button type="submit" name="upload_backup" class="btn btn-info btn-block">
                                                <i class="fa fa-arrow-up"></i> SUBIR
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <hr>

                <h4><i class="fa fa-list"></i> Backups Disponibles</h4>
                
                <?php if (empty($backups)): ?>
                    <div class="alert alert-info">No hay backups guardados.</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-dark table-hover">
                            <thead>
                                <tr><th>#</th><th>Archivo</th><th>Fecha</th><th>Tamaño</th><th>Acciones</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach ($backups as $index => $backup): ?>
                                <tr>
                                    <td><?= $index + 1 ?></td>
                                    <td><i class="fa fa-file-archive-o"></i> <?= htmlspecialchars($backup['name']) ?></td>
                                    <td><?= $backup['date'] ?></td>
                                    <td><?= $backup['size'] ?> KB</a>
                                    <td>
                                        <a href="?download=<?= urlencode($backup['name']) ?>" class="btn btn-sm btn-info">Descargar</a>
                                        <a href="?restore=<?= urlencode($backup['name']) ?>" class="btn btn-sm btn-warning" onclick="return confirm('¿Restaurar?')">Restaurar</a>
                                        <a href="?delete=<?= urlencode($backup['name']) ?>" class="btn btn-sm btn-danger" onclick="return confirm('¿Eliminar?')">Eliminar</a>
                                    </a>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                         </a>
                    </div>
                <?php endif; ?>
                
                <div class="alert alert-warning mt-3">
                    <i class="fa fa-info-circle"></i>
                    <strong>Información:</strong>
                    <ul class="mb-0 mt-2">
                        <li>✅ Base de datos: <strong>api/.db.db</strong></li>
                        <li>✅ Los backups se guardan en <strong>/backups/</strong></li>
                        <li>✅ Al restaurar se crea un backup automático</li>
                        <li>✅ Configuración guardada en <strong>telegram_config.json</strong></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function abrirModal() {
    document.getElementById('telegramModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function cerrarModal() {
    document.getElementById('telegramModal').style.display = 'none';
    document.body.style.overflow = 'auto';
}

<?php if ($showModal): ?>
    abrirModal();
<?php endif; ?>

document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        cerrarModal();
    }
});

document.getElementById('telegramModal').addEventListener('click', function(e) {
    if (e.target === this) {
        cerrarModal();
    }
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>