<?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';
require_once 'funcao_backup.php'; // Inclui o motor

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

// --- AÇÕES DO USUÁRIO ---

// 1. Gerar Backup Manual
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";
    }
}

// 2. Salvar Configuração Automática
if (isset($_POST['salvar_auto'])) {
    $status = isset($_POST['status']) ? 'ativo' : 'inativo';
    $tempo  = $_POST['tempo']; // diario, semanal, mensal
    $horario = $_POST['horario'];
    
    // Verifica se já existe config (ID 1)
    $check = $connGeral->query("SELECT id FROM backup_automatizado WHERE id=1")->fetch();
    if ($check) {
        $sql = "UPDATE backup_automatizado SET status=?, tempo=?, horario=? WHERE id=1";
        $connGeral->prepare($sql)->execute([$status, $tempo, $horario]);
    } else {
        $sql = "INSERT INTO backup_automatizado (id, status, tempo, horario) VALUES (1, ?, ?, ?)";
        $connGeral->prepare($sql)->execute([$status, $tempo, $horario]);
    }
    $msg = "Configuração automática salva!"; $msg_tipo = "info";
}

// 3. Excluir Backup
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); } // Deleta arquivo físico
        $connGeral->prepare("DELETE FROM arquivo_backup WHERE id=?")->execute([$id_del]); // Deleta do banco
        $msg = "Backup excluído."; $msg_tipo = "warning";
    }
}

// --- BUSCAR DADOS ---
// Lista de Backups
$backups = $connGeral->query("SELECT * FROM arquivo_backup ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
// Configuração Auto
$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>Gerenciar Backups</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>
        body { background: #151521; color: #fff; font-family: 'Segoe UI', sans-serif; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: #1e1e2d; padding: 20px; border-right: 1px solid #333; z-index: 1000; }
        .main-content { margin-left: 260px; padding: 30px; }
        .card-custom { background: #1e1e2d; border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; }
        .table-dark { background: #1e1e2d; --bs-table-bg: #1e1e2d; color: #fff; }
        .table-dark td { border-color: #333; vertical-align: middle; }
        .form-control, .form-select { background: #2b2b40; border: 1px solid #444; color: #fff; }
        .form-control:focus, .form-select:focus { background: #32324a; border-color: #7367f0; color: #fff; }
        @media (max-width: 768px) { .sidebar{display:none;} .main-content{margin-left:0;} }
    </style>
</head>
<body>

<nav class="sidebar">
    <h4 class="mb-4 fw-bold text-white"><i class="fas fa-tv text-primary"></i> Painel</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="btn btn-dark text-start border-0 py-2"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="gerenciar_backups.php" class="btn btn-primary text-start border-0 py-2"><i class="fas fa-database me-2"></i> Backups</a>
    </div>
</nav>

<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Gerenciador de Backups</h3>
        <span class="text-white-50">Segurança dos seus dados</span>
    </div>

    <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show"><?= $msg ?><button class="btn-close btn-close-white" 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">
                <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 contendo os 3 bancos de dados (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">
                <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" 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 (Todo dia)</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 btn-sm">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> <?= $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 me-1" title="Baixar"><i class="fas fa-download"></i></a>
                                    <a href="?del=<?= $b['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Excluir este backup?')" title="Excluir"><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>
</body>
</html>
