<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../auth.php';
requirePerfil(['ADMIN']);

function backupDatabase($pdo) {
    $backupDir = __DIR__ . '/../backups/';
    if (!is_dir($backupDir)) mkdir($backupDir, 0755, true);
    
    $filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
    $filepath = $backupDir . $filename;
    
    // Buscar todas as tabelas
    $stmt = $pdo->query("SHOW TABLES");
    $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $output = "-- Backup MKT Telecom\n";
    $output .= "-- Data: " . date('Y-m-d H:i:s') . "\n";
    $output .= "-- Banco: " . DB_NAME . "\n\n";
    $output .= "SET FOREIGN_KEY_CHECKS=0;\n\n";
    
    foreach ($tables as $table) {
        // Estrutura da tabela
        $stmt = $pdo->query("SHOW CREATE TABLE $table");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $output .= "\n-- Estrutura da tabela {$table}\n";
        $output .= "DROP TABLE IF EXISTS `{$table}`;\n";
        $output .= $row['Create Table'] . ";\n\n";
        
        // Dados
        $stmt = $pdo->query("SELECT * FROM $table");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (count($rows) > 0) {
            $output .= "-- Dados da tabela {$table}\n";
            foreach ($rows as $row) {
                $values = array_map(function($val) use ($pdo) {
                    if ($val === null) return 'NULL';
                    return $pdo->quote($val);
                }, array_values($row));
                
                $columns = array_map(function($col) {
                    return "`{$col}`";
                }, array_keys($row));
                
                $output .= "INSERT INTO `{$table}` (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $values) . ");\n";
            }
            $output .= "\n";
        }
    }
    
    $output .= "\nSET FOREIGN_KEY_CHECKS=1;\n";
    
    // Escrever arquivo
    file_put_contents($filepath, $output);
    
    // Limpar backups antigos (manter últimos 30 dias)
    $files = glob($backupDir . 'backup_*.sql');
    usort($files, function($a, $b) {
        return filemtime($a) - filemtime($b);
    });
    
    while (count($files) > 30) {
        unlink(array_shift($files));
    }
    
    // Registrar no log
    registrarLog('BACKUP_REALIZADO', 'sistema', null, ['arquivo' => $filename]);
    
    return ['success' => true, 'file' => $filename, 'size' => filesize($filepath)];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = backupDatabase($pdo);
    echo json_encode($result);
}
