<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid request method.");
}

if (empty($_POST['pdf'])) {
    die("No PDF data provided.");
}

// Get Base64 PDF
$pdfData = $_POST['pdf'];
$filename = $_POST['filename'];
$pdfData = str_replace('data:application/pdf;base64,', '', $pdfData);
$pdfData = str_replace(' ', '+', $pdfData); // fix spaces

$pdfBinary = base64_decode($pdfData);
if (!$pdfBinary) {
    die("Invalid PDF data.");
}

// Output PDF for direct download
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=\"$filename.pdf\"");
header("Content-Length: " . strlen($pdfBinary));

if (ob_get_level()) ob_end_clean();

echo $pdfBinary;
exit;
?>
