<?php
session_start();
// Optional: check login
// if (!isset($_SESSION['user_id'])) exit('Unauthorized');

$transactionId = intval($_GET['transactionId'] ?? 0);
$folder        = $_GET['folder'] ?? '';
$fileName      = basename($_GET['file'] ?? '');

// Allowed folders
$allowedFolders = ['invoices', 'warranty'];
if (!in_array($folder, $allowedFolders)) {
    http_response_code(400);
    exit('Invalid folder');
}

// Build path
$uploadsDir = __DIR__ . '/uploads';
$transactionDir = "$uploadsDir/transactions/transaction_$transactionId/$folder";
$filePath = "$transactionDir/$fileName";

// File exists?
if (!file_exists($filePath)) {
    http_response_code(404);
    exit('File not found');
}

// Detect MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $filePath);
finfo_close($finfo);

// Headers
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($filePath));
header('Content-Disposition: inline; filename="' . $fileName . '"');
header('X-Content-Type-Options: nosniff');

// Output file
readfile($filePath);
exit;
