<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) { session_start(); }

// 1. Authenticated User Check Guard
if (!isset($_SESSION['user_id'])) {
    die("Access Denied: Unauthenticated transaction.");
}

require_once('../titancore/titanconfig.php');

// 2. Validate incoming request ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("Error: Missing target reference identifier.");
}

$record_id = intval($_GET['id']);
$uid = $_SESSION['user_id'];
$utype = $_SESSION['utype'] ?? $_SESSION['user_type'] ?? 'Retailer';

// 3. Database lookup based on role permissions
if ($utype === 'TitanAdmin') {
    $stmt = $conn->prepare("SELECT ration_no, pdf_data FROM ration_pdf_history WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $record_id);
} else {
    $stmt = $conn->prepare("SELECT ration_no, pdf_data FROM ration_pdf_history WHERE id = ? AND user_id = ? LIMIT 1");
    $stmt->bind_param("is", $record_id, $uid);
}

$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    die("Error: Document match not located or access restricted.");
}

$data = $res->fetch_assoc();
$stmt->close();

$ration_no = preg_replace('/[^A-Za-z0-9_]/', '', $data['ration_no']);
$pdf_url = trim($data['pdf_data']);

// 4. Standardize the absolute remote file URL string parameters
if (!empty($pdf_url) && strpos($pdf_url, 'http') === false) {
    $pdf_url = str_replace(['../dashboard/', 'uploads/ration_docs/'], '', $pdf_url);
    $pdf_url = "https://maxxapi.site/uploads/ration_docs/" . $pdf_url;
}

// 5. Streaming Core Connection Cluster using curl proxy to bypass OpenResty controls
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $pdf_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$file_buffer = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// If the proxy fails to download, give a clean error instead of a broken page
if ($http_code !== 200 || empty($file_buffer)) {
    die("Error: The source PDF file could not be pulled from the remote storage array. Code: " . $http_code);
}

// 6. Clear buffer pipelines completely to ensure clean binary delivery
if (ob_get_length()) { ob_end_clean(); }

// 7. Inject forced file-attachment download headers
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="Ration_' . $ration_no . '.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($file_buffer));

// Send file binary data stream down to the client machine space
echo $file_buffer;
exit();