<?php
if (!isset($_POST['file']) || empty($_POST['file'])) {
    die("File missing!");
}

$data = base64_decode($_POST['file']);

/* Clean Safe Filename */
$raw = $_POST['user_applno'] ?? "LL_Exam";
$clean = preg_replace("/[^A-Za-z0-9_-]/", "", $raw);
$finalName = $clean . ".pdf";

/* Detect file type */
$finfo = finfo_open();
$type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);

/* ---------------------------------------------------
   IF ALREADY PDF → DIRECT DOWNLOAD
--------------------------------------------------- */
if ($type === "application/pdf") {
    header("Content-Type: application/pdf");
    header("Content-Disposition: attachment; filename=\"$finalName\"");
    echo $data;
    exit;
}

/* ---------------------------------------------------
   OTHERWISE IT IS IMAGE → CONVERT TO PDF WITHOUT DOMPDF
--------------------------------------------------- */

$tempImg = "temp_" . time() . ".jpg";
file_put_contents($tempImg, $data);

/* Create simple PDF using raw format */
$pdf = "%PDF-1.3
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800]
/Resources <<
    /XObject <</Im0 4 0 R>>
    /ProcSet [/PDF /ImageC]
>>
/Contents 5 0 R
>>
endobj
4 0 obj
<< /Type /XObject /Subtype /Image /Width 600 /Height 800
/ColorSpace /DeviceRGB /BitsPerComponent 8
/Filter /DCTDecode /Length " . filesize($tempImg) . " >>
stream
" . file_get_contents($tempImg) . "
endstream
endobj
5 0 obj
<< /Length 50 >>
stream
q
600 0 0 800 0 0 cm
/Im0 Do
Q
endstream
endobj
xref
0 6
0000000000 65535 f 
0000000010 00000 n 
0000000060 00000 n 
0000000115 00000 n 
0000000270 00000 n 
0000000500 00000 n 
trailer
<< /Size 6 /Root 1 0 R >>
startxref
650
%%EOF";

unlink($tempImg);

/* Output PDF */
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=\"$finalName\"");
echo $pdf;
exit;
?>
