<?php

use \Adianti\Widget\Container\TNotebook;
use \Adianti\Widget\Container\TTable;
use \Adianti\Wrapper\BootstrapFormBuilder;

class LeituraView extends TPage
{
    protected $form; // form
    protected $detail_list;

    /**
     * Class constructor
     * Creates the page and the registration form
     */
    public function __construct($param)
    {
        parent::__construct();
        parent::setTargetContainer('adianti_right_panel');

        TSession::setValue('size', 226);

        $this->form = new BootstrapFormBuilder('form_Sale_View');
        $ini = parse_ini_file('app/config/application.ini', true);
        $this->form->setFormTitle($ini['general']['title'].' - Leitura');
        $this->form->setColumnClasses(2, ['col-sm-3', 'col-sm-9']);
        $this->form->addHeaderActionLink( _t('Print'), new TAction([$this, 'onPrint'], ['key'=>$param['key'], 'static' => '1']), 'far:file-pdf red');
        $this->form->addHeaderActionLink( _t('Close'), new TAction([$this, 'onClose']), 'fa:times red');

        parent::add($this->form);
    }

    /**
     * Load content
     */
    public function onView($param)
    {
        try
        {
            TTransaction::open('jackpot');

            $movimento = new Movimento($param['key']);

            $label_date = new TLabel('Data:', '#333333', '16px', 'b');
            $label_time = new TLabel('Hora:', '#333333', '16px', 'b');
            $label_ponto_id = new TLabel('Ponto:', '#333333', '16px', 'b');
            $label_operador_id = new TLabel('Oper:', '#333333', '16px', 'b');

            $text_date  = new TTextDisplay(substr($movimento->dia,8,2).'/'.substr($movimento->dia,5,2).'/'.substr($movimento->dia,0,4) , '#333333', '16px', '');
            $text_time  = new TTextDisplay(substr($movimento->dia,11,5), '#333333', '16px', '');
            $text_ponto_id  = new TTextDisplay(Ponto::find($movimento->id_ponto)->nome, '#333333', '16px', '');
            $text_operador_id  = new TTextDisplay(SystemUser::find($movimento->usuario)->name, '#333333', '16px', '');

            $this->form->addFields([$label_date],[$text_date]);
            $this->form->addFields([$label_time],[$text_time]);
            $this->form->addFields([$label_ponto_id],[$text_ponto_id]);
            $this->form->addFields([$label_operador_id],[$text_operador_id]);

            // load customers
            $leituras = Leitura::where('id_movi', '=', $param['key'])
                ->load();

            foreach ($leituras as $leitura){
                $maquina = Maquina::find($leitura->maquina);
                $entrou = $leitura->fim_entra - $leitura->ini_entra;
                If($entrou != 0){$entrou = $entrou * $maquina->credito;}
                $saiu = $leitura->fim_sai - $leitura->ini_sai;
                If($saiu != 0){$saiu = $saiu * $maquina->credito;}
                // creates a notebook
                $notebook = new TNotebook;
                $mesa = new TTable;
                $mesa->width = '100%';
                // adds the notebook page
                $notebook->appendPage($maquina->tipo, $mesa);
                $row=$mesa->addRow();
                $row->addCell(new TLabel('ENTRADA INICIAL:'));
                $row->addCell($leitura->ini_entra);
                $row=$mesa->addRow();
                $row->addCell(new TLabel('ENTRADA FINAL:'));
                $row->addCell($leitura->fim_entra);
                $row=$mesa->addRow();
                $row->addCell(new TLabel('ENTRADAS (+):'));
                $row->addCell(number_format($entrou, 2, ',', '.'));
                $row=$mesa->addRow();
                $row->addCell(new TLabel('SAIDA INICIAL:'));
                $row->addCell($leitura->ini_sai);
                $row=$mesa->addRow();
                $row->addCell(new TLabel('SAIDA FINAL:'));
                $row->addCell($leitura->fim_sai);
                $row=$mesa->addRow();
                $row->addCell(new TLabel('SAIDA (-):'));
                $row->addCell(number_format($saiu, 2, ',', '.'));
                $this->form->addContent([$notebook]);
                $size = TSession::getValue('size');
                TSession::setValue('size', $size + 140);
            }

            $mesa = new TTable;
            $mesa->width = '100%';
            $row=$mesa->addRow();
            $row->addCell(new TLabel('ANT MAQS:'));
            $row->addCell($movimento->deve_anterior);
            $this->form->addContent([$mesa]);
            $size = TSession::getValue('size');
            TSession::setValue('size', $size + 50);

            // creates a notebook
            $notebook = new TNotebook;
            $mesa = new TTable;
            $mesa->width = '100%';
            // adds the notebook page
            $notebook->appendPage('APURADO', $mesa);
            $row=$mesa->addRow();
            $row->addCell(new TLabel('ENTRADAS (+):'));
            $row->addCell(number_format($movimento->entrada, 2, ',', '.'));
            $row=$mesa->addRow();
            $row->addCell(new TLabel('SAIDAS (-):'));
            $row->addCell(number_format($movimento->saida, 2, ',', '.'));
            $row=$mesa->addRow();
            $row->addCell(new TLabel('DESPESAS (-):'));
            $row->addCell(number_format($movimento->despesas, 2, ',', '.'));
            $this->form->addContent([$notebook]);
            $size = TSession::getValue('size');
            TSession::setValue('size', $size + 60);

            // creates a notebook
            $notebook = new TNotebook;
            $mesa = new TTable;
            $mesa->width = '100%';
            // adds the notebook page
            $notebook->appendPage('FINANCEIRO', $mesa);
            $row=$mesa->addRow();
            $row->addCell(new TLabel('ANT CX (+):'));
            $row->addCell(number_format($movimento->cx_anterior, 2, ',', '.'));
            $row=$mesa->addRow();
            $row->addCell(new TLabel('APURADO (+):'));
            $row->addCell(number_format($movimento->entrada - $movimento->saida - $movimento->despesas, 2, ',', '.'));
            $row=$mesa->addRow();
            $row->addCell(new TLabel('COMISSAO (-):'));
            $row->addCell(number_format($movimento->comissao, 2, ',', '.'));
            $row=$mesa->addRow();
            $row->addCell(new TLabel('VLR PAGO (-):'));
            $row->addCell(number_format($movimento->pago, 2, ',', '.'));
            $row=$mesa->addRow();
            $row->addCell(new TLabel('ATU CX (=):'));
            $row->addCell(number_format($movimento->cx_atual, 2, ',', '.'));
            $this->form->addContent([$notebook]);
            $size = TSession::getValue('size');
            TSession::setValue('size', $size + 100);


            $mesa = new TTable;
            $mesa->width = '100%';
            $row=$mesa->addRow();
            $row->addCell(new TLabel('ATU MAQS:'));
            $row->addCell($movimento->deve_atual);
            $this->form->addContent([$mesa]);
            $size = TSession::getValue('size');
            TSession::setValue('size', $size + 50);


            /*
            $this->detail_list = new BootstrapDatagridWrapper( new TDataGrid );
            $this->detail_list->style = 'width:100%';
            $this->detail_list->disableDefaultClick();

            $product       = new TDataGridColumn('product->description',  'Product', 'left');
            $price         = new TDataGridColumn('sale_price',  'Price',    'right');
            $amount        = new TDataGridColumn('amount',  'Amount',    'center');
            $discount      = new TDataGridColumn('discount',  'Discount',    'right');
            $total         = new TDataGridColumn('total',  'Total',    'right');

            $this->detail_list->addColumn( $product );
            $this->detail_list->addColumn( $price );
            $this->detail_list->addColumn( $amount );
            $this->detail_list->addColumn( $discount );
            $this->detail_list->addColumn( $total );

            $format_value = function($value) {
                if (is_numeric($value)) {
                    return 'R$ '.number_format($value, 2, ',', '.');
                }
                return $value;
            };

            $total->setTransformer($format_value);

            // define totals
            $total->setTotalFunction( function($values) {
                return array_sum((array) $values);
            });

            $this->detail_list->createModel();

            $items = SaleItem::where('sale_id', '=', $master_object->id)->load();
            $this->detail_list->addItems($items);

            $panel = new TPanelGroup('Itens', '#f5f5f5');
            $panel->add($this->cards);
            $panel->getBody()->style = 'overflow-x:auto';

            $this->form->addContent([$panel]);
*/
            TTransaction::close();
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    public function onPrint($param)
    {
        try
        {
            $this->onView($param);

            // string with HTML contents
            $html = clone $this->form;
            $contents = file_get_contents('app/resources/styles-leitura.html') . $html->getContents();

            $options = new \Dompdf\Options();
            $options->setChroot(getcwd());

            $customPaper = array(0,0,250,TSession::getValue('size'));

            // converts the HTML template into PDF
            $dompdf = new \Dompdf\Dompdf($options);
            $dompdf->loadHtml($contents);
            $dompdf->setPaper($customPaper, 'portrait');
//            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();

            $file = 'app/output/leitura.pdf';

            // write and open file
            file_put_contents($file, $dompdf->output());

            $window = TWindow::create('Export', 0.8, 0.8);
            $object = new TElement('object');
            $object->data  = $file.'?rndval='.uniqid();
            $object->type  = 'application/pdf';
            $object->style = "width: 100%; height:calc(100% - 10px)";
            $window->add($object);
            $window->show();
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    /**
     * onEdit
     */
    public static function onEdit($param)
    {
        unset($param['static']);
        $param['register_state'] = 'false';
        AdiantiCoreApplication::loadPage('SaleForm', 'onEdit', $param);
    }

    /**
     * Close side panel
     */
    public static function onClose($param)
    {
        TScript::create("Template.closeRightPanel()");
    }
}