<?php
// icx/backup.php
require_once __DIR__ . '/../common/config.php';
require_once __DIR__ . '/common/auth-check.php';

// Check permissions
if (!isset($_SESSION['admin_id'])) {
    die("Unauthorized");
}

// Generate simple SQL backup (Structure & Data)
$tables = [];
$result =$pdo->query("SHOW TABLES");
while ($row =$result->fetch(PDO::FETCH_NUM)) {
    $tables[] =$row[0];
}

$sqlDump = "-- Database Backup for ICX TOPUP\n";
$sqlDump .= "-- Generated: " . date('Y-m-d H:i:s') . "\n\n";

foreach ($tables as$table) {
    $result =$pdo->query("SELECT * FROM `$table`");
    $numFields =$result->columnCount();
    
    $row2 =$pdo->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_NUM);
    $sqlDump .= "\n\n" . $row2[1] . ";\n\n";
    
    for ($i = 0; $i < $numFields; $i++) {
        while ($row = $result->fetch(PDO::FETCH_NUM)) {$sqlDump .= "INSERT INTO `$table` VALUES(";
            for ($j = 0; $j < $numFields; $j++) {
                $row[$j] = addslashes($row[$j]);
                $row[$j] = str_replace("\n", "\\n", $row[$j]);
                if (isset($row[$j])) {$sqlDump .= '"' . $row[$j] . '"';
                } else {
                    $sqlDump .= '""';
                }
                if ($j < ($numFields - 1)) {$sqlDump .= ',';
                }
            }
            $sqlDump .= ");\n";
        }
    }
    $sqlDump .= "\n\n\n";
}

// Log backup action
$pdo->prepare("INSERT INTO activity_logs (admin_id, action) VALUES (?, 'Downloaded Database Backup')")->execute([$_SESSION['admin_id']]);

// Serve the file
$filename = 'icx_backup_' . date('Y-m-d_H-i') . '.sql';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"".$filename."\""); 
echo $sqlDump;
exit;
?>

