<?php
require_once '../vendor/dompdf-3.1.0/autoload.inc.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);

$dompdf = new Dompdf($options);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['type']) && isset($_POST['data'])) {

    $type = trim($_POST['type']);
    $id = trim($_POST['data']);
    $downloadFileName = '';

    if (empty($type) || empty($id)) {
        include("../config/config.php");
        include('../content/shared/error.php');
        exit;
    }
    ob_start();

    switch ($type) {
        case 'bill':
            $downloadFileName = "Bill_$id";
            $_GET['billNum'] = $id;
            include("../print/cust_bill.php");
            break;
        case 'eventConfirmation':
            $downloadFileName = "Event Confirmation - $id";
            $_POST['billNum'] = $id;
            include("../print/event_confirmation.php");
            break;
        default:
            include("../config/config.php");
            include('../content/shared/error.php');
            exit;
    }

    $html = ob_get_clean();

    if (!$html) {
        include("../config/config.php");
        include('../content/shared/error.php');
        exit;
    }

    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    file_put_contents('sDebug.html', $html);

    // Output PDF to browser
    $dompdf->stream("$downloadFileName.pdf", ['Attachment' => false]);
} else {
    include("../config/config.php");
    include('../content/shared/error.php');
    exit;
}
