<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use Sethrey\SysvoteWebsite\EnvLoader;
use Sethrey\SysvoteWebsite\DownloadToken;

if (class_exists(EnvLoader::class)) {
    EnvLoader::load(__DIR__ . '/../.env');
}

$token = $_GET['token'] ?? '';
$downloadSecret = getenv('DOWNLOAD_SECRET') ?: '';
$productPath = getenv('PRODUCT_FILE_PATH') ?: '';

$sessionId = ($token !== '' && $downloadSecret !== '')
    ? DownloadToken::verify($token, $downloadSecret)
    : null;

if ($sessionId === null) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=utf-8');
    echo "This download link is invalid or has expired.\nPlease contact support with your payment receipt to get a fresh link.";
    exit;
}

if ($productPath === '' || !is_file($productPath)) {
    http_response_code(500);
    error_log('[download.php] PRODUCT_FILE_PATH is missing or not readable: ' . $productPath);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'The product file is temporarily unavailable. Please contact support — your payment is safe and already confirmed.';
    exit;
}

$fileName = basename($productPath);

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . (string) filesize($productPath));
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store');

readfile($productPath);
exit;
