<?php

/**
 * viabook platform for Contao Open Source CMS
 *
 * Copyright (C) 2012-2013 eSalesMedia
 *
 * @package    eSM_viabook
 * @link       http://www.esales-media.de
 * @license    commercial
 *
 * @author     Benjamin Roth <benjamin@esales-media.de>
 */

namespace eSM_isotope_custom\Pdf;

use Isotope\Model\Product;
use Isotope\Interfaces\IsotopeProduct;
use Isotope\Interfaces\IsotopeAttribute;
use Isotope\Model\Gallery;


class ModuleExpertisePdf extends \Module
{

    /**
     * Template
     * @var String
     */
    protected $strTemplate = '';

    /**
     * Product model
     * @var IsotopeProduct|null
     */
    protected $objProduct = null;

    /**
     * @return string
     */
    public function generate()
    {
        global $objPage;

        if (TL_MODE == 'BE')
        {
            /** @var \BackendTemplate|object $objTemplate */
            $objTemplate = new \BackendTemplate('be_wildcard');

            $objTemplate->wildcard = '### ' . utf8_strtoupper($GLOBALS['TL_LANG']['FMD']['expertisePDF'][0]) . ' ###';
            $objTemplate->title = $this->headline;
            $objTemplate->id = $this->id;
            $objTemplate->link = $this->name;
            $objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;

            return $objTemplate->parse();
        }

        $strBuffer = parent::generate();

        if (empty($strBuffer))
        {
            return '';
        }


        return $strBuffer;
    }

    /**
     * Compile the current element
     */
    protected function compile()
    {
        global $objPage;

        // Set the item from the auto_item parameter
        if ($GLOBALS['TL_CONFIG']['useAutoItem'] && in_array('product', $GLOBALS['TL_AUTO_ITEM']))
        {
            \Input::setGet('product', \Input::get('auto_item'));
        }


        // Stop if no expertise should be generated
        if (!isset($_GET['expertisePdf']) || !\Input::get('product'))
        {
            return;
        }


        // Load product model
        $objProduct = Product::findAvailableByIdOrAlias(\Input::get('product'));

        if (null === $objProduct)
        {
            return;
        }

        $this->objProduct = $objProduct;

        $this->createPdf();

    }

    protected function createPdf()
    {
        // Load language file
        \System::loadLanguageFile('ExpertisePdf');

        // Print date
        $objTime = new \Date();

        // Instantiate PDF
        if (!empty($this->classname))
        {
          $PDF = new ExpertisePdf($this->classname);
        } else {
          $PDF = new ExpertisePdf();
        }

        // Baseprice
        $Baseprice = deserialize($this->objProduct->baseprice,true);

        // Gallery
        $GalleryFiles = Gallery::createForProductAttribute($this->objProduct,'images',array('gallery'=>1))->getFiles();

        /*** Page 1 ***/
        // Datum
        $intLabelLength = 35;
        $intValOffset = 40;
        $intValLength = 70;
        $intBoxContentLength = $intValOffset+$intValLength;
        $intContentLength = 115;
        $intLabelFontSize = 10;
        $intValueFontSize = 11;
        $intContentFontSize = 12;
        $intHeadlineFontSize = 14;
        $margins = $PDF->pdf->getMargins();


        $PDF->pdf->SetFont(PDF_FONT_NAME_MAIN);
        $PDF->pdf->SetTextColor(86,85,79,100);

        switch($this->objProduct->type)
        {
            case 1:
            case 2:

                if (is_array($GalleryFiles) && count($GalleryFiles))
                {
                    $strFile = $GalleryFiles[0]['src'];
                    if (strpos($strFile, '/') === false) {
                        $strFile = 'isotope/' . strtolower(substr($strFile, 0, 1)) . '/' . $strFile;
                    }
//                    $PDF->pdf->Image(TL_ROOT . '/'.$strFile, $margins['left'], $margins['top'],40,185,'PNG','','T',true,300,'',false,false,0,true);
                    $PDF->pdf->Image(TL_ROOT . '/'.$strFile, $margins['left'], $margins['top']+5,40,160,'','','T',true,150,'',false,false,0,true);
                }

                $PDF->pdf->SetTextColor(17,40,70,0);
                $PDF->pdf->SetTextColor(193,102,21);
                $PDF->pdf->SetCellHeightRatio(1.25);
                $PDF->pdf->SetXY($margins['left']+65,$margins['top']);
                /*$PDF->pdf->CreateCell(8,0,'',0,25,'','L',PDF_FONT_NAME_ICON);
                $PDF->pdf->setX($margins['left']+65+8);*/
                $PDF->pdf->CreateMultiCell($intContentLength,0,$this->generateAttribute('name').($this->generateAttribute('jahrgang') ? " ".$this->generateAttribute('jahrgang') : ''),0,25,'','L',PDF_FONT_NAME_MAIN);
                if ($this->generateAttribute('qualitaet') || $this->generateAttribute('geschmack') || $this->generateAttribute('flascheninhalt'))
                {
                  $PDF->pdf->lbr(1);
//                  $PDF->pdf->SetX($margins['left']+65+8);
                  $PDF->pdf->SetX($margins['left']+65);
                  $PDF->pdf->CreateMultiCell($intContentLength,0,($this->generateAttribute('qualitaet') ? $this->generateAttribute('qualitaet')." " : '').($this->generateAttribute('geschmack') ? $this->generateAttribute('geschmack')." " : '').rtrim(rtrim(\System::getFormattedNumber($this->generateAttribute('flascheninhalt'),3),'0'),',').' l',0,17,'','L',PDF_FONT_NAME_MAIN);
                }
                if ($this->generateAttribute('zusatz'))
                {
                  $PDF->pdf->lbr(1);
                  //                  $PDF->pdf->SetX($margins['left']+65+8);
                  $PDF->pdf->SetX($margins['left']+65);
                  $PDF->pdf->CreateMultiCell($intContentLength,0,$this->generateAttribute('zusatz'),0,$intHeadlineFontSize,'','L',PDF_FONT_NAME_MAIN);
                }
                $PDF->pdf->lbr(3);

                $PDF->pdf->SetTextColor(17,40,70,0);
                $PDF->pdf->SetTextColor(193,102,21);
                $PDF->pdf->setX($margins['left']+65);
                $PDF->pdf->CreateCell($intContentLength,0,'Charakteristik',1,$intHeadlineFontSize,'');
                $PDF->pdf->SetTextColor(86,85,79,100);
                $PDF->pdf->setX($margins['left']+65);
                $PDF->pdf->CreateMultiCell($intContentLength,0,preg_replace('/\s+$/','',ucfirst(strip_tags($PDF->pdf->unhtmlentities(\StringUtil::restoreBasicEntities(str_ireplace(['<br>','<br />'],["\n","\n"],$this->generateAttribute('charakteristik'))))))."\n"),0,$intContentFontSize,'','L',PDF_FONT_NAME_DATA);
                $PDF->pdf->lbr(2);

                if ($this->objProduct->besonderheit) {
                  $PDF->pdf->SetTextColor(17,40,70,0);
                  $PDF->pdf->SetTextColor(193,102,21);
                  $PDF->pdf->setX($margins['left']+65);
                  $PDF->pdf->CreateCell($intContentLength,0,'Besonderheit',1,$intHeadlineFontSize,'');
                  $PDF->pdf->SetTextColor(86,85,79,100);
                  $PDF->pdf->setX($margins['left']+65);
                  $PDF->pdf->CreateMultiCell($intContentLength,0,ucfirst(strip_tags($PDF->pdf->unhtmlentities(\StringUtil::restoreBasicEntities($this->generateAttribute('besonderheit')))))."\n",0,$intContentFontSize,'','L',PDF_FONT_NAME_DATA);
                  $PDF->pdf->lbr(2);
                }

                if ($this->objProduct->speiseempfehlung) {
                  $PDF->pdf->SetTextColor(17,40,70,0);
                  $PDF->pdf->SetTextColor(193,102,21);
                  $PDF->pdf->setX($margins['left']+65);
                  $PDF->pdf->CreateCell($intContentLength,0,'Speiseempfehlung',1,$intHeadlineFontSize,'');
                  $PDF->pdf->SetTextColor(86,85,79,100);
                  $PDF->pdf->setX($margins['left']+65);
                  $PDF->pdf->CreateMultiCell($intContentLength,0,ucfirst(strip_tags($PDF->pdf->unhtmlentities(\StringUtil::restoreBasicEntities($this->generateAttribute('speiseempfehlung')))))."\n",0,$intContentFontSize,'','L',PDF_FONT_NAME_DATA);
                  $PDF->pdf->lbr(2);
                }

                /*if ($this->objProduct->trinktemperatur)
                {
                  $PDF->pdf->SetTextColor(17,40,70,0);
                  $PDF->pdf->SetTextColor(193,102,21);
                  $PDF->pdf->setX($margins['left']+65);
                  $PDF->pdf->CreateCell($intContentLength, 0, 'Empfohlene Trinktemperatur:', 1, $intHeadlineFontSize, '');
                  $PDF->pdf->SetTextColor(86, 85, 79, 100);
                  $PDF->pdf->setX($margins['left']+65);
                  $PDF->pdf->CreateMultiCell($intContentLength, 0, ucfirst(strip_tags($PDF->pdf->unhtmlentities($this->generateAttribute('trinktemperatur'))))." °C", 0, $intContentFontSize, '', 'L', PDF_FONT_NAME_DATA);
                  $PDF->pdf->lbr(2);
                }*/

                $PDF->pdf->lbr(2);
                $PDF->pdf->SetFont(PDF_FONT_NAME_DATA,'',PDF_FONT_SIZE_DATA);
                $PDF->pdf->SetTextColor(86,85,79,100);
                $PDF->pdf->SetCellHeightRatio(1.3);

                $box_Y1 = $PDF->pdf->GetY();
                $PDF->pdf2 = clone $PDF->pdf;
                $PDF->pdf2->setPrintHeader(false);
                $PDF->pdf2->setPrintFooter(false);
                $strClone = 'pdf2';

                for ($i=2; $i > 0; $i--)
                {

                  if ($this->objProduct->alkohol) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Alkohol', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, \System::getFormattedNumber($this->generateAttribute('alkohol'),1).' Vol. %', 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1.3);
                  }

                  if ($this->objProduct->restsuesse) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Restsüße', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, \System::getFormattedNumber($this->generateAttribute('restsuesse'),1).' g/Ltr.', 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1.3);
                  }

                  if ($this->objProduct->saeure) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Säure', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, \System::getFormattedNumber($this->generateAttribute('saeure'),1).' g/Ltr.', 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1.3);
                  }

                  /*
                  if ($this->objProduct->jahrgang) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Jahrgang:', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, $this->generateAttribute('jahrgang'), 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1);
                  }

                  if ($this->objProduct->qualitaet) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Qualitätsstufe:', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, $this->generateAttribute('qualitaet'), 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1);
                  }

                  if ($this->objProduct->geschmack) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Geschmack:', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, $this->generateAttribute('geschmack'), 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1);
                  }
                  */
                  if ($this->objProduct->rebsorte) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Rebsorte', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, $this->generateAttribute('rebsorte'), 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1.3);
                  }

                  /*if ($Baseprice['value']) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Inhalt:', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, rtrim(rtrim(\System::getFormattedNumber($Baseprice['value'],3),'0'),',').(in_array($this->objProduct->type,array(1,3)) ? ' l' : ''), 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1);
                  }*/

                  if ($this->objProduct->lagerfaehigkeit) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Lagerfähigkeit', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, $this->generateAttribute('lagerfaehigkeit').' Jahre', 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1.3);
                  }

                  if ($this->objProduct->trinktemperatur)
                  {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateMultiCell($intLabelLength, 0, 'Empfohlene Trinktemperatur', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, ucfirst(strip_tags($PDF->pdf->unhtmlentities($this->generateAttribute('trinktemperatur'))))." °C", 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1);
                  }

                  if ($this->objProduct->praemierungen) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Prämierung', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, $this->generateAttribute('praemierungen'), 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1.3);
                  }

                  /*if ($this->objProduct->sku) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'Artikelnummer:', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, $this->generateAttribute('sku'), 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1);
                  }

                  if ($this->objProduct->ean) {
                    $PDF->$strClone->SetTextColor(17,40,70,0);
                    $PDF->$strClone->SetTextColor(193,102,21);
                    $PDF->$strClone->SetX($margins['left']+65+2.5);
                    $PDF->$strClone->CreateCell($intLabelLength, 0, 'EAN:', 0, $intValueFontSize, 'B','L',PDF_FONT_NAME_DATA);
                    $PDF->$strClone->SetX($intValOffset + $margins['left']+65+2.5);
                    $PDF->$strClone->SetTextColor(86,85,79,100);
                    $PDF->$strClone->CreateMultiCell($intValLength, 0, $this->generateAttribute('ean'), 0, $intValueFontSize, '', 'L', PDF_FONT_NAME_DATA);
                    $PDF->$strClone->lbr(1);
                  }*/

                  $box_Y2 = $PDF->$strClone->GetY();

                  $strClone = 'pdf';

                  if ($i == 2)
                  {
                    $PDF->pdf->Rect($margins['left']+65, $box_Y1-2, $intContentLength, $box_Y2 - $box_Y1+4, 'F',array('all'=>array('width' => 0.1, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(193,102,21))), array(234,236,237));
                    //$PDF->pdf->RoundedRect($margins['left']+55, $box_Y1-2, $intBoxContentLength+5, $box_Y2 - $box_Y1+4, 4.0, '0101','F',array('width' => 0.2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 1, 'color' => array(35,52,75,13)), array(13, 26, 51, 0));
                    //$PDF->pdf->RoundedRect($margins['left'], $box_Y1-2, $intBoxContentLength+5, $box_Y2 - $box_Y1+4, 4.0, '0101','F',array('width' => 0.2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 1, 'color' => array(35,52,75,13)), array(80, 38, 100, 32));
                  }
                }

          unset($PDF->pdf2);
                $PDF->pdf->lbr(2);


            break;
        }



        // Generate PDF
        $PDF->documentFilename = $this->objProduct->sku.'_'.standardize($this->objProduct->name).'_'.$objTime->parse("Y-m-d").".pdf";

        $PDF->generate();

        // Stop script execution
        exit;
    }

    protected function generateAttribute($strAttribute, $blnStripTags = false, array $arrOptions = array()) {

        $objAttribute = $GLOBALS['TL_DCA']['tl_iso_product']['attributes'][$strAttribute];

        if (!($objAttribute instanceof IsotopeAttribute)) {
            throw new \InvalidArgumentException($strAttribute . ' is not a valid attribute');
        }

        $strBuffer = $objAttribute->generate($this->objProduct, $arrOptions);

        if ($blnStripTags)
        {
            $strBuffer = strip_tags($strBuffer,'<br><br /><br/></p></ p>');
            $strBuffer = str_ireplace(array('<br />','<br>','<br/>'),"\n",$strBuffer);
            $strBuffer = str_ireplace(array('</p>','</ p>'),"\n",$strBuffer);
            $strBuffer = preg_replace('/(\r\n|\n)$/','',$strBuffer);
        }

        return $strBuffer;
    }


}