<?php

class PrintPDF
{
    public static function getInvoicePDFContent($id)
    {
        $html_content = self::getHTMLContent($id);

        $pdf = new HTMLToPDF();

        return $pdf->generatePDF($html_content, null, true);
    }

    public static function getHTMLContent($id)
    {
        $lang = getVal('lang');
        switchLanguage($lang);
        loadLanguage('printOrder', $lang);

        $smarty = createSmarty(false, true);

        $order = new Order($id);
        $order->createFromDB($id, true, true, true);
        $order->fetchItems();

        changeCurrency($order->currency);

        $invoice_force = getVal('invoice_force');
        if (!empty($invoice_force)) {
            $order->status = $invoice_force;
        }

        if (getVal('proforma')) {
            $smarty->assign(['proforma' => true]);
        }

        global $dbcfg, $cfg;
        if (getVal('rate')) {
            $dbcfg['currency'] = '€';
            $dbcfg['rate'] = getVal('rate');
        } else {
            $dbcfg['rate'] = 1;
        }

        if (!$order->date_handle) {
            $order->date_handle = new DateTime();
        }

        $order['date_payment'] = clone $order->date_handle;
        $order['date_payment'] = $order['date_payment']->modify(' + '.($dbcfg['shop_due_days'] ?: '0').' days');

        $smarty->assign([
            'order' => $order,
            'dbcfg' => $dbcfg,
            'cfg' => $cfg,
        ]);

        $template_name = getVal('template');

        $template = 'pdf/'.$template_name.'.tpl';

        if ($smarty->templateExists($template)) {
            $result = $smarty->fetch($template);
        } else {
            $result = $smarty->fetch('pdf/invoicePDF.tpl');
        }

        changeCurrency();

        return $result;
    }
}
