<?php
session_start();

// Apenas o Administrador tem acesso
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { 
    header("Location: index.php"); 
    exit; 
}

require_once 'conexao.php'; 

$isAdmin = true;
$msg = "";
$msg_tipo = "";
$total_msg_nao_lidas = 0; // Para o menu lateral

// --- DIRETÓRIO DE BACKUPS ---
$backup_dir = __DIR__ . '/backups_csp';
if (!is_dir($backup_dir)) {
    @mkdir($backup_dir, 0777, true);
}
@chmod($backup_dir, 0777);

// --- LÓGICA DE DOWNLOAD DE BACKUP ---
if (isset($_GET['download'])) {
    $arquivo = basename($_GET['download']); 
    $filepath = $backup_dir . '/' . $arquivo;
    
    if (file_exists($filepath) && pathinfo($filepath, PATHINFO_EXTENSION) === 'xml') {
        header('Content-Description: File Transfer');
        header('Content-Type: application/xml');
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);
        exit; 
    } else {
        $msg = "Arquivo não encontrado ou inválido para download.";
        $msg_tipo = "danger";
    }
}

// --- 1. BUSCA O SERVIDOR CSP NO BANCO ---
$stmt = $connGeral->query("SELECT url, porta, usuario, senha, protocolo FROM painel LIMIT 1");
$srv = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$srv) die("ERRO: Nenhum servidor CSP configurado.");

$ip = str_replace(['http://', 'https://', '/'], '', $srv['url']);
$porta = trim($srv['porta']); 
$user_csp = trim($srv['usuario']);
$pass_csp = trim($srv['senha']);
$csp_base_url = "{$srv['protocolo']}://{$ip}:{$porta}";
$csp_auth = "{$user_csp}:{$pass_csp}";

// --- CONFIGURAÇÕES VISUAIS DO MENU ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config 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) { }

// --- FUNÇÃO PARA SESSÃO CSP ---
function getCspSession($url, $user, $pass, $auth) {
    $ch = curl_init();
    $login_xml = "<cws-status-req ver=\"1.0\">\n<cws-login>\n<user name=\"{$user}\" password=\"{$pass}\"/>\n</cws-login>\n</cws-status-req>";

    curl_setopt($ch, CURLOPT_URL, $url . "/xmlHandler");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $login_xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/xml']);

    $res = curl_exec($ch);
    curl_close($ch);

    if ($res && preg_match('/state="loggedIn"/i', $res) && preg_match('/session-id="([^"]+)"/i', $res, $matches)) {
        return $matches[1]; 
    }
    return false;
}

// --- FUNÇÃO PARA LER O XML ---
function getCspXml($url, $user, $pass, $auth) {
    $session_id = getCspSession($url, $user, $pass, $auth);
    if (!$session_id) return "ERRO_HTTP|Falha no Login da CSP. Verifique as credenciais.";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . "/xmlHandler?command=fetch-cfg");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Cookie: sessionId={$session_id}"]);
    
    $xml_raw = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpcode == 200 && !empty($xml_raw)) {
        if (strpos($xml_raw, 'Super-user required') !== false) return "ERRO_HTTP|Acesso negado: Super User requerido.";
        return trim($xml_raw);
    }
    return "ERRO_HTTP|Código HTTP retornado ao tentar ler: $httpcode.";
}

// --- FUNÇÃO PARA REINICIAR (SHUTDOWN) VIA API ---
function restartCsp($url, $user, $pass, $auth) {
    $session_id = getCspSession($url, $user, $pass, $auth);
    if (!$session_id) return false;

    $ch = curl_init();
    $restart_xml = "<cws-command-req ver=\"1.0\">\n<session session-id=\"{$session_id}\"/>\n<command command=\"shutdown\"/>\n</cws-command-req>";

    curl_setopt($ch, CURLOPT_URL, $url . "/xmlHandler");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $restart_xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/xml', "Cookie: sessionId={$session_id}"]);
    
    $result = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpcode == 0 || $result === false) return true;
    if ($httpcode == 200 && strpos($result, 'IllegalArgumentException') === false) return true;

    return false;
}

// --- 2. PROCESSAR AÇÕES (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao'])) {
    $acao = $_POST['acao'];

    // FAZER BACKUP
    if ($acao === 'fazer_backup') {
        $xml = getCspXml($csp_base_url, $user_csp, $pass_csp, $csp_auth);
        
        if (is_string($xml) && strpos($xml, 'ERRO_') !== 0) {
            $filename = 'backup_csp_' . date('Y-m-d_H-i-s') . '.xml';
            
            if (@file_put_contents($backup_dir . '/' . $filename, $xml)) {
                $msg = "Backup <b>$filename</b> criado com sucesso no painel!";
                $msg_tipo = "success";
            } else {
                $msg = "Erro ao guardar o ficheiro. Sem permissão de escrita na pasta <b>$backup_dir</b>.";
                $msg_tipo = "danger";
            }
        } else {
            $erro_msg = is_string($xml) ? str_replace("ERRO_HTTP|", "", $xml) : "Erro desconhecido ao comunicar com a CSP.";
            $msg = "Falha ao ler a configuração: <b>$erro_msg</b>";
            $msg_tipo = "danger";
        }
    }

    // EXCLUIR BACKUP
    if ($acao === 'excluir_backup' && isset($_POST['arquivo'])) {
        $arquivo = basename($_POST['arquivo']);
        $filepath = $backup_dir . '/' . $arquivo;
        if (file_exists($filepath)) {
            unlink($filepath);
            $msg = "Backup <b>$arquivo</b> removido com sucesso!";
            $msg_tipo = "success";
        }
    }

    // RESTAURAR BACKUP (COM PODER DE SUDO E CAMINHO EXATO)
    if ($acao === 'restaurar_backup' && isset($_POST['arquivo'])) {
        $arquivo = basename($_POST['arquivo']);
        $filepath = $backup_dir . '/' . $arquivo;
        
        // Caminho oficial validado
        $destino_csp = '/usr/local/csp/csp/config/proxy.xml'; 
        
        if (file_exists($filepath)) {
            $xml_content = file_get_contents($filepath);
            
            // Injeta o arquivo direto no Linux
            if (@file_put_contents($destino_csp, $xml_content)) {
                
                // 1. Desliga suavemente via API (se possível)
                restartCsp($csp_base_url, $user_csp, $pass_csp, $csp_auth);
                
                // 2. FORÇA BRUTA: Inicia/Reinicia usando SUDO no terminal via PHP
                @exec("sudo /usr/local/csp/csp/csp.sh restart > /dev/null 2>&1");
                @exec("sudo /usr/local/csp/csp/csp.sh start > /dev/null 2>&1");
                
                $msg = "<i class='fas fa-check-circle me-2'></i> Backup <b>$arquivo</b> restaurado com sucesso na pasta oficial da CSP! A CSP foi reiniciada.";
                $msg_tipo = "success";
                sleep(2); 
            } else {
                $msg = "<b>Bloqueio de Permissão do Linux:</b> O painel não conseguiu injetar o arquivo.<br>Rode este comando no terminal da sua VPS:<br><code class='bg-dark p-2 rounded mt-2 d-inline-block text-white'>chmod 777 /usr/local/csp/csp/config/proxy.xml</code>";
                $msg_tipo = "danger";
            }
        } else {
            $msg = "Arquivo de backup não encontrado no servidor.";
            $msg_tipo = "warning";
        }
    }
}

// --- 3. LISTAR BACKUPS ---
$backups = [];
if (is_dir($backup_dir)) {
    $files = scandir($backup_dir);
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..' && pathinfo($file, PATHINFO_EXTENSION) === 'xml') {
            $filepath = $backup_dir . '/' . $file;
            $backups[] = [
                'nome' => $file,
                'data' => filemtime($filepath),
                'tamanho' => filesize($filepath)
            ];
        }
    }
    // Ordena do mais recente para o mais antigo
    usort($backups, function($a, $b) {
        return $b['data'] - $a['data'];
    });
}

function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 
    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Backups CSP | <?= 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; 
            --text-color: #d0d2d6;
            --border-color: #2b2b40;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0); 
        }
        body { background: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        /* Sidebar Restourada com as mesmas especificações Premium */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        .nav-link[data-bs-toggle="collapse"] .submenu-icon { transition: transform 0.3s; }
        .nav-link[data-bs-toggle="collapse"][aria-expanded="true"] .submenu-icon { transform: rotate(180deg); }
        
        /* Main Content ajustado para Flexbox p/ empurrar Rodapé */
        .main-content { margin-left: 260px; transition: 0.3s; display: flex; flex-direction: column; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }

        /* Elementos Premium */
        .card-custom { background-color: var(--bg-card) !important; border: 1px solid var(--border-color) !important; border-radius: 12px; overflow: hidden; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        
        /* Tabela Dinâmica que respeita Tema Claro/Escuro DE VERDADE */
        .table-custom { width: 100%; margin-bottom: 0; border-collapse: separate; border-spacing: 0; background: transparent !important; }
        .table-custom th { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: #a6a6b7 !important; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap; }
        .table-custom td { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: var(--text-color) !important; vertical-align: middle; padding: 15px; font-size: 0.95rem; }
        .table-custom tbody tr:hover td { background-color: rgba(115, 103, 240, 0.08) !important; }

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; } 
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            .top-header { flex-direction: column; align-items: flex-start; gap: 15px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); padding: 15px 20px; }
        }
        
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<main class="main-content d-flex flex-column min-vh-100">
    <div class="top-header">
        <div class="d-flex align-items-center w-100">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-save me-2"></i> Gerenciador de Backups CSP</div>
        </div>
        
        <div>
            <form method="POST" class="m-0" onsubmit="return confirm('Deseja criar um novo backup agora?')">
                <input type="hidden" name="acao" value="fazer_backup">
                <button type="submit" class="btn btn-success fw-bold rounded-pill shadow-sm" style="letter-spacing: 0.5px;">
                    <i class="fas fa-cloud-download-alt me-2"></i> FAZER BACKUP AGORA
                </button>
            </form>
        </div>
    </div>

    <div class="container-fluid p-3 p-md-4 flex-grow-1">

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

        <div class="alert alert-info shadow-sm border-0 mb-4 px-4 py-3" style="background-color: rgba(0, 207, 232, 0.1); color: #00cfe8;">
            <i class="fas fa-info-circle me-2 fs-5 float-start mt-1"></i> 
            <span style="display: block; margin-left: 35px; line-height: 1.6;">
                Aqui ficam guardados os ficheiros originais da sua CSP (<code>proxy.xml</code>). <br>
                Quando clica em <b>Restaurar</b>, o painel envia o ficheiro escolhido de volta para a VPS e reinicia a CSP automaticamente para aplicar as alterações na mesma hora.
            </span>
        </div>

        <div class="card card-custom shadow-lg">
            <div class="table-responsive">
                <table class="table table-custom table-hover align-middle">
                    <thead>
                        <tr>
                            <th class="ps-4">Nome do Arquivo</th>
                            <th>Data e Hora</th>
                            <th>Tamanho</th>
                            <th class="text-end pe-4">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($backups)): ?>
                            <tr>
                                <td colspan="4" class="text-center py-5">
                                    <div class="text-muted mb-2"><i class="fas fa-box-open fs-1 opacity-50"></i></div>
                                    <span style="color: var(--text-color); opacity: 0.7;">Nenhum backup efetuado ainda.</span><br>
                                    <small style="color: var(--text-color); opacity: 0.5;">Clique no botão verde no topo para criar o seu primeiro backup.</small>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($backups as $bkp): ?>
                            <tr>
                                <td class="ps-4 fw-bold text-info font-monospace"><i class="fas fa-file-code me-2" style="color: var(--text-color); opacity: 0.5;"></i> <?= htmlspecialchars($bkp['nome']) ?></td>
                                <td style="color: var(--text-color);"><?= date('d/m/Y \à\s H:i:s', $bkp['data']) ?></td>
                                <td><span class="badge bg-dark border border-secondary shadow-sm text-white px-2 py-1 fs-6"><?= formatBytes($bkp['tamanho']) ?></span></td>
                                <td class="text-end pe-4 text-nowrap">
                                    <div class="d-flex gap-2 justify-content-end">
                                        <a href="?download=<?= urlencode($bkp['nome']) ?>" class="btn btn-sm btn-outline-info shadow-sm rounded-3" title="Baixar Backup para o PC">
                                            <i class="fas fa-download me-1"></i> Download
                                        </a>

                                        <form method="POST" class="m-0" onsubmit="return confirm('ATENÇÃO: Restaurar este backup irá SOBRESCREVER todas as linhas e usuários atuais pela configuração salva no dia <?= date('d/m/Y', $bkp['data']) ?>.\n\nA CSP será reiniciada. Tem a certeza absoluta que deseja prosseguir?')">
                                            <input type="hidden" name="acao" value="restaurar_backup">
                                            <input type="hidden" name="arquivo" value="<?= $bkp['nome'] ?>">
                                            <button class="btn btn-sm btn-outline-warning shadow-sm rounded-3" title="Restaurar Backup na CSP">
                                                <i class="fas fa-history me-1"></i> Restaurar
                                            </button>
                                        </form>
                                        
                                        <form method="POST" class="m-0" onsubmit="return confirm('Tem a certeza que deseja apagar este backup do servidor do painel?')">
                                            <input type="hidden" name="acao" value="excluir_backup">
                                            <input type="hidden" name="arquivo" value="<?= $bkp['nome'] ?>">
                                            <button class="btn btn-sm btn-outline-danger shadow-sm rounded-3" title="Excluir Arquivo">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </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>
