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

$token = $_GET['token'] ?? '';
if(!$token) die('Invalid Request');

$decoded = base64_decode($token);
list($id,$key) = explode('|',$decoded);

if($key !== $secret) die('Access Denied');

$q = mysqli_query(
  $tng_conn,
  "SELECT pdf,service_name,name,number 
   FROM all_pdf_records 
   WHERE id='$id' LIMIT 1"
);
$row = mysqli_fetch_assoc($q);
if(!$row) die('PDF Not Found');

$pdf = trim($row['pdf']);

/* URL PDF */
if(filter_var($pdf, FILTER_VALIDATE_URL)){
  header("Location: $pdf");
  exit;
}

/* BASE64 PDF */
if(strpos($pdf,'base64,') !== false){
  $pdf = explode('base64,', $pdf, 2)[1];
}

$binary = base64_decode($pdf);
if(!$binary || strlen($binary) < 5000){
  die('Invalid PDF');
}

function clean($s){
  return preg_replace('/[^a-zA-Z0-9_-]/','_',$s);
}

$filename =
  clean($row['service_name']).'_'.
  clean($row['name']).'_'.
  clean($row['number']).'.pdf';

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

echo $binary;
exit;
