<?php
session_start();
require_once __DIR__ . '/config.php';
ensure_schema();

if (empty($_SESSION['user_id'])) { header("Location: ".BASE_URL."/login.php"); exit; }
$role = $_SESSION['role'] ?? 'user';

$id = (int)($_GET['id'] ?? 0);
$type = $_GET['type'] ?? '';

if(!in_array($type, ['ori','mod'], true)){ http_response_code(400); echo "Bad request"; exit; }

$pdo = db();
$st = $pdo->prepare("SELECT * FROM requests WHERE id=? LIMIT 1");
$st->execute([$id]);
$r = $st->fetch();
if(!$r){ http_response_code(404); echo "Not found"; exit; }

// Authorization
if($role !== 'admin'){
  if((int)$r['user_id'] !== (int)$_SESSION['user_id']){
    http_response_code(403); echo "Forbidden"; exit;
  }
}

$stored = '';
$downloadName = '';

if($type === 'ori'){
  $stored = $r['stored_filename'] ?? '';
  $downloadName = $r['original_filename'] ?? 'original.bin';
} else {
  // mod
  if($role !== 'admin'){
    if(($r['status'] ?? '') !== 'COMPLETED' || empty($r['result_stored_filename'])){
      http_response_code(403); echo "Not ready"; exit;
    }
  }
  $stored = $r['result_stored_filename'] ?? '';
  $downloadName = $r['result_original_filename'] ?? 'mod.bin';
}

$stored = basename($stored);
if($stored === ''){ http_response_code(404); echo "File missing"; exit; }

$path = UPLOAD_DIR . '/' . $stored;
if(!is_file($path)){ http_response_code(404); echo "File not found"; exit; }

$downloadName = preg_replace('/[^A-Za-z0-9._-]+/', '_', $downloadName);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$downloadName.'"');
header('Content-Length: ' . filesize($path));
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
readfile($path);
exit;
?>
