<?php
ob_start();

$zipname = $_GET['fl'] ?? '';
$zipname = basename($zipname); // Prevent directory traversal

$dumpDir = __DIR__ . '/dump/';
$zipDir  = __DIR__ . '/dump/zip/';
$dumpFile = $dumpDir . $zipname;
$gzFile = $zipDir . $zipname . '.gz';

function compress($sourceFile, $destinationFile) {
    if (!file_exists($sourceFile)) {
        die("No SQL file found.");
    }

    if (file_exists($destinationFile)) {
        unlink($destinationFile); // Remove existing zip if any
    }

    $fp = fopen($sourceFile, "rb");
    if (!$fp) {
        die("Failed to open source file.");
    }

    $zp = gzopen($destinationFile, "wb9");
    if (!$zp) {
        fclose($fp);
        die("Failed to create zip file.");
    }

    while (!feof($fp)) {
        $data = fread($fp, 8192);
        gzwrite($zp, $data);
    }

    fclose($fp);
    gzclose($zp);
    return true;
}

// Ensure paths exist
if (!file_exists($dumpFile)) {
    die("Requested file not found.");
}

if (!is_dir($zipDir)) {
    mkdir($zipDir, 0755, true); // Create zip directory if missing
}

// Compress if not already
if (!file_exists($gzFile)) {
    compress($dumpFile, $gzFile);
}

// Set headers and serve file
header('Content-Type: application/gzip');
header('Content-Disposition: attachment; filename="' . basename($gzFile) . '"');
header('Content-Length: ' . filesize($gzFile));
readfile($gzFile);
exit;
