<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("HTTP/1.1 401 Unauthorized");
    exit("Unauthorized");
}

$file = $_GET['file'] ?? '';

// Mapping of downloadable files for the Cloud Print Bridge
$allowedFiles = [
    'cloud-service' => [
        'path' => __DIR__ . '/../print_service_cloud.ps1',
        'name' => 'print_service_cloud.ps1'
    ],
    'cloud-batch' => [
        'path' => __DIR__ . '/../run_cloud_print_service.bat',
        'name' => 'run_cloud_print_service.bat'
    ],
    'cloud-vbs' => [
        'path' => __DIR__ . '/../launch_cloud_hidden.vbs',
        'name' => 'launch_cloud_hidden.vbs'
    ],
    'cloud-config' => [
        'path' => __DIR__ . '/../cloud_printer_config.txt',
        'name' => 'cloud_printer_config.txt'
    ],
    'cloud-printer' => [
        'path' => __DIR__ . '/../printer_config.txt',
        'name' => 'printer_config.txt'
    ]
];

if ($file === 'cloud-bundle') {
    $zipName = 'JustSale_Printer_Kit.zip';
    $zipFile = tempnam(sys_get_temp_dir(), 'zip');
    $zip = new ZipArchive();
    
    if ($zip->open($zipFile, ZipArchive::CREATE)) {
        foreach ($allowedFiles as $key => $f) {
            if (file_exists($f['path'])) {
                $zip->addFile($f['path'], $f['name']);
            }
        }
        $zip->close();
        
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipName . '"');
        header('Content-Length: ' . filesize($zipFile));
        readfile($zipFile);
        unlink($zipFile);
        exit;
    }
}

if (isset($allowedFiles[$file])) {
    $filePath = $allowedFiles[$file]['path'];
    $fileName = $allowedFiles[$file]['name'];
    
    if (file_exists($filePath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.$fileName.'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    } else {
        header("HTTP/1.1 404 Not Found");
        exit("File Not Found");
    }
} else {
    header("HTTP/1.1 400 Bad Request");
    exit("Invalid File Requested");
}
?>
