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

if (empty($_SESSION['user_id'])) { header("Location: index.html?e=1"); exit; }

$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

function clean_rel(string $p): string {
  $p = trim($p);
  $p = str_replace(["\0", ".."], '', $p);
  $p = str_replace('\\', '/', $p);
  return ltrim($p, '/');
}

$id   = (int)($_GET['id'] ?? 0);
$mode = (string)($_GET['mode'] ?? 'download'); // view | download
if ($id <= 0) { http_response_code(400); exit('missing id'); }

$st = $pdo->prepare("SELECT file_name, file_path, file_type FROM case_files WHERE id=? LIMIT 1");
$st->execute([$id]);
$row = $st->fetch();
if (!$row) { http_response_code(404); exit('file not found'); }

$rel = clean_rel((string)($row['file_path'] ?? ''));
if ($rel === '') { http_response_code(404); exit('empty path'); }

/*
  file_path غالباً يكون:
  uploads/cases/xxx.pdf
  أو HLG-Justice-Hub/uploads/cases/xxx.pdf
*/
$try1 = realpath(__DIR__ . '/' . $rel);
$try2 = realpath(__DIR__ . '/uploads/' . $rel); // لو مخزن بدون uploads
$try3 = realpath(__DIR__ . '/' . preg_replace('~^HLG-Justice-Hub/~', '', $rel)); // لو مخزن مع اسم المجلد

$abs = ($try1 && is_file($try1)) ? $try1 : (($try2 && is_file($try2)) ? $try2 : (($try3 && is_file($try3)) ? $try3 : false));

if ($abs === false) {
  http_response_code(404);
  exit('file missing on disk');
}

$mime = (string)($row['file_type'] ?? '');
if ($mime === '' || stripos($mime, '/') === false) $mime = 'application/octet-stream';

$filename = (string)($row['file_name'] ?? basename($abs));
$disp = ($mode === 'view') ? 'inline' : 'attachment';

header('Content-Type: '.$mime);
header('X-Content-Type-Options: nosniff');
header('Content-Length: ' . filesize($abs));
header("Content-Disposition: {$disp}; filename*=UTF-8''" . rawurlencode($filename));

readfile($abs);
exit;