<?php
// ── POST handlers antes de qualquer output ──────────────────────
$pdo  = db();
$msg  = null;
$msgType = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $msg = 'Token CSRF inválido.'; $msgType = 'error';
    } else {
        $action = $_POST['action'] ?? '';

        // ── Salvar configuração FTP ──
        if ($action === 'save_ftp') {
            set_system_setting('backup_ftp_enabled',  isset($_POST['ftp_enabled']) ? '1' : '0');
            set_system_setting('backup_ftp_host',     trim($_POST['ftp_host']     ?? ''));
            set_system_setting('backup_ftp_port',     (string)(int)($_POST['ftp_port'] ?? 21));
            set_system_setting('backup_ftp_user',     trim($_POST['ftp_user']     ?? ''));
            set_system_setting('backup_ftp_path',     trim($_POST['ftp_path']     ?? '/backups'));
            if (!empty($_POST['ftp_pass'])) {
                set_system_setting('backup_ftp_pass', trim($_POST['ftp_pass']));
            }
            // Gera arquivo de config para o backup.sh
            backup_write_config_file($pdo);
            $msg = 'Configuração FTP salva com sucesso!';
        }

        // ── Testar FTP ──
        elseif ($action === 'test_ftp') {
            $host = get_system_setting('backup_ftp_host','');
            $port = (int)get_system_setting('backup_ftp_port', 21);
            $user = get_system_setting('backup_ftp_user','');
            $pass = get_system_setting('backup_ftp_pass','');
            if (!$host || !$user) {
                $msg = 'Configure o FTP antes de testar.'; $msgType = 'error';
            } else {
                // Usa curl para testar (extensão ftp pode não estar instalada)
                $userEsc = escapeshellarg($user . ':' . $pass);
                $urlEsc  = escapeshellarg('ftp://' . $host . ':' . $port . '/');
                $output  = [];
                $code    = 0;
                exec("curl -s --connect-timeout 10 --max-time 15 -l --user {$userEsc} {$urlEsc} 2>&1", $output, $code);
                if ($code === 0) {
                    $msg = "✅ FTP OK! Conectado em {$host}:{$port} com sucesso.";
                } else {
                    $detail = implode(' ', array_slice($output, 0, 2));
                    $msg = "❌ Falha na conexão FTP ({$host}:{$port}): {$detail}"; $msgType = 'error';
                }
            }
        }

        // ── Salvar configuração Google Drive ──
        elseif ($action === 'save_gdrive') {
            set_system_setting('backup_gdrive_enabled', isset($_POST['gdrive_enabled']) ? '1' : '0');
            set_system_setting('backup_gdrive_folder',  trim($_POST['gdrive_folder'] ?? 'MonitorPing-Backups'));
            if (!empty($_POST['gdrive_sa_json'])) {
                $json = trim($_POST['gdrive_sa_json']);
                $decoded = json_decode($json, true);
                if (!$decoded || !isset($decoded['type'])) {
                    $msg = 'JSON da conta de serviço inválido.'; $msgType = 'error';
                } else {
                    set_system_setting('backup_gdrive_sa_json', base64_encode($json));
                    backup_write_config_file($pdo);
                    $msg = 'Configuração Google Drive salva com sucesso!';
                }
            } else {
                backup_write_config_file($pdo);
                $msg = 'Configuração Google Drive salva com sucesso!';
            }
        }

        // ── Disparar backup manual ──
        elseif ($action === 'trigger_backup') {
            $triggerFile = '/opt/backups/monitorping/.backup_trigger';
            file_put_contents($triggerFile, date('Y-m-d H:i:s'));
            $msg = '✅ Backup iniciado! Aguarde até 1 minuto e recarregue a página para ver o arquivo gerado.';
        }

        // ── Deletar backup ──
        elseif ($action === 'delete_backup') {
            $file = basename($_POST['filename'] ?? '');
            if ($file && preg_match('/^monitorping_backup_[\d_\-]+\.tar\.gz$/', $file)) {
                $path = '/opt/backups/monitorping/' . $file;
                if (file_exists($path)) {
                    unlink($path);
                    $msg = "Backup {$file} removido.";
                } else {
                    $msg = 'Arquivo não encontrado.'; $msgType = 'error';
                }
            } else {
                $msg = 'Nome de arquivo inválido.'; $msgType = 'error';
            }
        }
    }
}

// ── Helper: escreve arquivo de config para o backup.sh ──────────
function backup_write_config_file(PDO $pdo): void {
    $dir = '/opt/backups/monitorping';
    if (!is_dir($dir)) return;
    $lines = [
        '#!/bin/sh',
        '# Gerado automaticamente pelo MonitorPing Admin — NÃO EDITE MANUALMENTE',
        '',
        '# FTP',
        'BACKUP_FTP_ENABLED="'  . (get_system_setting('backup_ftp_enabled','0') === '1' ? '1' : '0') . '"',
        'BACKUP_FTP_HOST="'     . addslashes(get_system_setting('backup_ftp_host',''))    . '"',
        'BACKUP_FTP_PORT="'     . (int)get_system_setting('backup_ftp_port', 21)          . '"',
        'BACKUP_FTP_USER="'     . addslashes(get_system_setting('backup_ftp_user',''))    . '"',
        'BACKUP_FTP_PASS="'     . addslashes(get_system_setting('backup_ftp_pass',''))    . '"',
        'BACKUP_FTP_PATH="'     . addslashes(get_system_setting('backup_ftp_path','/backups')) . '"',
        '',
        '# Google Drive',
        'BACKUP_GDRIVE_ENABLED="' . (get_system_setting('backup_gdrive_enabled','0') === '1' ? '1' : '0') . '"',
        'BACKUP_GDRIVE_FOLDER="'  . addslashes(get_system_setting('backup_gdrive_folder','MonitorPing-Backups')) . '"',
        'BACKUP_GDRIVE_SA_JSON="' . get_system_setting('backup_gdrive_sa_json','') . '"',
    ];
    file_put_contents($dir . '/.backup_config.sh', implode("\n", $lines) . "\n");
}

// ── Lê backups disponíveis ───────────────────────────────────────
$backupDir   = '/opt/backups/monitorping';
$backupFiles = [];
if (is_dir($backupDir)) {
    $files = glob($backupDir . '/monitorping_backup_*.tar.gz') ?: [];
    rsort($files);
    foreach ($files as $f) {
        $backupFiles[] = [
            'name'    => basename($f),
            'size'    => filesize($f),
            'mtime'   => filemtime($f),
        ];
    }
}

// ── Configurações salvas ─────────────────────────────────────────
$ftpEnabled     = get_system_setting('backup_ftp_enabled', '0') === '1';
$ftpHost        = get_system_setting('backup_ftp_host', '');
$ftpPort        = get_system_setting('backup_ftp_port', '21');
$ftpUser        = get_system_setting('backup_ftp_user', '');
$ftpPath        = get_system_setting('backup_ftp_path', '/backups');
$hasFtpPass     = !empty(get_system_setting('backup_ftp_pass', ''));

$gdriveEnabled  = get_system_setting('backup_gdrive_enabled', '0') === '1';
$gdriveFolder   = get_system_setting('backup_gdrive_folder', 'MonitorPing-Backups');
$hasGdriveSa    = !empty(get_system_setting('backup_gdrive_sa_json', ''));

function fmt_bytes(int $bytes): string {
    if ($bytes >= 1048576) return round($bytes / 1048576, 1) . ' MB';
    if ($bytes >= 1024)    return round($bytes / 1024, 0) . ' KB';
    return $bytes . ' B';
}

// ── HTML ─────────────────────────────────────────────────────────
require_once __DIR__ . '/../includes/header.php';

$sectionStyle    = "background:#fff;border-radius:16px;border:1px solid #e2e8f0;overflow:hidden;margin-bottom:20px;";
$sectionHdrStyle = "padding:18px 24px;border-bottom:1px solid #e2e8f0;background:#f8fafc;";
$sectionBdyStyle = "padding:24px;";
$inputStyle      = "width:100%;padding:10px 14px;border:1px solid #cbd5e1;border-radius:10px;font-size:0.92rem;font-family:inherit;outline:none;box-sizing:border-box;";
$labelStyle      = "display:block;font-weight:600;font-size:0.85rem;color:#475569;margin-bottom:5px;";
?>

<div style="max-width:1000px;margin:0 auto;display:flex;flex-direction:column;gap:20px;">

    <!-- Header -->
    <div style="background:linear-gradient(135deg,#1e293b,#0f172a);border-radius:20px;padding:28px 32px;color:#f1f5f9;">
        <h1 style="margin:0;font-size:1.6rem;font-weight:900;">💾 Backup do Sistema</h1>
        <p style="margin:6px 0 0;color:#94a3b8;font-size:0.9rem;">
            Backups automáticos diários às 03h · Rotação de 7 dias · FTP e Google Drive
        </p>
    </div>

    <?php if ($msg): ?>
    <div style="padding:14px 18px;background:<?= $msgType==='error'?'#fee2e2':'#dcfce7' ?>;border-left:4px solid <?= $msgType==='error'?'#ef4444':'#22c55e' ?>;color:<?= $msgType==='error'?'#b91c1c':'#166534' ?>;border-radius:10px;font-weight:600;">
        <?= h($msg) ?>
    </div>
    <?php endif; ?>

    <!-- Resumo + Backup Manual -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px;">
        <div style="background:#eff6ff;border:1px solid #93c5fd;border-radius:14px;padding:20px;text-align:center;">
            <div style="font-size:2.2rem;font-weight:900;color:#1e40af;"><?= count($backupFiles) ?></div>
            <div style="font-size:0.78rem;font-weight:700;color:#2563eb;text-transform:uppercase;letter-spacing:.05em;margin-top:4px;">Backups disponíveis</div>
        </div>
        <div style="background:<?= $ftpEnabled?'#f0fdf4':'#f8fafc' ?>;border:1px solid <?= $ftpEnabled?'#86efac':'#e2e8f0' ?>;border-radius:14px;padding:20px;text-align:center;">
            <div style="font-size:1.4rem;margin-bottom:4px;"><?= $ftpEnabled?'✅':'⭕' ?></div>
            <div style="font-size:0.78rem;font-weight:700;color:<?= $ftpEnabled?'#16a34a':'#64748b' ?>;text-transform:uppercase;letter-spacing:.05em;">FTP <?= $ftpEnabled?'Ativo':'Inativo' ?></div>
            <?php if ($ftpEnabled && $ftpHost): ?><div style="font-size:0.75rem;color:#475569;margin-top:4px;"><?= h($ftpHost) ?></div><?php endif; ?>
        </div>
        <div style="background:<?= $gdriveEnabled?'#f0fdf4':'#f8fafc' ?>;border:1px solid <?= $gdriveEnabled?'#86efac':'#e2e8f0' ?>;border-radius:14px;padding:20px;text-align:center;">
            <div style="font-size:1.4rem;margin-bottom:4px;"><?= $gdriveEnabled?'✅':'⭕' ?></div>
            <div style="font-size:0.78rem;font-weight:700;color:<?= $gdriveEnabled?'#16a34a':'#64748b' ?>;text-transform:uppercase;letter-spacing:.05em;">GDrive <?= $gdriveEnabled?'Ativo':'Inativo' ?></div>
            <?php if ($gdriveEnabled && $gdriveFolder): ?><div style="font-size:0.75rem;color:#475569;margin-top:4px;"><?= h($gdriveFolder) ?></div><?php endif; ?>
        </div>
        <!-- Botão backup manual -->
        <form method="post" onsubmit="return confirm('Iniciar backup agora?');" style="display:flex;flex-direction:column;">
            <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="trigger_backup">
            <button type="submit" style="flex:1;background:linear-gradient(135deg,#4f46e5,#4338ca);color:#fff;border:none;border-radius:14px;padding:20px;font-size:0.95rem;font-weight:800;cursor:pointer;transition:opacity .15s;"
                onmouseover="this.style.opacity='.85'" onmouseout="this.style.opacity='1'">
                ⚡ Backup Agora
            </button>
        </form>
    </div>

    <!-- Lista de Backups -->
    <div style="<?= $sectionStyle ?>">
        <div style="<?= $sectionHdrStyle ?>">
            <h3 style="margin:0;font-size:1rem;font-weight:700;color:#0f172a;">📁 Backups Disponíveis</h3>
            <p style="margin:2px 0 0;font-size:0.82rem;color:#64748b;">Últimos 7 dias · Salvos em /opt/backups/monitorping/</p>
        </div>
        <div style="<?= $sectionBdyStyle ?>">
        <?php if (empty($backupFiles)): ?>
            <div style="text-align:center;padding:40px;background:#f8fafc;border-radius:10px;color:#94a3b8;">
                Nenhum backup encontrado ainda. Clique em <strong>⚡ Backup Agora</strong> para gerar o primeiro.
            </div>
        <?php else: ?>
            <div style="overflow-x:auto;">
            <table style="width:100%;border-collapse:collapse;font-size:0.88rem;">
                <thead>
                    <tr style="background:#f8fafc;">
                        <th style="padding:10px 14px;text-align:left;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">Arquivo</th>
                        <th style="padding:10px 14px;text-align:right;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">Tamanho</th>
                        <th style="padding:10px 14px;text-align:left;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">Data</th>
                        <th style="padding:10px 14px;text-align:center;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">Ações</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($backupFiles as $i => $bf):
                    $dt = date('d/m/Y H:i:s', $bf['mtime']);
                    $rowBg = $i % 2 === 0 ? '#fff' : '#f8fafc';
                ?>
                <tr style="background:<?= $rowBg ?>;">
                    <td style="padding:10px 14px;font-family:monospace;font-size:0.82rem;color:#1e293b;">
                        <?= h($bf['name']) ?>
                        <?php if ($i === 0): ?>
                            <span style="background:#dbeafe;color:#1d4ed8;padding:1px 8px;border-radius:20px;font-size:0.7rem;font-weight:700;margin-left:6px;font-family:sans-serif;">Mais recente</span>
                        <?php endif; ?>
                    </td>
                    <td style="padding:10px 14px;text-align:right;font-weight:700;color:#475569;"><?= fmt_bytes($bf['size']) ?></td>
                    <td style="padding:10px 14px;color:#64748b;"><?= $dt ?></td>
                    <td style="padding:10px 14px;text-align:center;">
                        <div style="display:flex;gap:6px;justify-content:center;align-items:center;">
                            <a href="<?= BASE_URL ?>index.php?page=admin_backup_download&file=<?= urlencode($bf['name']) ?>"
                               style="padding:5px 12px;background:#4f46e5;color:#fff;border-radius:7px;font-size:0.78rem;font-weight:700;text-decoration:none;">
                                ⬇ Download
                            </a>
                            <form method="post" onsubmit="return confirm('Remover <?= h($bf['name']) ?>?');" style="margin:0;">
                                <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
                                <input type="hidden" name="action" value="delete_backup">
                                <input type="hidden" name="filename" value="<?= h($bf['name']) ?>">
                                <button type="submit" style="padding:5px 12px;background:#fee2e2;color:#b91c1c;border:1px solid #fca5a5;border-radius:7px;font-size:0.78rem;font-weight:700;cursor:pointer;">
                                    🗑 Remover
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        <?php endif; ?>
        </div>
    </div>

    <!-- Configuração FTP -->
    <div style="<?= $sectionStyle ?>">
        <div style="<?= $sectionHdrStyle ?>display:flex;justify-content:space-between;align-items:center;">
            <div>
                <h3 style="margin:0;font-size:1rem;font-weight:700;color:#0f172a;">📡 Envio Automático via FTP</h3>
                <p style="margin:2px 0 0;font-size:0.82rem;color:#64748b;">Após cada backup, envia automaticamente para um servidor FTP</p>
            </div>
            <span style="background:<?= $ftpEnabled?'#dcfce7':'#f1f5f9' ?>;color:<?= $ftpEnabled?'#16a34a':'#64748b' ?>;padding:4px 14px;border-radius:20px;font-size:0.8rem;font-weight:700;">
                <?= $ftpEnabled ? '✅ Ativo' : '⭕ Inativo' ?>
            </span>
        </div>
        <form method="post" style="<?= $sectionBdyStyle ?>">
            <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="save_ftp">

            <label style="display:inline-flex;align-items:center;gap:10px;cursor:pointer;background:#f8fafc;padding:12px 18px;border-radius:10px;border:1px solid #e2e8f0;margin-bottom:20px;">
                <input type="checkbox" name="ftp_enabled" <?= $ftpEnabled?'checked':'' ?> style="width:18px;height:18px;accent-color:#4f46e5;">
                <span style="font-weight:700;color:#0f172a;font-size:0.9rem;">Habilitar envio FTP após cada backup</span>
            </label>

            <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
                <div>
                    <label style="<?= $labelStyle ?>">Host FTP</label>
                    <input type="text" name="ftp_host" value="<?= h($ftpHost) ?>" placeholder="ftp.seuservidor.com"
                        style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#4f46e5'" onblur="this.style.borderColor='#cbd5e1'">
                </div>
                <div>
                    <label style="<?= $labelStyle ?>">Porta</label>
                    <input type="number" name="ftp_port" value="<?= h($ftpPort) ?>" placeholder="21" min="1" max="65535"
                        style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#4f46e5'" onblur="this.style.borderColor='#cbd5e1'">
                </div>
                <div>
                    <label style="<?= $labelStyle ?>">Usuário FTP</label>
                    <input type="text" name="ftp_user" value="<?= h($ftpUser) ?>" placeholder="usuario@dominio.com"
                        style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#4f46e5'" onblur="this.style.borderColor='#cbd5e1'">
                </div>
                <div>
                    <label style="<?= $labelStyle ?>">Senha FTP <?= $hasFtpPass ? '<span style="color:#16a34a;font-weight:600;">(configurada)</span>' : '' ?></label>
                    <input type="password" name="ftp_pass" placeholder="<?= $hasFtpPass ? '••••••••  (deixe vazio para manter)' : 'Digite a senha FTP' ?>"
                        style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#4f46e5'" onblur="this.style.borderColor='#cbd5e1'">
                </div>
                <div style="grid-column:1/-1;">
                    <label style="<?= $labelStyle ?>">Caminho remoto</label>
                    <input type="text" name="ftp_path" value="<?= h($ftpPath) ?>" placeholder="/backups/monitorping"
                        style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#4f46e5'" onblur="this.style.borderColor='#cbd5e1'">
                    <div style="font-size:0.75rem;color:#94a3b8;margin-top:4px;">Pasta no servidor FTP onde os backups serão salvos.</div>
                </div>
            </div>

            <div style="display:flex;gap:10px;margin-top:20px;">
                <button type="submit" style="padding:11px 28px;background:#4f46e5;color:#fff;border:none;border-radius:10px;font-weight:700;font-size:0.92rem;cursor:pointer;">
                    💾 Salvar FTP
                </button>
                <!-- Botão testar FTP separado -->
                <button type="submit" form="form-test-ftp"
                    style="padding:11px 22px;background:#f8fafc;color:#374151;border:1px solid #e2e8f0;border-radius:10px;font-weight:700;font-size:0.92rem;cursor:pointer;">
                    🔌 Testar Conexão
                </button>
            </div>
        </form>
        <form id="form-test-ftp" method="post" style="display:none;">
            <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="test_ftp">
        </form>
    </div>

    <!-- Configuração Google Drive -->
    <div style="<?= $sectionStyle ?>">
        <div style="<?= $sectionHdrStyle ?>display:flex;justify-content:space-between;align-items:center;">
            <div>
                <h3 style="margin:0;font-size:1rem;font-weight:700;color:#0f172a;">
                    <img src="https://www.gstatic.com/images/branding/product/1x/drive_2020q4_48dp.png" style="width:20px;height:20px;vertical-align:middle;margin-right:6px;" alt="">
                    Envio Automático via Google Drive
                </h3>
                <p style="margin:2px 0 0;font-size:0.82rem;color:#64748b;">Usa conta de serviço Google para envio automático após cada backup</p>
            </div>
            <span style="background:<?= $gdriveEnabled?'#dcfce7':'#f1f5f9' ?>;color:<?= $gdriveEnabled?'#16a34a':'#64748b' ?>;padding:4px 14px;border-radius:20px;font-size:0.8rem;font-weight:700;">
                <?= $gdriveEnabled ? '✅ Ativo' : '⭕ Inativo' ?>
            </span>
        </div>
        <form method="post" style="<?= $sectionBdyStyle ?>">
            <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="save_gdrive">

            <label style="display:inline-flex;align-items:center;gap:10px;cursor:pointer;background:#f8fafc;padding:12px 18px;border-radius:10px;border:1px solid #e2e8f0;margin-bottom:20px;">
                <input type="checkbox" name="gdrive_enabled" <?= $gdriveEnabled?'checked':'' ?> style="width:18px;height:18px;accent-color:#4285f4;">
                <span style="font-weight:700;color:#0f172a;font-size:0.9rem;">Habilitar envio para Google Drive após cada backup</span>
            </label>

            <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;margin-bottom:16px;">
                <div>
                    <label style="<?= $labelStyle ?>">Nome da pasta no Drive</label>
                    <input type="text" name="gdrive_folder" value="<?= h($gdriveFolder) ?>" placeholder="MonitorPing-Backups"
                        style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#4285f4'" onblur="this.style.borderColor='#cbd5e1'">
                    <div style="font-size:0.75rem;color:#94a3b8;margin-top:4px;">Pasta criada automaticamente no Google Drive da conta de serviço.</div>
                </div>
            </div>

            <div>
                <label style="<?= $labelStyle ?>">
                    JSON da Conta de Serviço Google
                    <?= $hasGdriveSa ? '<span style="color:#16a34a;font-weight:600;">(configurado ✓)</span>' : '<span style="color:#ef4444;">* obrigatório</span>' ?>
                </label>
                <textarea name="gdrive_sa_json" rows="8"
                    placeholder='Cole aqui o conteúdo do arquivo JSON da conta de serviço Google...'
                    style="<?= $inputStyle ?>font-family:monospace;font-size:0.78rem;resize:vertical;"
                    onfocus="this.style.borderColor='#4285f4'" onblur="this.style.borderColor='#cbd5e1'"><?= $hasGdriveSa ? '' : '' ?></textarea>
                <div style="margin-top:8px;padding:12px 16px;background:#eff6ff;border:1px solid #93c5fd;border-radius:8px;font-size:0.8rem;color:#1e40af;">
                    <strong>Como obter o JSON:</strong><br>
                    1. Acesse <strong>console.cloud.google.com</strong> → IAM &amp; Admin → Contas de serviço<br>
                    2. Crie uma conta de serviço e gere uma chave JSON<br>
                    3. No Google Drive, compartilhe a pasta com o e-mail da conta de serviço (editor)<br>
                    4. Cole o conteúdo do arquivo .json aqui<br>
                    5. Deixe o campo vazio para manter o JSON já salvo.
                </div>
            </div>

            <button type="submit" style="margin-top:20px;padding:11px 28px;background:#4285f4;color:#fff;border:none;border-radius:10px;font-weight:700;font-size:0.92rem;cursor:pointer;">
                💾 Salvar Google Drive
            </button>
        </form>
    </div>

    <!-- Info sobre restauração -->
    <div style="background:#1e293b;border-radius:16px;padding:24px 28px;color:#94a3b8;font-size:0.85rem;">
        <div style="font-size:1rem;font-weight:800;color:#f1f5f9;margin-bottom:12px;">📖 Como Restaurar o Banco de Dados</div>
        <pre style="background:#0f172a;padding:14px 18px;border-radius:10px;overflow-x:auto;color:#86efac;font-size:0.8rem;margin:0;">pg_restore -h HOST -U USUARIO -d DATABASE --clean --no-owner database.dump</pre>
        <div style="margin-top:10px;color:#64748b;font-size:0.8rem;">
            O arquivo <code style="color:#93c5fd;">database.dump</code> está dentro do <code style="color:#93c5fd;">.tar.gz</code> junto com os arquivos da aplicação e o manifesto.
        </div>
    </div>

</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
