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

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

$stmt = mysqli_prepare($ahk_conn, "SELECT user_phone, status, application_no, mukhiya_pdf_1, mukhiya_pdf_2, result_pdf_path FROM samagra_merge_family_id_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 === 'mukhiya1') {
    if (!$isAdmin) {
        http_response_code(403);
        exit('Download not allowed.');
    }
    $relativePath = $request['mukhiya_pdf_1'];
} elseif ($fileType === 'mukhiya2') {
    if (!$isAdmin) {
        http_response_code(403);
        exit('Download not allowed.');
    }
    $relativePath = $request['mukhiya_pdf_2'];
} 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_merge_family_id');
$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 === 'mukhiya1' ? '-mukhiya-1' : ($fileType === 'mukhiya2' ? '-mukhiya-2' : '-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;
