<?php
require_once __DIR__ . '/includes/functions.php';
require_login();

$doc_id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("
    SELECT cd.*, c.user_id
    FROM claim_documents cd
    JOIN claims c ON c.id = cd.claim_id
    WHERE cd.id = ?
");
$stmt->execute([$doc_id]);
$doc = $stmt->fetch();

if (!$doc) {
    http_response_code(404);
    die('مدرک یافت نشد.');
}

$user = current_user();
if ($user['role'] !== 'admin' && $doc['user_id'] != $user['id']) {
    http_response_code(403);
    die('شما مجاز به مشاهده این مدرک نیستید.');
}

$full_path = UPLOAD_DIR . '/' . $doc['file_path'];
if (!file_exists($full_path)) {
    http_response_code(404);
    die('فایل روی سرور یافت نشد.');
}

$ext = strtolower(pathinfo($full_path, PATHINFO_EXTENSION));
$mime_map = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'pdf' => 'application/pdf'];
$mime = $mime_map[$ext] ?? 'application/octet-stream';

header('Content-Type: ' . $mime);
header('Content-Disposition: inline; filename="' . rawurlencode($doc['original_name']) . '"');
header('Content-Length: ' . filesize($full_path));
readfile($full_path);
exit;
