<?php

namespace KupShop\AdminBundle\Util\PrintCenter\PDF;

use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Pdf\HTMLToPDF;
use KupShop\KupShopBundle\Util\Price\Price;
use Query\Operator;

class StockInPDF
{
    /**
     * @var CurrencyContext
     */
    public $currencyContext;

    public function getPDF($stockInId)
    {
        $html = $this->createHTML($stockInId);

        $pdf = new HTMLToPDF();

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

    protected function createHTML(string $stockInId): string
    {
        $dbcfg = \Settings::getDefault();

        $smarty = createSmarty(true, true);

        $data['header'] = sqlQueryBuilder()
            ->select('si.*, s.name as supplier_name')
            ->from('stock_in', 'si')
            ->leftJoin('si', 'suppliers', 's', 's.id = si.id_supplier')
            ->where(Operator::equals(['si.id' => $stockInId]))
            ->execute()->fetch();

        $qb = sqlQueryBuilder()
            ->select('si.id, COALESCE(pv.ean, p.ean) as ean, si.id_product, si.id_variation, si.price, si.quantity, si.name, p.title as product_title, pv.title as variation_title, v.vat')
            ->from('stock_in_items', 'si')
            ->leftJoin('si', 'products', 'p', 'p.id=si.id_product')
            ->leftJoin('p', 'products_variations', 'pv', 'pv.id=si.id_variation')
            ->leftJoin('p', 'vats', 'v', 'v.id=p.vat')
            ->where(Operator::equals(['si.id_stock_in' => $stockInId]))
            ->orderBy('si.id', 'DESC');

        if (findModule(\Modules::PRODUCTS_VARIATIONS, \Modules::SUB_CODE)) {
            $qb->addSelect('COALESCE(pv.code, p.code) as code');
        } else {
            $qb->addSelect('p.code as code');
        }

        $data['header']['total_price_vat'] = 0;
        foreach ($qb->execute()->fetchAll() as $item) {
            $item['priceObject'] = new Price(toDecimal($item['price']), $this->currencyContext->getDefault(), $item['vat']);
            $data['header']['total_price_vat'] += ($item['price'] * $item['quantity']) * (1 + $item['vat'] / 100);
            $data['items'][] = $item;
        }

        $smarty->assign([
            'body' => [
                'data' => $data,
            ],
        ]);

        return $smarty->fetch('printCenter/pdf/stockInPDF.tpl');
    }

    /**
     * @required
     */
    public function setCurrencyContext(CurrencyContext $currencyContext)
    {
        $this->currencyContext = $currencyContext;
    }
}
