<?php
include('../includes/config.php');

/* ===============================
   INPUT (history page se)
================================ */
$id      = $_GET['id']   ?? '';
$type    = $_GET['type'] ?? '';
$service = $_GET['service'] ?? '';

if ($id=='' || $type=='' || $service=='') {
    die('Invalid Request');
}

/* ===============================
   DB SE DATA NIKALO
================================ */
$res = mysqli_query(
    $tng_conn,
    "SELECT * FROM all_pdf_records WHERE id='".mysqli_real_escape_string($tng_conn,$id)."'"
);

$row = mysqli_fetch_assoc($res);

if (!$row) {
    die('Record not found');
}

/*
  json_data = base64(JSON DATA)
*/
$dataBase64 = $row['json_data'];

/* ===============================
   PDF GENERATOR API
   (SAB SERVICES KE LIYE SAME)
================================ */
$pdfApiUrl =
  "http://72-61-225-209.nip.io/vehicle_pdf_generate/vehicle_rcpdf_verification2in1uniqapiserveikjik_server_1.php"
  . "?data=" . urlencode($dataBase64)
  . "&type=" . urlencode($type)
  . "&service=" . urlencode($service);

/* ===============================
   API CALL (cURL)
================================ */
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $pdfApiUrl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    curl_close($ch);
    die('PDF API Error');
}
curl_close($ch);

/* ===============================
   JSON RESPONSE HANDLE
================================ */
$json = json_decode($response, true);

if (
    !isset($json['sampleCode']) ||
    $json['sampleCode'] != '200' ||
    empty($json['pdf'])
) {
    die('PDF not generated');
}

/*
  API se PURE BASE64 aata hai:
  "pdf": "JVBERi0xLjQKJeLjz9MK..."
*/
$pdfBase64 = $json['pdf'];

/* ===============================
   BASE64 → PDF
================================ */
$pdfBinary = base64_decode($pdfBase64);

if ($pdfBinary === false) {
    die('Invalid PDF base64');
}

/* ===============================
   FORCE DOWNLOAD
================================ */
$filename =
    strtoupper($service)
    . "_"
    . preg_replace('/[^A-Za-z0-9]/','',$row['number'])
    . ".pdf";

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Length: '.strlen($pdfBinary));
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: public');

echo $pdfBinary;
exit;
