<?php
// backend/download_zip_file.php
// Streams the zip file to the browser: /backend/download_zip_file.php?file=XXXXX.zip

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

error_reporting(E_ALL);
ini_set('display_errors', 0);

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        http_response_code(405);
        echo "Method not allowed";
        exit;
    }

    $file = isset($_GET['file']) ? basename($_GET['file']) : '';
    if ($file === '' || !preg_match('/\.zip$/i', $file)) {
        http_response_code(400);
        echo "Invalid file";
        exit;
    }

    $zipPath = $_SERVER['DOCUMENT_ROOT'] . '/backend/downloads/apply_listelegislative_zips/' . $file;

    if (!file_exists($zipPath) || !is_file($zipPath)) {
        http_response_code(404);
        echo "File not found";
        exit;
    }

    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $file . '"');
    header('Content-Length: ' . filesize($zipPath));
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Pragma: no-cache');

    readfile($zipPath);
    exit;

} catch (Exception $e) {
    http_response_code(500);
    echo "Server error";
    exit;
}
?>