<?php
include('../includes/session.php');
include('../includes/config.php');
include('samagra_pravasan_common.php');
checkSession();
ensureSamagraPravasanTable($ahk_conn);

$id = (int) ($_GET['id'] ?? 0);
$stmt = mysqli_prepare($ahk_conn, "SELECT user_phone, status, pdf_path, application_no FROM samagra_pravasan_requests WHERE id=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
$request = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
mysqli_stmt_close($stmt);

$isAdmin = checkAdmin($udata['type']);
if (!$request || $request['status'] !== 'approved' || (!$isAdmin && $request['user_phone'] !== $udata['phone'])) {
    http_response_code(403);
    exit('Download not allowed.');
}

$base = realpath(__DIR__ . '/uploads/samagra_pravasan');
$file = realpath(__DIR__ . '/' . $request['pdf_path']);
if (!$base || !$file || strpos($file, $base . DIRECTORY_SEPARATOR) !== 0 || !is_file($file)) {
    http_response_code(404);
    exit('PDF not found.');
}

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . preg_replace('/[^A-Za-z0-9_-]/', '', $request['application_no']) . '.pdf"');
header('Content-Length: ' . filesize($file));
header('X-Content-Type-Options: nosniff');
readfile($file);
exit;
