<?php
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) { header("Location: index.php"); exit; }
if ($_SESSION['nivel'] !== 'admin') { header("Location: index.php"); exit; }

require_once 'conexao.php'; // Traz $connGeral e $connUser
require_once 'funcao_backup.php'; // Inclui o motor

$msg = ""; $msg_tipo = "";

// --- 1. BUSCA CONFIGURAÇÕES DO SITE (NOME E COR) ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config WHERE id=1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }

// --- 2. AÇÕES DE BACKUP ---
if (isset($_POST['gerar_manual'])) {
    if (gerarBackupCompleto('Manual')) {
        $msg = "Backup criado com sucesso!"; $msg_tipo = "success";
    } else {
        $msg = "Erro ao criar arquivo ZIP. Verifique permissões da pasta 'backups'."; $msg_tipo = "danger";
    }
}

if (isset($_POST['salvar_auto'])) {
    $status = isset($_POST['status']) ? 'ativo' : 'inativo';
    $tempo  = $_POST['tempo'];
    $horario = $_POST['horario'];
    $check = $connGeral->query("SELECT id FROM backup_automatizado WHERE id=1")->fetch();
    if ($check) {
        $connGeral->prepare("UPDATE backup_automatizado SET status=?, tempo=?, horario=? WHERE id=1")->execute([$status, $tempo, $horario]);
    } else {
        $connGeral->prepare("INSERT INTO backup_automatizado (id, status, tempo, horario) VALUES (1, ?, ?, ?)")->execute([$status, $tempo, $horario]);
    }
    $msg = "Configuração automática salva!"; $msg_tipo = "info";
}

if (isset($_GET['del'])) {
    $id_del = (int)$_GET['del'];
    $file = $connGeral->prepare("SELECT local FROM arquivo_backup WHERE id=?");
    $file->execute([$id_del]);
    $f = $file->fetch();
    if ($f) {
        $caminho = __DIR__ . "/backups/" . $f['local'];
        if (file_exists($caminho)) { unlink($caminho); }
        $connGeral->prepare("DELETE FROM arquivo_backup WHERE id=?")->execute([$id_del]);
        $msg = "Backup excluído."; $msg_tipo = "warning";
    }
}

// --- 3. BUSCAR LISTAGEM ---
$backups = $connGeral->query("SELECT * FROM arquivo_backup ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
$config_auto = $connGeral->query("SELECT * FROM backup_automatizado WHERE id=1")->fetch(PDO::FETCH_ASSOC);
if (!$config_auto) $config_auto = ['status'=>'inativo', 'tempo'=>'diario', 'horario'=>'03:00'];
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Backups | <?= htmlspecialchars($nomePainel) ?></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: <?= $corPrimaria ?>; 
            --bg-body: #151521; 
            --bg-card: #1e1e2d; 
        }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        
        /* Menu Lateral */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); padding: 20px; border-right: 1px solid #333; transition: 0.3s; z-index: 1050; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; margin-bottom: 2px; display: flex; align-items: center; gap: 10px; transition: 0.2s; text-decoration: none; font-size: 0.9rem; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 20px 0 10px 12px; }

        .card-custom { background: var(--bg-card); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; }
        .table-dark { background: var(--bg-card); --bs-table-bg: var(--bg-card); }
        .form-control, .form-select { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; }

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 15px; } .mobile-toggle { display: block !important; }
        }
        .mobile-toggle { display: none; font-size: 1.5rem; color: #fff; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white text-center"><i class="fas fa-tv text-primary"></i> <?= htmlspecialchars($nomePainel) ?></h4>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        
        <div class="nav-group-title">Administração</div>
        <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Gerenciar Perfis</a>
        <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores DNS</a>
        <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Gestão de Admins</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> Config. E-mail</a>
        <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
        <a href="gerenciar_backups.php" class="nav-link active"><i class="fas fa-database"></i> Backups</a>
        <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Config. Geral</a>

        <div class="nav-group-title">Operacional</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="status_online.php" class="nav-link"><i class="fas fa-wifi"></i> Monitor Online</a>
        
        <hr class="border-secondary mt-4"><a href="sair.php" class="nav-link text-danger"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Gerenciador de Backups</h3>
    </div>

    <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

    <div class="row g-4">
        <div class="col-md-6">
            <div class="card card-custom h-100 border-top border-3 border-primary p-4 shadow-sm">
                <h5 class="mb-3 text-primary"><i class="fas fa-hand-pointer me-2"></i> Backup Manual</h5>
                <p class="text-white-50">Gera um arquivo ZIP completo com as bases Geral, Acessos e Usuários imediatamente.</p>
                <form method="POST" class="mt-auto"><button type="submit" name="gerar_manual" class="btn btn-primary w-100 fw-bold"><i class="fas fa-download me-2"></i> GERAR AGORA</button></form>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card card-custom h-100 border-top border-3 border-warning p-4 shadow-sm">
                <h5 class="mb-3 text-warning"><i class="fas fa-clock me-2"></i> Backup Automático</h5>
                <form method="POST">
                    <div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" name="status" id="chkAuto" <?= ($config_auto['status']=='ativo')?'checked':'' ?>><label class="form-check-label text-white" for="chkAuto">Ativar Automação</label></div>
                    <div class="row g-2">
                        <div class="col-6"><label class="small text-white-50">Frequência</label><select name="tempo" class="form-select"><option value="diario" <?= ($config_auto['tempo']=='diario')?'selected':'' ?>>Diário</option><option value="semanal" <?= ($config_auto['tempo']=='semanal')?'selected':'' ?>>Semanal</option></select></div>
                        <div class="col-6"><label class="small text-white-50">Horário</label><input type="time" name="horario" class="form-control" value="<?= $config_auto['horario'] ?>"></div>
                    </div>
                    <button type="submit" name="salvar_auto" class="btn btn-outline-warning w-100 mt-3 fw-bold">SALVAR CONFIGURAÇÃO</button>
                </form>
            </div>
        </div>

        <div class="col-12">
            <div class="card card-custom">
                <div class="card-header bg-transparent border-0 p-3"><h5 class="mb-0 text-white"><i class="fas fa-history me-2"></i> Histórico de Arquivos</h5></div>
                <div class="table-responsive">
                    <table class="table table-dark table-hover align-middle mb-0">
                        <thead><tr class="text-white-50 small text-uppercase"><th class="ps-4">Arquivo</th><th>Data / Hora</th><th>Tipo</th><th>Tamanho</th><th class="text-end pe-4">Ações</th></tr></thead>
                        <tbody>
                            <?php if(empty($backups)): ?><tr><td colspan="5" class="text-center py-4 text-white-50">Nenhum backup encontrado.</td></tr><?php else: ?>
                            <?php foreach($backups as $b): ?>
                            <tr>
                                <td class="ps-4 text-info fw-bold"><i class="fas fa-file-archive me-2"></i> <?= htmlspecialchars($b['local']) ?></td>
                                <td><?= date('d/m/Y H:i', strtotime($b['data'])) ?></td>
                                <td><span class="badge <?= ($b['tipo']=='Manual')?'bg-primary':'bg-warning text-dark' ?>"><?= $b['tipo'] ?></span></td>
                                <td><?= $b['size'] ?></td>
                                <td class="text-end pe-4">
                                    <a href="backups/<?= $b['local'] ?>" download class="btn btn-sm btn-success rounded-circle me-1"><i class="fas fa-download"></i></a>
                                    <a href="?del=<?= $b['id'] ?>" class="btn btn-sm btn-danger rounded-circle" onclick="return confirm('Excluir este backup?')"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
</script>
</body>
</html>
