<?php
include 'db.php'; // must define $host, $username, $password, $dbname

// Handle file download requests from backup dashboard
if (isset($_GET['file'])) {
    $requestedFile = $_GET['file'];
    $backupDir = 'D:/wamp/backups/itrpos/';
    $filePath = $backupDir . basename($requestedFile); // Sanitize filename
    
    if (file_exists($filePath)) {
        // Set headers for download
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"" . basename($requestedFile) . "\"");
        header("Content-Length: " . filesize($filePath));
        header("Pragma: no-cache");
        header("Expires: 0");
        
        // Output file
        readfile($filePath);
        exit;
    } else {
        http_response_code(404);
        die("File not found: " . htmlspecialchars($requestedFile));
    }
}

// Original backup functionality for direct database export
$filename = "backup_" . date('Y-m-d_H-i-s') . ".sql";

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Pragma: no-cache");
header("Expires: 0");

$command = "mysqldump --user=$username --password=$password --host=$host $dbname 2>&1";

passthru($command, $return_var);

if ($return_var !== 0) {
    echo "Error: Backup failed. Please check server permissions or credentials.";
}
exit;
