<?php

class LeituraList extends TPage
{
    Public $param;

    public function __construct($param)
    {
        parent::__construct();

        if(!array_key_exists('tipo', $param)){
            $param['tipo'] = 'Dia';
        }
        if(!array_key_exists('primeirodia', $param)){
            $param['primeirodia'] = NULL;
        }
        if(!array_key_exists('ultimodia', $param)){
            $param['ultimodia'] = NULL;
        }

        if($param['primeirodia'] == 'NULL'){
            $param['primeirodia'] = NULL;
            $param['ultimodia'] = NULL;
        }
        $this->param = $param;
        // creates the items form and add a table inside
        $this->form_item = new TForm('form_atendente');
        $this->form_item->class = 'tform';
        $table_item = new TTable;
        $table_item-> width = '100%';
        $this->form_item->add($table_item);

        $this->text_win = '';
        if($this->param['tipo'] == 'Fechado') {
            $this->text_win = 'LEITURA DO DIA - ' . substr($this->param['primeirodia'], 8, 2) . '/' . substr($this->param['primeirodia'], 5, 2) . '/' . substr($this->param['primeirodia'], 0, 4) . ' - ' . substr($this->param['primeirodia'], 11, 2) . ':' . substr($this->param['primeirodia'], 14, 2) . ':' . substr($this->param['primeirodia'], 17, 2);
        }else{
            $this->text_win = 'LEITURA DO DIA';
        }
        $this->button_win = new TButton('win');
        $this->button_win->setAction(new TAction(array($this, 'onWin')), $this->text_win);
        $this->button_win->class = 'btn btn-danger btn-lg btn-block';

// create the datagrid
        $this->datagrid = new TQuickGrid;
        $this->datagrid->style = 'width: 100%';

        // add the columns
        $this->datagrid->addQuickColumn('Máquina','maquina','center', 50, new TAction(array($this, 'onReload')), array('order', 'dia'));
        $this->datagrid->addQuickColumn('Tipo','tipo','center', 100, new TAction(array($this, 'onReload')), array('order', 'maquina'));
        $this->datagrid->addQuickColumn('Entrada Inicial','ini_entra','center', 80, new TAction(array($this, 'onReload')), array('order', 'descricao'));
        $this->datagrid->addQuickColumn('Saída Inicial','ini_sai','center', 80, new TAction(array($this, 'onReload')), array('order', 'descricao'));
        $this->datagrid->addQuickColumn('Entrada Final','fim_entra','center', 80, new TAction(array($this, 'onReload')), array('order', 'descricao'));
        $this->datagrid->addQuickColumn('Saída Final','fim_sai','center', 80, new TAction(array($this, 'onReload')), array('order', 'descricao'));
        $jogou = $this->datagrid->addQuickColumn('Jogou', 'jogou', 'right', 100, new TAction(array($this, 'onReload')), array('order', 'jogou'));
        $jogou->setTransformer(array('Utils', 'formatValueLei'));
        $pagou = $this->datagrid->addQuickColumn('Pagou', 'pagou', 'right', 100, new TAction(array($this, 'onReload')), array('order', 'pagou'));
        $pagou->setTransformer(array('Utils', 'formatValueLei'));
        $azul = $this->datagrid->addQuickColumn('L/P', 'azul', 'right', 100, new TAction(array($this, 'onReload')), array('order', 'azul'));
        $azul->setTransformer(array('Utils', 'formatValueLei'));
        $this->datagrid->addQuickColumn('Retenção', 'retencao', 'center', 30, new TAction(array($this, 'onReload')), array('order', 'azul'));

//        $this->datagrid->setGroupColumn('ilha', '{ilha}');
        // create the datagrid model
        $this->datagrid->createModel();
        $this->onReload();
		
        // creates an action button
        $bt_excel = new TButton('ptinr');
        $bt_excel->setAction(new TAction([$this, 'onGenerate'], ['param'=>0]), 'Exportar Excel');
        $bt_excel->class = 'btn btn-info';

        $act_print = new TAction(array($this, 'onPrint'));
        $act_print->setParameters($this->param);
        $bt_print = new TButton('print');
        $bt_print->setAction($act_print, 'IMPRIME A LEITURA');
        $bt_print->class = 'btn btn-warning btn-lg btn-block';

        // define the form fields
        $this->form_item->setFields(array($bt_print,$bt_excel,$this->button_win));

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
        if($this->param['tipo'] == 'Fechado') {
            $vbox->add($this->button_win)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        }
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        $vbox->add($bt_print)->style = 'width: 100%; text-align: left;';
//        $vbox->add($bt_excel)->style = 'width: 100%; text-align: left;';
        parent::add($vbox);
    }

    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {
            TTransaction::open('unit_database');
            if($this->param['tipo'] == 'Dia'){
                $leituras = leitura::where('fechado', 'IS', NULL)
                    ->orderby('maquina')
                    ->load();
            } elseif($this->param['tipo'] == 'Fechado'){
                $leituras = leitura::where('fechado', '=', $this->param['primeirodia'])
                    ->orderby('maquina')
                    ->load();
            } elseif($this->param['tipo'] == 'Semana'){
                $leituras = leitura::where('fechado', '>=', $this->param['primeirodia'])
                    ->where('fechado', '<=', $this->param['ultimodia'])
                    ->orderby('maquina')
                    ->load();
            }

            $this->datagrid->clear();

            $quebra='0';
            $ent_fim_ilha = 0;
            $ent_ini_ilha = 0;
            $jogou_ilha=0;
            $sai_fim_ilha = 0;
            $sai_ini_ilha = 0;
            $pagou_ilha=0;
            $azul_ilha=0;

            $ent_fim_geral = 0;
            $ent_ini_geral = 0;
            $jogou_geral=0;
            $sai_fim_geral = 0;
            $sai_ini_geral = 0;
            $pagou_geral=0;
            $azul_geral=0;

            if ($leituras)
            {
                foreach ($leituras as $leitura)
                {
                    $machine = new maquina($leitura->maquina);

                    if($quebra == '0'){$quebra = $machine->ilha;}

                    if($quebra != $machine->ilha){
                        $obj = new stdclass();
                        $obj->ilha = $machine->ilha;
                        $obj->maquina = '';
                        $obj->tipo = 'TOTAIS';
                        $obj->fim_entra = $ent_fim_ilha;
                        $obj->ini_entra = $ent_ini_ilha;
                        $obj->jogou = $jogou_ilha;
                        $obj->fim_sai = $sai_fim_ilha;
                        $obj->ini_sai = $sai_ini_ilha;
                        $obj->pagou = $pagou_ilha;
                        $obj->azul = $azul_ilha;
                        if($obj->pagou == 0 AND $obj->jogou == 0){$retencao = '';}
                        elseif(($obj->pagou > $obj->jogou) AND $obj->jogou == 0){$retencao = '';}
                        elseif($obj->pagou == 0){$retencao = '100,00';}
                        else{$retencao = number_format(100-((($obj->fim_sai-$obj->ini_sai) / ($obj->fim_entra-$obj->ini_entra))*100), 2, ',', '.');}
                        $obj->retencao = $retencao;
                        $this->datagrid->addItem($obj);
                        $ent_fim_ilha = 0;
                        $ent_ini_ilha = 0;
                        $jogou_ilha=0;
                        $sai_fim_ilha = 0;
                        $sai_ini_ilha = 0;
                        $pagou_ilha=0;
                        $azul_ilha=0;
                    };

                    // add the object inside the datagrid
                    $obj = new stdclass();
                    $obj->ilha = $machine->ilha;
                    $obj->maquina = $leitura->maquina;
                    $obj->tipo = $machine->tipo;
                    $obj->fim_entra = $leitura->fim_entra;
                    $obj->ini_entra = $leitura->ini_entra;
                    $obj->jogou = ($leitura->fim_entra-$leitura->ini_entra)*$leitura->credito;
                    $obj->fim_sai = $leitura->fim_sai;
                    $obj->ini_sai = $leitura->ini_sai;
                    $obj->pagou = ($leitura->fim_sai-$leitura->ini_sai)*$leitura->credito;
                    $obj->azul = $obj->jogou - $obj->pagou;

                    if($obj->pagou == 0 AND $obj->jogou == 0){$retencao = '';}
                    elseif(($obj->pagou > $obj->jogou) AND $obj->jogou == 0){$retencao = '';}
                    elseif($obj->pagou == 0){$retencao = '100,00';}
                    else{$retencao = number_format(100-((($obj->fim_sai-$obj->ini_sai) / ($obj->fim_entra-$obj->ini_entra))*100), 2, ',', '.');}
                    $obj->retencao = $retencao;
                    $this->datagrid->addItem($obj);

                    $ent_fim_ilha += $leitura->fim_entra;
                    $ent_ini_ilha += $leitura->ini_entra;
                    $jogou_ilha += ($leitura->fim_entra-$leitura->ini_entra)*$leitura->credito;
                    $sai_fim_ilha += $leitura->fim_sai;
                    $sai_ini_ilha += $leitura->ini_sai;
                    $pagou_ilha += ($leitura->fim_sai-$leitura->ini_sai)*$leitura->credito;
                    $azul_ilha += (($leitura->fim_entra-$leitura->ini_entra) - ($leitura->fim_sai-$leitura->ini_sai))*$leitura->credito;

                    $ent_fim_geral += $leitura->fim_entra;
                    $ent_ini_geral += $leitura->ini_entra;
                    $jogou_geral += ($leitura->fim_entra-$leitura->ini_entra)*$leitura->credito;
                    $sai_fim_geral += $leitura->fim_sai;
                    $sai_ini_geral += $leitura->ini_sai;
                    $pagou_geral += ($leitura->fim_sai-$leitura->ini_sai)*$leitura->credito;
                    $azul_geral += (($leitura->fim_entra-$leitura->ini_entra) - ($leitura->fim_sai-$leitura->ini_sai))*$leitura->credito;

                    $quebra = $machine->ilha;
                }
                $obj = new stdclass();
                $obj->ilha = $machine->ilha;
                $obj->maquina = '';
                $obj->tipo = 'TOTAIS';
                $obj->fim_entra = $ent_fim_ilha;
                $obj->ini_entra = $ent_ini_ilha;
                $obj->jogou = $jogou_ilha;
                $obj->fim_sai = $sai_fim_ilha;
                $obj->ini_sai = $sai_ini_ilha;
                $obj->pagou = $pagou_ilha;
                $obj->azul = $azul_ilha;
                if($obj->pagou == 0 AND $obj->jogou == 0){$retencao = '';}
                elseif(($obj->pagou > $obj->jogou) AND $obj->jogou == 0){$retencao = '';}
                elseif($obj->pagou == 0){$retencao = '100,00';}
                else{$retencao = number_format(100-((($obj->fim_sai-$obj->ini_sai) / ($obj->fim_entra-$obj->ini_entra))*100), 2, ',', '.');}
                $obj->retencao = $retencao;
                $this->datagrid->addItem($obj);

                $obj = new stdclass();
                $obj->ilha = $machine->ilha;
                $obj->maquina = '';
                $obj->tipo = 'GERAL';
                $obj->fim_entra = $ent_fim_geral;
                $obj->ini_entra = $ent_ini_geral;
                $obj->jogou = $jogou_geral;
                $obj->fim_sai = $sai_fim_geral;
                $obj->ini_sai = $sai_ini_geral;
                $obj->pagou = $pagou_geral;
                $obj->azul = $azul_geral;
                if($obj->pagou == 0 AND $obj->jogou == 0){$retencao = '';}
                elseif(($obj->pagou > $obj->jogou) AND $obj->jogou == 0){$retencao = '';}
                elseif($obj->pagou == 0){$retencao = '100,00';}
                else{$retencao = number_format((($azul_geral / $jogou_geral)*100), 2, ',', '.');}
                $obj->retencao = $retencao;
                $this->datagrid->addItem($obj);
            }

            // close the transaction
            TTransaction::close();
            $this->loaded = true;
//            $this->labelTotal->setValue('SALDO: R$ '.number_format($this->totalgeral, 2, ',', '.'));
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());

            // undo all pending operations
            TTransaction::rollback();
        }
    }
    function onGenerate($param)
    {
        try
        {

            // open a transaction with database 'samples'
            TTransaction::open('unit_database');

            $relrepo = new TRepository('leitura');
            $criteria = new TCriteria;
            $criteria->setProperty('order', 'maquina');
            $criteria->setProperties('direction','ASC');
            If($param['param'] == 0){
                $criteria->add(new TFilter('fechado', 'IS', NULL));
            } else {
                $criteria->add(new TFilter('fechado', '=', $param['param']));
            }
            $customers = $relrepo->load($criteria);

            if ($customers)
            {
                $widths = array(40, 200, 120, 120, 120, 120);

                $table = new TTableWriterXLS($widths);

                if (!empty($table))
                {
                    // create the document styles
                    $table->addStyle('header', 'Helvetica', '16', 'B', '#ffffff', '#4B5D8E');
                    $table->addStyle('title',  'Helvetica', '10', 'B', '#ffffff', '#617FC3');
                    $table->addStyle('datap',  'Helvetica', '10', '',  '#000000', '#E3E3E3', 'LR');
                    $table->addStyle('datai',  'Helvetica', '10', '',  '#000000', '#ffffff', 'LR');
                    $table->addStyle('footer', 'Helvetica', '10', '',  '#2B2B2B', '#B4CAFF');

                    $table->setHeaderCallback( function($table) {
                        $table->addRow();
                        $table->addCell('Leitura do Dia', 'center', 'header', 5);

                        $table->addRow();
                        $table->addCell('Máquina',        'center', 'title');
                        $table->addCell('Entrada Inicial','center', 'title');
                        $table->addCell('Saida Inicial'  ,'center', 'title');
                        $table->addCell('Entrada Final'  ,'center', 'title');
                        $table->addCell('Saida Final'    ,'center', 'title');
                    });

                    $table->setFooterCallback( function($table) {
                        $table->addRow();
                        $table->addCell(date('Y-m-d h:i:s'), 'center', 'footer', 6);
                    });

                    // controls the background filling
                    $colour= FALSE;

                    // data rows
                    foreach ($customers as $customer)
                    {
                        $style = $colour ? 'datap' : 'datai';
                        $table->addRow();
                        $table->addCell($customer->maquina,  'center', $style);
                        $table->addCell($customer->ini_entra,'center',   $style);
                        $table->addCell($customer->ini_sai,  'center',   $style);
                        $table->addCell($customer->fim_entra,'center', $style);
                        $table->addCell($customer->fim_sai,  'center', $style);

                        $colour = !$colour;
                    }

                    $output = "app/output/leituras.xls";

                    // stores the file
                    if (!file_exists($output) OR is_writable($output))
                    {
                        $table->save($output);
                        parent::openFile($output);
                    }
                    else
                    {
                        throw new Exception(_t('Permission denied') . ': ' . $output);
                    }

                    // shows the success message
                    new TMessage('info', 'Exportação concluida com sucesso');
                }
            }
            else
            {
                new TMessage('error', 'No records found');
            }

            // close the transaction
            TTransaction::close();
            AdiantiCoreApplication::gotoPage('CaixaList'); // reload

        }
        catch (Exception $e) // in case of exception
        {
            new TMessage('error', $e->getMessage());
            TTransaction::rollback();
        }
    }
    public function onPrint($param)
    {
        // converts the HTML template into PDF
        $dompdf = new \Dompdf\Dompdf();
        $paginas = '.'.file_get_contents('app/resources/styles-print.html').$this->button_win->getContents().$this->datagrid->getContents();
        $dompdf->loadHtml($paginas);
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();

        // write and open file
        $saida = 'app/output/leitura'.substr(time(),-4).'pdf';
        file_put_contents($saida, $dompdf->output());

        // open window to show pdf
        $window = TWindow::create('Leitura', 0.8, 0.8);
        $object = new TElement('iframe');
        $object->src  = $saida;
        $object->type  = 'application/pdf';
        $object->style = "width: 100%; height:calc(100% - 10px)";
        $window->add($object);
        $window->show();
    }
    public function onWin()
    {
        return;
    }

}