<?php
session_start();
$file = isset($_GET['file']) ? $_GET['file'] : (isset($_SESSION['file']) ? $_SESSION['file'] : '');

// Check if a file is set
if (empty($file) || !file_exists($file)) {
    header('Location: index.php');
    exit;
}

// Serve the file as a download
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

readfile($file);

// Clean up
unlink($file);
unset($_SESSION['file']);
unset($_SESSION['filename']);
unset($_SESSION['return']);

exit;
