<?php
require_once("../includes/session.php");
require_once("../includes/config.php");

$id = intval($_GET['id'] ?? 0);

if (checkAdmin($udata['type'])) {
    $rec = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM puc_requests WHERE id=$id"));
} else {
    $rec = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM puc_requests WHERE id=$id AND username='{$udata['name']}'"));
}

if ($rec && $rec['status'] == 'Success' && !empty($rec['receiving_file'])) {
    if (strpos($rec['receiving_file'], 'base64,') !== false) {
        $parts = explode('base64,', $rec['receiving_file']);
        $fileData = base64_decode($parts[1]);
        
        $mimeType = 'application/pdf';
        if (strpos($parts[0], 'image/jpeg') !== false) $mimeType = 'image/jpeg';
        else if (strpos($parts[0], 'image/png') !== false) $mimeType = 'image/png';
        
        $ext = ($mimeType == 'application/pdf') ? 'pdf' : 'jpg';
        
        header('Content-Type: ' . $mimeType);
        header('Content-Disposition: attachment; filename="PUC_' . $rec['order_id'] . '.' . $ext . '"');
        header('Content-Length: ' . strlen($fileData));
        echo $fileData;
        exit;
    }
}

echo "File not found!";
?>