<?php

include_once('../includes/db.php');

$order_id = $_GET['order_id'] ?? null;
if (!$order_id) {
    die("Invalid request");
}

// Full path to the invoice PDF
$invoicePath = $_SERVER['DOCUMENT_ROOT'] . "/printshop/invoices/invoice_{$order_id}.pdf";

// If it doesn't exist, generate it from the API folder
if (!file_exists($invoicePath)) {
    include_once("../api/generate_invoice.php"); // ✅ Note: this goes up one folder to api/
}

// Now serve the file if it exists
if (file_exists($invoicePath)) {
    header("Content-Type: application/pdf");
    header("Content-Disposition: attachment; filename=invoice_{$order_id}.pdf");
    readfile($invoicePath);
    exit;
} else {
    echo "Invoice could not be generated.";
}
