<?php
if (!defined('_PS_VERSION_')) {
    exit;
}
class InpostHelper extends Module
{
    public static function requirePdfFiles()
    {
        require_once(_INPOST_TOOLS_DIR_.'mpdf/mpdf.php');
        require_once(_INPOST_TOOLS_DIR_.'barcode/barcode.php');
        require_once(_INPOST_TOOLS_DIR_.'pdf_merge/PDFMerger.php');

    }


    public static function generateBarcode($packageId)
    {
        $barcodeobj = new TCPDFBarcode($packageId, 'C128C');

        return $barcodeobj->getBarcodePNG($packageId, 2, 50);
    }

    public static function mergePdf($files)
    {
        self::requirePdfFiles();
        $pdf = new PDFMerger;
        if (isset($files)) {
            foreach ($files as $file) {
                $pdf->addPDF($file);
            }

            $pdf->merge('download', 'Manifest - InPost' . date('Y-m-d-H-i') . '.pdf');
            exit;
        }
    }


    public static function generateManifestPdf($html, $key)
    {

        $mpdf=new mpdf('UTF-8', 'A4', '', '', 5, 5, 5, 5, 5, 5);
        $mpdf->useOnlyCoreFonts = true;
        $mpdf->showImageErrors = false;
        $mpdf->progressBar = false;
        $mpdf->WriteHTML($html);

        $html = (new InpostHelper())->htmlAssign('manifestPDFFooter');

        $mpdf->setHtmlFooter($html);

        $mpdf->Output(_PS_MODULE_DIR_.'/inpost/pdf/manifest'.$key.'.pdf', 'f');
    }

    /**
     * Get html code from tpl
     *
     * @param $identifier identifier block in `$tpl`
     * @param null $blocks html code or array with html codes
     * @param string $tpl tpl file for getting html code
     * @return mixed
     */
    public function htmlAssign($identifier, $blocks = null, $tpl = 'hook/blocks.tpl')
    {
        $context = $this->context;

        $context->smarty->assign($identifier, true);

        if($blocks && is_array($blocks)) {
            foreach ($blocks as $block_key => $block_value) {
                $context->smarty->assign($block_key, $block_value);
            }
        }

        return $context->smarty->fetch(INPOST_TPL_DIR . $tpl);
    }
}
