<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';

$token = trim($_GET['token'] ?? '');
if (!$token || !preg_match('/^[a-f0-9]{32}$/', $token)) {
    http_response_code(400);
    exit('Invalid token');
}

$job = Db::getJobByToken($token);
if (!$job) {
    http_response_code(404);
    exit('Job not found');
}
if ($job['status'] !== 'done') {
    http_response_code(400);
    exit('Job not finished yet');
}

$filename = $job['filename'];
$filePath = EXPORTS_DIR . '/' . $filename;

if (!file_exists($filePath)) {
    http_response_code(404);
    exit('Export file not found');
}

// Detect format from stored filename
$ext     = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$outName = 'product_images_results_' . date('Ymd_His', strtotime($job['completed_at'] ?? 'now')) . '.' . $ext;

$mimeTypes = [
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'csv'  => 'text/csv; charset=utf-8',
];
$mime = $mimeTypes[$ext] ?? 'application/octet-stream';

header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . $outName . '"');
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: no-store, must-revalidate');
header('Pragma: no-cache');

readfile($filePath);
exit;
