<?php
/******************************************************************************
 *   ______                                                                   *
 *  /       \                                                                 *
 * /$$$$$$  | ________  __    __   ______    ______                           *
 * $$ |__$$ |/        |/  |  /  | /      \  /      \                          *
 * $$    $$ |$$$$$$$$/ $$ |  $$ |/$$$$$$  |/$$$$$$  |                         *
 * $$$$$$$$ |  /  $$/  $$ |  $$ |$$ |  $$/ $$    $$ |                         *
 * $$ |  $$ | /$$$$/__ $$ \__$$ |$$ |      $$$$$$$$/                          *
 * $$ |  $$ |/$$      |$$    $$/ $$ |      $$       |                         *
 * $$/   $$/ $$$$$$$$/  $$$$$$/  $$/        $$$$$$$/                          *
 *                                                                            *
 * @PROJECT    : 3D Preview Extension [Magetop.com]                           *
 * @AUTHOR     : Azure - Developer                                            *
 * @COPYRIGHT  : © 2019  Magetop.com                                          *
 * @LINK       : https://Magetop.com                                          *
 * @CREATED    :  10/01/2022                                                  *
 ******************************************************************************/

namespace Magetop\Advancepreview\Controller\Order;

use Magento\Framework\App\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;
class PrintInvoice extends Action\Action
{
    protected $httpContext;
    protected $filesystem;
    protected $file;
    protected $fileFactory;
    protected $bookTicket;
    protected $x;
    protected $y;
    protected $company_name;
    protected $item_name;
    protected $ticket_price;
    protected $ticket_time;
    /**
     * @var \Magento\Framework\Stdlib\StringUtils
     */
    protected $stringUtils;
    protected $urlInterface;
    protected $priceHelper;
    protected $session;
    protected $timeHelper;
    /**
     * @var \Magetop\Bookingonline\Model\ResourceModel\BookOrders\CollectionFactory
     */
    protected $bookOrdersFactory;
    protected $productMetadata;
    protected $preview_pdf;
    protected $orderFactory;
    protected $cart;
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\ProductFactory
     */
    protected $resProductFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $colProductFactory;
    /**
     * @var \Magento\Customer\Model\Session
     */
    // protected $customerSession;
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;
    protected $colPreviewDiscountFactory;
    protected $colPreviewAdditionalFactory;
    protected $colPreviewThreeFactory;
    protected $dailyShippingFactory;
    protected $font_small = 10;
    protected $font_normally = 12;
    protected $font_big = 16;
    protected $itemFactory;
    protected $resItemFactory;
    protected $wishlistOptionFactory;
    protected $addressFactory;
    protected $previewHelper;
    protected $number_page = 0;
    protected $current_page = null;
    protected $foolter_texts = [];
    protected $colPreviewOrderItemsFactory;
    protected $_scopeConfig;
    protected $fileStorageDatabase;
    protected $_mediaDirectory;
    protected $invoice;
    protected $addressCollectionFactory;
    public function __construct(
        Action\Context $context,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Filesystem\Driver\File $file,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Stdlib\StringUtils $stringUtils,
        \Magento\Framework\UrlInterface $urlInterface,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\MediaStorage\Helper\File\Storage\Database $fileStorageDatabase,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magento\Customer\Model\Session $session,
        \Magento\Framework\App\ProductMetadataInterface $productMetadata,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $resProductFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $colProductFactory,
        \Magento\Sales\Model\Order\Invoice $invoice,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory $colPreviewDiscountFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory $colPreviewAdditionalFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        \Magento\Wishlist\Model\ItemFactory $itemFactory,
        \Magento\Wishlist\Model\ResourceModel\ItemFactory $resItemFactory,
        \Magento\Wishlist\Model\ResourceModel\Item\Option\CollectionFactory $wishlistOptionFactory,
        \Magento\Customer\Model\AddressFactory $addressFactory,
        \Magetop\Advancepreview\Helper\Data $previewHelper,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        \Magento\Sales\Model\ResourceModel\Order\Address\CollectionFactory $addressCollectionFactory
    )
    {
        parent::__construct($context);
        $this->httpContext = $httpContext;
        $this->filesystem = $filesystem;
        $this->file = $file;
        $this->fileFactory = $fileFactory;
        $this->stringUtils = $stringUtils;
        $this->urlInterface = $urlInterface;
        $this->_scopeConfig = $scopeConfig;
        $this->fileStorageDatabase = $fileStorageDatabase;
        $this->priceHelper = $priceHelper;
        $this->session = $session;
        $this->productMetadata = $productMetadata;
        $this->orderFactory = $orderFactory;
        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->colProductFactory = $colProductFactory;
        $this->httpContext = $httpContext;
        $this->colPreviewDiscountFactory = $colPreviewDiscountFactory;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
        $this->customerFactory = $customerFactory;
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->itemFactory = $itemFactory;
        $this->resItemFactory = $resItemFactory;
        $this->wishlistOptionFactory = $wishlistOptionFactory;
        $this->addressFactory = $addressFactory;
        $this->previewHelper = $previewHelper;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $this->invoice = $invoice;
        $this->addressCollectionFactory = $addressCollectionFactory;
    }
    public function execute()
    {
        $invoiceId = $this->getRequest()->getParam('invoice_id',0);
        $itemId = $this->getRequest()->getParam('item_id',0);
        if($invoiceId <= 0 || $itemId <= 0) {
            $this->messageManager->addErrorMessage(__('Invoice not found, please check again'));
            return   $this->resultRedirectFactory->create()->setPath('index.php');
        }
        try {
            $pdf = new \Zend_Pdf();
            $this->setPreviewPdf($pdf);
            /** @var \Zend_Pdf_Page $page*/
            $numberPage = $this->number_page;
            $page = $this->getPreviewPdf()->pages[$numberPage];
            //   $page->drawLine(0,842 - $ticketHeight,595,842 - $ticketHeight);
            $this->x = 20;
            $this->y = 822; //print table row from page top – 100px
            $this->insertLogo($page);
            $this->y = 800;

            $invoice = $this->getInvoiceById($invoiceId);
            if(!$invoice) {
                $this->messageManager->addErrorMessage(__('Invoice not found, please check again'));
                return   $this->resultRedirectFactory->create()->setPath('index.php');
            }
            $this->renderHeaderInvoice($page,$invoice);
            $shippingAddress = $invoice->getOrder()->getShippingAddress();
            $this->renderShippingAddress($page,$shippingAddress);
            $this->y -= 20;
            // print item
            $customerId = $invoice->getOrder()->getCustomerId();
            $items = $invoice->getOrder()->getAllItems();
            $this->current_page = $page;
            if(count($items)) {
                foreach ($items as $item) {
                    if($itemId != $item->getId()) {
                        continue;
                    }
                    $productId = $item->getProduct()->getId();
//                     $infoBuyRequest = $item->getProductOptionByCode('info_buyRequest');
                    $infoBuyRequest = $this->getCustomItemDetail($item);
//                     $productId = isset($infoBuyRequest['product']) ? $infoBuyRequest['product'] : 0;
                    $qty = isset($infoBuyRequest['qty']) ? $infoBuyRequest['qty'] : 0;
//                     $customerId = isset($infoBuyRequest['customer_id']) ? $infoBuyRequest['customer_id'] : 0;
                    $_product = $this->getProductById($productId);
                    $tierPrice = $this->getTierPriceByProductId($_product);
                    $tierQtyPrice = $this->getTierPriceItemByQty($tierPrice, $qty);
                    $ourPrice = $this->getCustomTierOurPrice($_product,$tierQtyPrice);
                    $customDiscounts = $this->getPreviewDiscounts($productId);
                    $i = 0;
                    $totalExtraPrice = 0;
                    $shippingPrice = 0;
                    $designType = isset($infoBuyRequest['txt_custom_preview_design_type']) ? $infoBuyRequest['txt_custom_preview_design_type'] : 0;
                    $shippingDailyId = isset($infoBuyRequest['txt_daily_shipping']) ? $infoBuyRequest['txt_daily_shipping'] : 0;
                    $offerId = isset($infoBuyRequest['request_offer_id']) ? $infoBuyRequest['request_offer_id'] : 0;
                    $projectName = isset($infoBuyRequest['custom_project_name']) ? $infoBuyRequest['custom_project_name'] : '';
                    $paramsAdditionOptions = isset($infoBuyRequest['preview_additional_options']) ? $infoBuyRequest['preview_additional_options'] : [];
                    $shippingDaily = $this->getDailyShippingById($shippingDailyId);
                    $dailyPrice = 0;
                    $dailyTitle = '';
                    $dailyDay  = 0;
                    $additionOptionTitle = '';
                    if($shippingDaily != null && $shippingDaily->getId()) {
                        $dailyPrice = $shippingDaily->getData('amount');
                        $dailyTitle = $shippingDaily->getData('delivery_type');
                        $dailyDay = $shippingDaily->getData('delivery_days');
//                    $dailyDays = $shippingDaily->getData('delivery_days');
                    }
                    foreach ($customDiscounts as $customDiscount) {
                        if ($i == 0) {
                            $i++;
                            continue;
                        }
                        if ($designType == 1 && $i == 1) {
                            $additionOption = $this->getAdditionPriceByIds($paramsAdditionOptions);
                            $totalExtraPrice += $additionOption['price'];
                            $additionOptionTitle .= implode(',',$additionOption['title']);
                        } else if ($i == $customDiscounts->getSize() - 1) {
                            $shippingPrice = $customDiscount->getData('discount_price') + ($ourPrice * $dailyPrice * $item->getQtyOrdered()) / 100;
                            continue;
                        }
                        $totalExtraPrice += $customDiscount->getData('discount_price');

                        $i++;
                    }
                    $previewOptions = [
                        'our_price'=>$ourPrice,
                        'qty'=>$qty,
                        'extra_price'=>$totalExtraPrice,
                        'shipping_price'=>$shippingPrice,
                        'discount'=>$_product->getData('pcto_discount'),
                        'offer_id'=>$offerId,
                        'product_id'=>$productId,
                        'customer_id'=>$customerId,
                        'project_name'=>$projectName,
                        'addition_title'=>$additionOptionTitle,
                        'daily_title'=>$dailyTitle,
                        'daily_day'=>$dailyDay,
                    ];
                    $productInfo = [
                        'product_name'=>$_product->getName(),
                        'product_sku'=>$_product->getSku(),
                        'product_description'=>strip_tags($_product->getData('pdf_product_description')),
                    ];
                    $this->renderItems( $page,$previewOptions,$productInfo,$_product );
                }
            }
            $fileName = 'myfitmix-invoice-'.date('Y-m-d-H-i-s').'.pdf';
           $this->fileFactory->create(
                $fileName,
                $pdf->render(),
                DirectoryList::VAR_DIR,
                'application/pdf'
            );
        }
        catch (\Exception $exception) {

        }
    }

    /**
     * @param \Zend_Pdf_Page $page
     * @param \Magento\Sales\Model\Order\Invoice $invoice
     */
    protected function renderHeaderInvoice(\Zend_Pdf_Page &$page, $invoice) {
        $subMedia = '/advancepreview/icons/';
        $bg = $subMedia.'bg_invoice_header.png';
        $this->addImageToPdf($page,$bg,$this->x, 734, 575, $this->y);
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES_ROMAN);
        $style = new \Zend_Pdf_Style();
        //logo
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(1,1,1)); //red
        $page->setStyle($style);
        $xText = $this->x + 10;
        $yText = $this->y - 20;
        $page->drawText('Invoice # '.$invoice->getIncrementId(),$xText,   $yText,'UTF-8');
        $yText -= $this->font_small + 5;
        $page->drawText('Order # '.$invoice->getOrder()->getIncrementId(),$xText,   $yText,'UTF-8');
        $yText -= $this->font_small + 5;
        $orderDate = date('M d Y',strtotime($invoice->getOrder()->getCreatedAt()));
        $page->drawText('Order Date # '.$orderDate,$xText,   $yText,'UTF-8');
        $this->y = 734;
    }

    /**
     * @param \Zend_Pdf_Page $page
     * @param \Magento\Sales\Model\Order\Address $shippingAddress
     * @throws \Zend_Pdf_Exception
     */
    protected function renderShippingAddress(
        \Zend_Pdf_Page &$page,
        $shippingAddress
    ) {
        $subMedia = '/advancepreview/icons/';
        $bg = $subMedia.'bg_shipping.png';
        $this->addImageToPdf($page,$bg,$this->x, 574, 575, $this->y);
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES_ROMAN);
        $style = new \Zend_Pdf_Style();
        //logo
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $xText = $this->x + 10;
        $yText = $this->y - 50;
        $xRight = 286;
        $stresses = $shippingAddress->getStreet();
        $page->drawText($shippingAddress->getName(),$xText,   $yText,'UTF-8');
        $page->drawText($shippingAddress->getName(),$xRight,   $yText,'UTF-8');
        $yText -= $this->font_small + 5;
        if(count($stresses)) {
            foreach ($stresses as $stress) {
                $page->drawText($stress,$xText,   $yText,'UTF-8');
                $page->drawText($stress,$xRight,   $yText,'UTF-8');
                $yText -= $this->font_small + 5;
            }
        }
        $cityRegsion = $shippingAddress->getCity();
        if($shippingAddress->getRegion() != '') {
            $cityRegsion .= ', '. $shippingAddress->getRegion();
        }
        $cityRegsion .= ', '.$shippingAddress->getPostcode();
        $page->drawText($cityRegsion,$xText,   $yText,'UTF-8');
        $page->drawText($cityRegsion,$xRight,   $yText,'UTF-8');
        $yText -= $this->font_small + 5;
        $page->drawText($shippingAddress->getCountryId(),$xText,   $yText,'UTF-8');
        $page->drawText($shippingAddress->getCountryId(),$xRight,   $yText,'UTF-8');
        $yText -= $this->font_small + 5;
        $page->drawText('T: '. $shippingAddress->getTelephone(),$xText,   $yText,'UTF-8');
        $page->drawText('T: '. $shippingAddress->getTelephone(),$xRight,   $yText,'UTF-8');
        $yText -= $this->font_small + 5;
        $this->y = $yText;

    }
    protected function renderItems(
        \Zend_Pdf_Page &$page,
        $orderItems,
        $productInfo,
        $product
    ) {
//        print_r($orderItems);
        $tax = 19;
        // render header
        $xCol = $this->x;

        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style = new \Zend_Pdf_Style();
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText($product->getName(),$xCol, $this->y);
        $this->y -= 15;
        $yText = $this->y - 20;
//        $yText -= 15;
        $style = new \Zend_Pdf_Style();

        /* $fillColor = new \Zend_Pdf_Color_Rgb(0,0,0);
        $lineColor = new \Zend_Pdf_Color_Rgb(0.8,0.8,0.8);
       $this->drawBlockRect($page,$this->x, $this->y,$this->x + 520, $yText,$fillColor, $lineColor);*/
        $bg = 'advancepreview/icons/bg_gray.png';
        $this->addImageToPdf($page,$bg,$this->x,$yText,$this->x + 560,$this->y);
        // add text
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);


        $headers = [
            'Pos',
            'Q-ty',
            'Unit',
            'Description',
            'price ',
            'Discount',
            'Unit price',
            'Total price',
        ];
        $h = 0;
        foreach ($headers as $key => $header) {
            if($h == count($headers) - 1) {
                $wlast = $this->widthForStringUsingFontSize($header,$font,$this->font_small);
                $xLast = ($xCol + 71) - $wlast;
                $page->drawText($header,$xLast, $yText + 5,'UTF-8');
            }
            else {
                $page->drawText($header,$xCol + 5, $yText + 5,'UTF-8');
            }
            if($h == 3) {
                $xCol += 135;
            }
            elseif($h == 0 || $h == 2) {
                $xCol += 25;
            }
            elseif($h == 0 || $h == 2)  {
                $xCol += 30;
            }
            elseif($h == 1 || $h == 5)  {
                $xCol += 60;
            }
            else {
                $xCol += 90;
            }
            $h++;
        }
        if(count($orderItems)) {
            $discount = $orderItems['discount'];
            $qty = $orderItems['qty'];
            $k = 1;
            $grandTotalPrice = 0;
            $yText -= 20;
            foreach ($orderItems as $keyV => $orderItem) {
                $xCol = $this->x;

                $colPrice = 0;

                if($keyV == 'our_price') {
                    $m = 0;
//                    foreach ()
                    $colPrice = $orderItems['our_price'];

                }
                else if($keyV == 'extra_price') {
                    $colPrice = $orderItems['extra_price'];
                    $qty = 1;

                }
                else if($keyV == 'shipping_price') {
                    $colPrice = $orderItems['shipping_price'];
                    $qty = 1;
//                    $yText -= 20;
                }
                else {
                    continue;
                }
                $priceAfterDiscount = $colPrice - ($colPrice * $discount) / 100;
                $totalOurPrice = $priceAfterDiscount * $qty;
                $grandTotalPrice += $totalOurPrice;
                $cols = [
                    $k,
                    $qty,
                    'stk',
                    'test',
                    $this->convertNumberToPrice($colPrice),
                    $discount.'%',
                    $this->convertNumberToPrice($priceAfterDiscount),
                    $this->convertNumberToPrice($totalOurPrice)
                ];
                $m = 0;
                $yDes = 0;
                foreach ($cols as $col) {
                    if($m == 3) {
                        if($keyV == 'our_price') {
                            $productName = $productInfo['product_name'];
                            $productSku = $productInfo['product_sku'];
                            $productDes = $productInfo['product_description'];
                            $productDes = substr($productDes,0,45);
                            $yDes = $yText + 5;
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
//                            $page->drawText($productName,$xCol, $yDes);
//                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yDes,$productName,$font);
//                            $wProductName = $this->widthForStringUsingFontSize($productName,$font,$this->font_small);
//                            $yDes -= 15;
//                            $page->drawText($productSku,$xCol + 5, $yDes);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yDes,$productSku,$font);
                            $yDes -= 15;
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yDes,$productDes,$font);
                        }
                        elseif($keyV == 'extra_price') {
//                            $page->drawText('Additional printing costs 5C transparent Quality check Design service',$xCol + 5, $yText + 5);
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yText + 5,'Additional printing costs',$font);
                            $yDes -= 15;
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yDes,$orderItems['addition_title'],$font);
                        }
                        elseif($keyV == 'shipping_price') {
//                            $page->drawText('Delivery time: 8 days plus shipping',$xCol + 5, $yText + 5);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yText + 5,'Delivery time: '.$orderItems['daily_day'].' days plus shipping - '.$orderItems['daily_title'],$font);
                        }
                        /*else {
                            $page->drawText($col,$xCol + 5, $yText + 5);
                        }*/

                        $xCol += 135;
                    }
                    else if($m == count($cols) - 1) {
                        $wlast = $this->widthForStringUsingFontSize($col,$font,$this->font_small);
                        $xLast = ($xCol + 65) - $wlast;
                        $page->drawText($col,$xLast, $yText + 5,'UTF-8');
                    }
                    elseif($m == 0 || $m == 2) {
                        $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        $xCol += 30;
                    }
                    elseif($m == 1 || $m == 5) {
                        $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        $xCol += 60;
                    }
                    else {
                        $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        $xCol += 90;
                    }
                    $m++;
                    if($m == count($cols)) {
                        $yText = $yDes - 22;
                    }
                }
                $page->drawLine($this->x,$yText + 18,580,$yText + 18);
                $k++;
            }
            $yText -= 10;
//            Net Amount
            $xTotal = $xCol + (55 * 6) + 135;
            $page->drawText('Net Amount',$xCol, $yText,'UTF-8');
            $textGrand = $this->convertNumberToPrice($grandTotalPrice);
            $wGrandTotal = $this->widthForStringUsingFontSize($textGrand,$font,$this->font_small);
            $xGrandTotal = 580 - $wGrandTotal;
            $page->drawText($textGrand,$xGrandTotal, $yText,'UTF-8');
            $taxAmount = ($grandTotalPrice * $tax) / 100;
            $grandTotalPriceTax = $grandTotalPrice + ($grandTotalPrice * $tax) / 100;
            $taxAmount = $this->convertNumberToPrice($taxAmount);
            $yText -= 20;
            $page->drawText($tax.'% VAT',$xCol, $yText,'UTF-8');
            $wTax = $this->widthForStringUsingFontSize($taxAmount,$font,$this->font_small);
            $xTax = 580 - $wTax;
            $page->drawText($taxAmount,$xTax, $yText,'UTF-8');

            $yText -= 20;
            $fillColor = new \Zend_Pdf_Color_Rgb(0,0,0);
            $lineColor = new \Zend_Pdf_Color_Rgb(0,0,0);
//            $this->drawBlockRect($page,$this->x, $yText + 15,$this->x + 520, $yText - 5,$fillColor, $lineColor);
            $bg = 'advancepreview/icons/bg_gray.png';
            $this->addImageToPdf($page,$bg,$this->x,$yText - 10, $this->x + 560,$yText + 10);
            $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);
            $txtGrandTotalPriceTax = $this->convertNumberToPrice($grandTotalPriceTax);
            $wgrandTotalPriceTax = $this->widthForStringUsingFontSize($txtGrandTotalPriceTax,$font,$this->font_small);
            $xGrandTotalPriceTax = 580 - $wgrandTotalPriceTax - 3;
            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
            $style->setFont($font,$this->font_small);
            $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);
            $page->drawText('Amount to pay ',$xCol + 5, $yText - 5,'UTF-8');
            $page->drawText($txtGrandTotalPriceTax,$xGrandTotalPriceTax, $yText - 5,'UTF-8');
            //
            $yText -= 40;
            $y = $yText;
            $x = $this->x;
//            $this->y = $yText;
            if($y < 400) {
                /* $pdf = new \Zend_Pdf();
                 $this->setPreviewPdf($pdf,true);
                 $this->number_page++;
                 $numberPage = $this->number_page;*/
                /*   $page = $this->getPreviewPdf()->pages[$numberPage];
                   $this->y = 800;*/
//                $this->y = $y;
            }

            $y -= 40;
            $this->y = $y;
        }
    }
    protected function insertLogo(&$page, $store = null)
    {
        $this->y = $this->y ? $this->y : 815;
        $image = $this->_scopeConfig->getValue(
            'sales/identity/logo',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $store
        );
        if ($image) {
            $imagePath = '/sales/store/logo/' . $image;
            if ($this->fileStorageDatabase->checkDbUsage() &&
                !$this->_mediaDirectory->isFile($imagePath)
            ) {
                $this->fileStorageDatabase->saveFileToFilesystem($imagePath);
            }
            if ($this->_mediaDirectory->isFile($imagePath)) {
                $image = \Zend_Pdf_Image::imageWithPath($this->_mediaDirectory->getAbsolutePath($imagePath));
                $top = 830;
                //top border of the page
                $widthLimit = 270;
                //half of the page width
                $heightLimit = 270;
                //assuming the image is not a "skyscraper"
                $width = $image->getPixelWidth();
                $height = $image->getPixelHeight();

                //preserving aspect ratio (proportions)
                $ratio = $width / $height;
                if ($ratio > 1 && $width > $widthLimit) {
                    $width = $widthLimit;
                    $height = $width / $ratio;
                } elseif ($ratio < 1 && $height > $heightLimit) {
                    $height = $heightLimit;
                    $width = $height * $ratio;
                } elseif ($ratio == 1 && $height > $heightLimit) {
                    $height = $heightLimit;
                    $width = $widthLimit;
                }

                $y1 = $top - $height;
                $y2 = $top;
                $x1 = 25;
                $x2 = $x1 + $width;

                //coordinates after transformation are rounded by Zend
                $page->drawImage($image, $x1, $y1, $x2, $y2);

                $this->y = $y1 - 10;
            }
        }
    }
    public function addBlockText($page,$x0,$x1,$x2,$y1,$text,$font) {
        $arText = explode(' ',$text);
        $x = $x1;
        if(count($arText)) {
            $i = 0;
            foreach ($arText as $str) {
                $textTmp = $str . ' ';
                $tmpW = $this->widthForStringUsingFontSize($textTmp,$font,$this->font_small);
                if($x + $tmpW >= $x2) {
                    $x = $x0;
                    $y1 -= 15;
                    $page->drawText($textTmp, $x, $y1);
                    $x += $tmpW;
                }
                else {
                    $page->drawText($textTmp, $x, $y1);
                    $x += $tmpW;
                }
            }
        }
        return $y1;

    }
    public function widthForStringUsingFontSize($string, $font, $fontSize)
    {
        $drawingString = @iconv(
            'UTF-8',
            'UTF-16BE',
            $string
        );

        $characters = [];
        for ($i = 0; $i < strlen($drawingString); $i++) {
            $characters[] = ord($drawingString[$i++]) << 8 | ord($drawingString[$i]);
        }
        $glyphs = $font->glyphNumbersForCharacters($characters);
        $widths = $font->widthsForGlyphs($glyphs);
        $stringWidth = array_sum($widths) / $font->getUnitsPerEm() * $fontSize;
        return $stringWidth;
    }
    protected function getInvoiceById($invoidId) {
        return $this->invoice->load($invoidId);
    }
    protected function getOrderById($invoidId) {
        return $this->orderFactory->create()->load($invoidId);

    }
    protected function getAddressById($addressId = 0) {
        return $this->addressCollection->create()->addFieldToFilter('entity_id',array($addressId))->getFirstItem();
    }
    protected function getCustomerGroup() {
        $group = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->session->getCustomerId();
            $customer = $this->customerFactory->create()->load($customerId);
            $group = $customer->getGroupId();

        }
        return $group;
    }
    protected function getCustomerName($customerId) {
        $customer = $this->customerFactory->create()->load($customerId);
        return $customer->getName();
    }
    protected function getCustomerAddress($customerId) {
        $shippingAddress = null;
        $customer = $this->customerFactory->create()->load($customerId);
        $shippingAddressId = $customer->getDefaultShipping();
        $shippingAddress = $this->addressFactory->create()->load($shippingAddressId);
        return $shippingAddress;
    }
    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }
    protected function addImageToPdf(
        \Zend_Pdf_Page &$page,
        $image,
        $x1,
        $y1,
        $x2,
        $y2
    ) {
        try {
            $mediaDictory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
            $image = \Zend_Pdf_Image::imageWithPath($mediaDictory->getAbsolutePath($image));
            $page->drawImage($image,$x1, $y1,$x2, $y2);
            return true;
        }
        catch (\Exception $exception) {

        }
        return  false;
    }
    function convertNumberToPrice($price) {
        return $this->priceHelper->currency($price,true,false);
    }
    public function getAdditionPriceByIds($ids = []) {
        $price = 0;
        $titles = [];
        if(count($ids)) {
            $collection = $this->colPreviewAdditionalFactory->create()
                ->addFieldToSelect(array('*'))
                ->addFieldToFilter('addition_id', array('in'=>implode(',',$ids)));
            // echo (string)$collection->getSelect();
            if($collection && $collection->getSize() > 0) {
                foreach ($collection as $item) {
                    $price += $item->getData('price');
                    $titles[] = trim($item->getData('title'));
                }
            }
        }
        return array(
            'title'=>$titles,
            'price'=>$price
        );
    }
    public function getDailyShippingById($dailyId = 0) {
        if($dailyId > 0) {
            $collection = $this->dailyShippingFactory->create()
                ->addFieldToFilter('daily_shipping_id',$dailyId);
            return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        }
        return  null;
    }
    protected function getPreviewDiscounts($productId = 0) {
        $collection = $this->colPreviewDiscountFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
        return $collection;
    }
    protected function getCustomTierOurPrice($product, $price = 0) {

        $customerGroup = $this->getCustomerGroup();
        if($customerGroup > 1) {
//            $product = $this->getProductById($productId);
            if($product) {
                $discount = $product->getData('pcto_discount');
                /* if($discount > 0) {
                     $price -= ($price * $discount) / 100;
                 }*/
            }
        }
        return $price;

    }
    protected function getTierPriceItemByQty($tierPriecs = [], $qty = 0)
    {
        $price = 0;
        $lastIndex = count($tierPriecs) ? count($tierPriecs) - 1 : 0;
        $lastItem = isset($tierPriecs[$lastIndex]) ? $tierPriecs[$lastIndex] : [];
        if ($lastIndex > 0 && isset($lastItem['price_qty']) && $qty >= $lastItem['price_qty']) {
            $price = $lastItem['price'];
        } else {
            for ($i = 0; $i < count($tierPriecs); $i++) {
                if ($i == 0 && $qty < $tierPriecs[0]['price_qty']) {
                    $price = $tierPriecs[0]['price'];
                    break;
                }
                if ($i + 1 < count($tierPriecs)) {
                    $currentTeir = $tierPriecs[$i];
                    $nextTier = $tierPriecs[$i + 1];
                    if ($qty >= $currentTeir['price_qty'] && $qty < $nextTier['price_qty']) {
                        $price = $currentTeir['price'];
                        break;
                    }
                }
            }
        }

        return $price;
    }
    protected function getTierPriceByProductId($product) {
        $tierPrices = [];
//        $_product = $this->getProductById($productId);
        if($product != null) {
            $tierPrices = $product->getTierPrice();
        }
        return $tierPrices;
    }
    protected function getProductById($productId = 0) {
        $product = $this->productFactory->create();
        $this->resProductFactory->create()->load($product, $productId);
        return $product;
    }
    protected function getCustomItemDetail(
        \Magento\Sales\Model\Order\Item $item
    ) {
         $infoRequest = $item->getProductOptionByCode('info_buyRequest');
        return $infoRequest;
    }
    protected function setPreviewPdf(\Zend_Pdf $pdf,$isNew = true) {
        if($isNew)
            $pdf->pages[] = $pdf->newPage(\Zend_Pdf_Page::SIZE_A4);
        $this->preview_pdf = $pdf;
    }
    protected function getPreviewPdf() {
        //Size A4: 595x842
        return $this->preview_pdf;
    }
}
