<?php
/**
 * Sistema de Backup - SuperAdmin
 * MontaLoja SaaS
 */
ob_start(); // Iniciar buffer de saída

require_once __DIR__ . '/../../../includes/config.php';

if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();

// Configurações
$backupDir = __DIR__ . '/../../../backups/';
$appDir = __DIR__ . '/../../../';
$dbName = 'socialar_socialar_commerce';
$dbUser = 'socialar';
$dbPass = 'y557t55n7rt6';

// Criar diretório se não existir
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

// Processar ações POST com padrão PRG (Post-Redirect-Get)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'create_backup') {
        try {
            $timestamp = date('Y-m-d_H-i-s');
            $backupName = 'backup_' . $timestamp;
            $backupPath = $backupDir . $backupName;
            
            // Criar diretório do backup
            mkdir($backupPath, 0755, true);
            mkdir($backupPath . '/files', 0755, true);
            
            // 1. Backup do banco de dados
            $sqlFile = $backupPath . '/database.sql';
            $mysqldumpCmd = "mysqldump -u{$dbUser} -p'{$dbPass}' {$dbName} > {$sqlFile} 2>&1";
            exec($mysqldumpCmd, $output, $returnCode);
            
            if ($returnCode !== 0) {
                throw new Exception('Erro ao fazer backup do banco de dados');
            }
            
            // 2. Backup dos arquivos importantes (excluindo backups e node_modules)
            $excludes = [
                '--exclude=backups',
                '--exclude=node_modules',
                '--exclude=vendor',
                '--exclude=.git',
                '--exclude=*.log',
                '--exclude=*.tmp'
            ];
            $excludeStr = implode(' ', $excludes);
            
            $tarFile = $backupPath . '/files.tar.gz';
            $tarCmd = "cd {$appDir} && tar czf {$tarFile} {$excludeStr} . 2>&1";
            exec($tarCmd, $output2, $returnCode2);
            
            if ($returnCode2 !== 0) {
                throw new Exception('Erro ao fazer backup dos arquivos');
            }
            
            // 3. Salvar metadados
            $metadata = [
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => $superAdmin['email'] ?? 'superadmin',
                'db_size' => filesize($sqlFile),
                'files_size' => filesize($tarFile),
                'php_version' => PHP_VERSION,
                'description' => $_POST['description'] ?? ''
            ];
            file_put_contents($backupPath . '/metadata.json', json_encode($metadata, JSON_PRETTY_PRINT));
            
            $_SESSION['flash_message'] = [
                'type' => 'success',
                'text' => 'Backup criado com sucesso: ' . $backupName
            ];
            
        } catch (Exception $e) {
            $_SESSION['flash_message'] = [
                'type' => 'error',
                'text' => 'Erro ao criar backup: ' . $e->getMessage()
            ];
        }
        
        ob_end_clean();
        header('Location: /pages/superadmin/system/backup.php');
        exit;
    }
    
    elseif ($action === 'restore_backup') {
        $backupName = $_POST['backup_name'] ?? '';
        $backupPath = $backupDir . $backupName;
        
        if (!is_dir($backupPath)) {
            $_SESSION['flash_message'] = [
                'type' => 'error',
                'text' => 'Backup não encontrado!'
            ];
        } else {
            try {
                // Criar backup de segurança antes de restaurar
                $safetyTimestamp = date('Y-m-d_H-i-s');
                $safetyBackup = $backupDir . 'pre_restore_' . $safetyTimestamp;
                mkdir($safetyBackup, 0755, true);
                
                // Backup rápido do banco antes de restaurar
                $safetySql = $safetyBackup . '/database.sql';
                exec("mysqldump -u{$dbUser} -p'{$dbPass}' {$dbName} > {$safetySql} 2>&1");
                
                file_put_contents($safetyBackup . '/metadata.json', json_encode([
                    'created_at' => date('Y-m-d H:i:s'),
                    'type' => 'pre_restore_safety',
                    'restored_from' => $backupName
                ], JSON_PRETTY_PRINT));
                
                // 1. Restaurar banco de dados
                $sqlFile = $backupPath . '/database.sql';
                if (file_exists($sqlFile)) {
                    $restoreCmd = "mysql -u{$dbUser} -p'{$dbPass}' {$dbName} < {$sqlFile} 2>&1";
                    exec($restoreCmd, $output, $returnCode);
                    
                    if ($returnCode !== 0) {
                        throw new Exception('Erro ao restaurar banco de dados');
                    }
                }
                
                // 2. Restaurar arquivos
                $tarFile = $backupPath . '/files.tar.gz';
                if (file_exists($tarFile)) {
                    $extractCmd = "cd {$appDir} && tar xzf {$tarFile} --overwrite 2>&1";
                    exec($extractCmd, $output2, $returnCode2);
                    
                    if ($returnCode2 !== 0) {
                        throw new Exception('Erro ao restaurar arquivos');
                    }
                }
                
                $_SESSION['flash_message'] = [
                    'type' => 'success',
                    'text' => 'Backup restaurado com sucesso! Um backup de segurança foi criado: pre_restore_' . $safetyTimestamp
                ];
                
            } catch (Exception $e) {
                $_SESSION['flash_message'] = [
                    'type' => 'error',
                    'text' => 'Erro ao restaurar: ' . $e->getMessage()
                ];
            }
        }
        
        ob_end_clean();
        header('Location: /pages/superadmin/system/backup.php');
        exit;
    }
    
    elseif ($action === 'delete_backup') {
        $backupName = $_POST['backup_name'] ?? '';
        $backupPath = $backupDir . $backupName;
        
        if (is_dir($backupPath)) {
            // Remover recursivamente
            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($backupPath, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::CHILD_FIRST
            );
            foreach ($files as $file) {
                if ($file->isDir()) {
                    rmdir($file->getRealPath());
                } else {
                    unlink($file->getRealPath());
                }
            }
            rmdir($backupPath);
            
            $_SESSION['flash_message'] = [
                'type' => 'success',
                'text' => 'Backup excluído com sucesso!'
            ];
        } else {
            $_SESSION['flash_message'] = [
                'type' => 'error',
                'text' => 'Backup não encontrado!'
            ];
        }
        
        ob_end_clean();
        header('Location: /pages/superadmin/system/backup.php');
        exit;
    }
}

// Capturar mensagem flash da sessão
$flashMessage = $_SESSION['flash_message'] ?? null;
unset($_SESSION['flash_message']);

// Listar backups existentes
$backups = [];
if (is_dir($backupDir)) {
    $dirs = scandir($backupDir);
    foreach ($dirs as $dir) {
        if ($dir === '.' || $dir === '..') continue;
        $path = $backupDir . $dir;
        if (is_dir($path)) {
            $metaFile = $path . '/metadata.json';
            $metadata = file_exists($metaFile) ? json_decode(file_get_contents($metaFile), true) : [];
            
            $backups[] = [
                'name' => $dir,
                'path' => $path,
                'created_at' => $metadata['created_at'] ?? date('Y-m-d H:i:s', filemtime($path)),
                'created_by' => $metadata['created_by'] ?? 'desconhecido',
                'db_size' => $metadata['db_size'] ?? 0,
                'files_size' => $metadata['files_size'] ?? 0,
                'description' => $metadata['description'] ?? '',
                'type' => $metadata['type'] ?? 'manual'
            ];
        }
    }
}

// Ordenar por data (mais recente primeiro)
usort($backups, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Função auxiliar para formatar bytes
function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB'];
    $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];
}

$pageTitle = 'Backup do Sistema';
$currentPage = 'backup';

ob_end_flush(); // Liberar buffer antes do HTML
include __DIR__ . '/../includes/header.php';
?>
    <div class="app-container">
        <?php include __DIR__ . '/../includes/sidebar.php'; ?>

        <main class="main-content">
            <?php include __DIR__ . '/../includes/topbar.php'; ?>

            <div class="content-area">
                <div class="page-header">
                    <h1><iconify-icon icon="solar:cloud-download-bold"></iconify-icon> Backup do Sistema</h1>
                    <p>Gerencie backups do sistema para segurança e recuperação</p>
                </div>

                <?php if ($flashMessage): ?>
                <div class="alert alert-<?= $flashMessage['type'] ?>">
                    <iconify-icon icon="<?= $flashMessage['type'] === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold' ?>"></iconify-icon>
                    <?= htmlspecialchars($flashMessage['text']) ?>
                </div>
                <?php endif; ?>

                <!-- Ações Rápidas -->
                <div class="backup-actions">
                    <div class="action-card create-backup">
                        <iconify-icon icon="solar:cloud-upload-bold" class="action-icon"></iconify-icon>
                        <h3>Criar Novo Backup</h3>
                        <p>Salva uma cópia completa do banco de dados e arquivos do sistema</p>
                        <form method="POST" onsubmit="return confirm('Criar um novo backup agora?');">
                            <input type="hidden" name="action" value="create_backup">
                            <div class="form-group" style="margin-bottom: 1rem;">
                                <input type="text" name="description" class="form-input" placeholder="Descrição do backup (opcional)" style="width: 100%;">
                            </div>
                            <button type="submit" class="btn btn-primary btn-lg">
                                <iconify-icon icon="solar:cloud-upload-bold"></iconify-icon>
                                Fazer Backup Agora
                            </button>
                        </form>
                    </div>

                    <div class="action-card restore-info">
                        <iconify-icon icon="solar:shield-check-bold" class="action-icon success"></iconify-icon>
                        <h3>Restauração Segura</h3>
                        <p>Ao restaurar, um backup de segurança é criado automaticamente antes de aplicar as alterações</p>
                        <div class="info-stats">
                            <div class="stat">
                                <span class="stat-value"><?= count($backups) ?></span>
                                <span class="stat-label">Backups disponíveis</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Lista de Backups -->
                <div class="panel">
                    <div class="section-header">
                        <h3 class="section-title">
                            <iconify-icon icon="solar:folder-bold"></iconify-icon>
                            Backups Disponíveis
                        </h3>
                    </div>

                    <?php if (empty($backups)): ?>
                    <div class="empty-state">
                        <iconify-icon icon="solar:cloud-bold-duotone"></iconify-icon>
                        <h3>Nenhum backup encontrado</h3>
                        <p>Crie seu primeiro backup para proteger seus dados.</p>
                    </div>
                    <?php else: ?>
                    <div class="backup-list">
                        <?php foreach ($backups as $backup): ?>
                        <div class="backup-item <?= strpos($backup['name'], 'pre_restore') !== false ? 'safety-backup' : '' ?>">
                            <div class="backup-icon">
                                <?php if (strpos($backup['name'], 'pre_restore') !== false): ?>
                                <iconify-icon icon="solar:shield-bold" style="color: var(--warning);"></iconify-icon>
                                <?php else: ?>
                                <iconify-icon icon="solar:cloud-bold" style="color: var(--primary);"></iconify-icon>
                                <?php endif; ?>
                            </div>
                            <div class="backup-info">
                                <div class="backup-name"><?= htmlspecialchars($backup['name']) ?></div>
                                <div class="backup-meta">
                                    <span><iconify-icon icon="solar:calendar-bold"></iconify-icon> <?= date('d/m/Y H:i', strtotime($backup['created_at'])) ?></span>
                                    <span><iconify-icon icon="solar:user-bold"></iconify-icon> <?= htmlspecialchars($backup['created_by']) ?></span>
                                    <?php if ($backup['db_size']): ?>
                                    <span><iconify-icon icon="solar:database-bold"></iconify-icon> <?= formatBytes($backup['db_size']) ?></span>
                                    <?php endif; ?>
                                    <?php if ($backup['files_size']): ?>
                                    <span><iconify-icon icon="solar:folder-bold"></iconify-icon> <?= formatBytes($backup['files_size']) ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php if ($backup['description']): ?>
                                <div class="backup-description"><?= htmlspecialchars($backup['description']) ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="backup-actions-btns">
                                <form method="POST" style="display: inline;" onsubmit="return confirm('ATENÇÃO: Restaurar este backup irá sobrescrever todos os dados atuais. Um backup de segurança será criado antes. Deseja continuar?');">
                                    <input type="hidden" name="action" value="restore_backup">
                                    <input type="hidden" name="backup_name" value="<?= htmlspecialchars($backup['name']) ?>">
                                    <button type="submit" class="btn btn-warning btn-sm">
                                        <iconify-icon icon="solar:history-bold"></iconify-icon>
                                        Restaurar
                                    </button>
                                </form>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja excluir este backup? Esta ação não pode ser desfeita.');">
                                    <input type="hidden" name="action" value="delete_backup">
                                    <input type="hidden" name="backup_name" value="<?= htmlspecialchars($backup['name']) ?>">
                                    <button type="submit" class="btn btn-outline btn-sm" style="color: var(--danger);">
                                        <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                                    </button>
                                </form>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

<style>
.backup-actions {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.action-card {
    background: var(--card-bg);
    border-radius: var(--radius-lg);
    padding: 2rem;
    text-align: center;
    border: 1px solid var(--border);
}

.action-card.create-backup {
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.1), rgba(99, 102, 241, 0.05));
    border-color: rgba(99, 102, 241, 0.3);
}

.action-icon {
    font-size: 3rem;
    color: var(--primary);
    margin-bottom: 1rem;
}

.action-icon.success {
    color: var(--success);
}

.action-card h3 {
    font-size: 1.25rem;
    margin-bottom: 0.5rem;
}

.action-card p {
    color: var(--text-muted);
    margin-bottom: 1.5rem;
    font-size: 0.9rem;
}

.info-stats {
    display: flex;
    justify-content: center;
    gap: 2rem;
}

.info-stats .stat {
    text-align: center;
}

.info-stats .stat-value {
    font-size: 2rem;
    font-weight: 700;
    color: var(--primary);
    display: block;
}

.info-stats .stat-label {
    font-size: 0.8rem;
    color: var(--text-muted);
}

.backup-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.backup-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem 1.5rem;
    background: var(--bg);
    border-radius: var(--radius);
    border: 1px solid var(--border);
    transition: all 0.2s;
}

.backup-item:hover {
    border-color: var(--primary);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.backup-item.safety-backup {
    background: rgba(245, 158, 11, 0.05);
    border-color: rgba(245, 158, 11, 0.3);
}

.backup-icon {
    font-size: 2rem;
}

.backup-info {
    flex: 1;
}

.backup-name {
    font-weight: 600;
    font-size: 1rem;
    margin-bottom: 0.25rem;
}

.backup-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    font-size: 0.8rem;
    color: var(--text-muted);
}

.backup-meta span {
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.backup-description {
    margin-top: 0.5rem;
    font-size: 0.85rem;
    color: var(--text-muted);
    font-style: italic;
}

.backup-actions-btns {
    display: flex;
    gap: 0.5rem;
}

.btn-warning {
    background: var(--warning);
    color: #000;
}

.btn-warning:hover {
    background: #d97706;
}

.empty-state {
    text-align: center;
    padding: 3rem;
    color: var(--text-muted);
}

.empty-state iconify-icon {
    font-size: 4rem;
    opacity: 0.5;
    margin-bottom: 1rem;
}

.empty-state h3 {
    margin-bottom: 0.5rem;
    color: var(--text);
}

.alert {
    padding: 1rem 1.5rem;
    border-radius: var(--radius);
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    font-weight: 500;
}

.alert iconify-icon {
    font-size: 1.5rem;
}

.alert-success {
    background: rgba(34, 197, 94, 0.1);
    border: 1px solid rgba(34, 197, 94, 0.3);
    color: var(--success);
}

.alert-error {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: var(--danger);
}

@media (max-width: 768px) {
    .backup-item {
        flex-direction: column;
        text-align: center;
    }
    
    .backup-meta {
        justify-content: center;
    }
    
    .backup-actions-btns {
        width: 100%;
        justify-content: center;
    }
}
</style>

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