<?php
session_start();
if (!isset($_SESSION['user'])) die("Acceso restringido");

require_once("includes/db.php");
include("includes/header.php");

// 📁 archivo sqlite real
$db_file = __DIR__ . "/../api/.db.db";

// carpeta backups
$dir = __DIR__ . "/backups/";
if (!file_exists($dir)) mkdir($dir, 0777, true);

// telegram
$token = "AQUI_TU_TOKEN";
$chat_id = "AQUI_TU_CHAT_ID";

// acciones
if (isset($_GET['action'])) {

    if ($_GET['action'] == "backup") {
        $date = date("Y-m-d_H-i-s");
        $backup = $dir . "backup_$date.db";

        copy($db_file, $backup);

        header("Location: gestor_backups.php?ok=1");
        exit;
    }

    if ($_GET['action'] == "telegram") {
        $date = date("Y-m-d_H-i-s");
        $backup = $dir . "backup_$date.db";

        copy($db_file, $backup);

        // enviar
        $url = "https://api.telegram.org/bot$token/sendDocument";

        $post = [
            'chat_id' => $chat_id,
            'document' => new CURLFile(realpath($backup))
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        curl_close($ch);

        header("Location: gestor_backups.php?ok=2");
        exit;
    }

    if ($_GET['action'] == "delete_all") {
        foreach (glob($dir . "*.db") as $file) unlink($file);
        header("Location: gestor_backups.php");
        exit;
    }
}

// listar
$files = glob($dir . "*.db");
?>

<div class="container mt-4">

<h4>📦 Gestión de Backups</h4>

<?php if (isset($_GET['ok'])): ?>
<div class="alert alert-success">Operación completada</div>
<?php endif; ?>

<div class="row">

    <div class="col-md-4">
        <div class="card bg-dark text-white p-3">
            <h5>💾 Backup Local</h5>
            <a href="?action=backup" class="btn btn-success mt-2">Crear Backup</a>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card bg-dark text-white p-3">
            <h5>🤖 Backup + Telegram</h5>
            <a href="?action=telegram" class="btn btn-primary mt-2">Crear y Enviar</a>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card bg-dark text-white p-3">
            <h5>🧹 Mantenimiento</h5>
            <a href="?action=delete_all" class="btn btn-warning mt-2">Limpiar</a>
        </div>
    </div>

</div>

<hr>

<h5>📂 Backups disponibles</h5>

<table class="table table-dark table-striped">
<tr>
<th>Archivo</th>
<th>Tamaño</th>
<th>Acciones</th>
</tr>

<?php foreach ($files as $file): ?>
<tr>
<td><?= basename($file) ?></td>
<td><?= round(filesize($file)/1024/1024,2) ?> MB</td>
<td>
<a href="backups/<?= basename($file) ?>" class="btn btn-info btn-sm">Descargar</a>
</td>
</tr>
<?php endforeach; ?>

</table>

</div>

<?php include("includes/footer.php"); ?>