<?php
session_start();
require_once 'conexao.php';

// Verifica Login e se é Admin
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true || strtolower($_SESSION['nivel']) !== 'admin') {
    header("Location: login.php"); exit;
}

// --- FUNÇÃO PARA GERAR O SQL (BACKUP NATIVO) ---
function realizarBackup($pdo, $nomeExibicao) {
    if (!$pdo) return false;

    try {
        $sql = "-- Backup: $nomeExibicao\n-- Gerado em: " . date('d/m/Y H:i:s') . "\n";
        $sql .= "SET FOREIGN_KEY_CHECKS=0;\n\n";

        $tabelas = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
        foreach ($tabelas as $tabela) {
            $create = $pdo->query("SHOW CREATE TABLE `$tabela`")->fetch(PDO::FETCH_ASSOC);
            $sql .= "\n\n" . $create['Create Table'] . ";\n\n";

            $dados = $pdo->query("SELECT * FROM `$tabela`")->fetchAll(PDO::FETCH_ASSOC);
            foreach ($dados as $linha) {
                $colunas = array_map(function($c) { return "`$c`"; }, array_keys($linha));
                $valores = array_map(function($v) use ($pdo) { 
                    return ($v === null) ? "NULL" : $pdo->quote($v); 
                }, array_values($linha));
                $sql .= "INSERT INTO `$tabela` (" . implode(', ', $colunas) . ") VALUES (" . implode(', ', $valores) . ");\n";
            }
        }
        $sql .= "\nSET FOREIGN_KEY_CHECKS=1;";
        return $sql;
    } catch (Exception $e) { return false; }
}

// --- PROCESSAR O DOWNLOAD ---
if (isset($_GET['download'])) {
    $tipo = $_GET['download'];
    $dataStr = date('Y-m-d_H-i');
    $conteudo = "";
    $nomeArq = "";

    // Mapeamento das variáveis confirmadas no seu functions.php
    if ($tipo === 'geral' && isset($painel_geral)) {
        $conteudo = realizarBackup($painel_geral, 'Configuracoes_Geral');
        $nomeArq = "backup_geral_{$dataStr}.sql";
    } elseif ($tipo === 'user' && isset($painel_user)) {
        $conteudo = realizarBackup($painel_user, 'Clientes_Usuarios');
        $nomeArq = "backup_usuarios_{$dataStr}.sql";
    } elseif ($tipo === 'acesso' && isset($painel_acessos)) {
        $conteudo = realizarBackup($painel_acessos, 'Logs_Acessos');
        $nomeArq = "backup_acessos_{$dataStr}.sql";
    }

    if ($conteudo) {
        header('Content-Type: application/sql');
        header('Content-Disposition: attachment; filename="' . $nomeArq . '"');
        echo $conteudo;
        exit;
    } else {
        echo "<script>alert('Erro: A conexão para este backup não foi definida no conexao.php'); window.location='gerenciar_backup.php';</script>";
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Central de Backup Individual</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: #7367f0; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; padding: 20px; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }
        .main-content { margin-left: 260px; padding: 40px; }
        .card-backup { background: var(--bg-card); border: 1px solid #2b2b40; border-radius: 12px; padding: 30px; text-align: center; transition: 0.3s; }
        .card-backup:hover { border-color: var(--primary); transform: translateY(-5px); }
        .icon-box { width: 60px; height: 60px; background: rgba(115, 103, 240, 0.1); color: var(--primary); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; font-size: 1.5rem; }
        .btn-download { background: var(--primary); color: #fff; border: none; width: 100%; padding: 12px; border-radius: 8px; font-weight: 600; text-decoration: none; display: inline-block; }
    </style>
</head>
<body>

<nav class="sidebar">
    <div class="nav flex-column mt-4">
        <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <a href="gerenciar_backup.php" class="nav-link active"><i class="fas fa-database"></i> Backup Individual</a>
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-power-off"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <h2 class="fw-bold text-white mb-4">Central de Backup Individual</h2>
    <div class="row g-4">
        <div class="col-md-4">
            <div class="card-backup">
                <div class="icon-box"><i class="fas fa-cogs"></i></div>
                <h5>Geral (Configurações)</h5>
                <p class="small text-white-50 mb-4">DNS, SMTP, e Perfil</p>
                <a href="?download=geral" class="btn-download">Baixar SQL</a>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card-backup">
                <div class="icon-box"><i class="fas fa-users"></i></div>
                <h5>Usuários e Clientes</h5>
                <p class="small text-white-50 mb-4">Logins e Vencimentos</p>
                <a href="?download=user" class="btn-download">Baixar SQL</a>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card-backup">
                <div class="icon-box"><i class="fas fa-history"></i></div>
                <h5>Logs de Acesso</h5>
                <p class="small text-white-50 mb-4">Histórico do Painel</p>
                <a href="?download=acesso" class="btn-download">Baixar SQL</a>
            </div>
        </div>
    </div>
</main>
</body>
</html>