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

$id = (int) ($_GET['id'] ?? 0);
$fileType = $_GET['file'] ?? 'result';

$stmt = mysqli_prepare($ahk_conn, "SELECT user_phone, status, application_no, member_aadhar_pdf, result_pdf_path FROM samagra_recover_member_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) {
    http_response_code(404);
    exit('File not found.');
}

if ($fileType === 'userdoc') {
    if (!$isAdmin) {
        http_response_code(403);
        exit('Download not allowed.');
    }
    $relativePath = $request['member_aadhar_pdf'];
} else {
    if ($request['status'] !== 'approved' || (!$isAdmin && $request['user_phone'] !== $udata['phone'])) {
        http_response_code(403);
        exit('Download not allowed.');
    }
    $relativePath = $request['result_pdf_path'];
}

if (!$relativePath) {
    http_response_code(404);
    exit('PDF not found.');
}

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

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