<?php

class LeituraList extends TStandardList
{
    protected $form;     // registration form
    protected $datagrid; // listing
    protected $pageNavigation;
    protected $formgrid;
    protected $deleteButton;
    protected $transformCallback;

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

        parent::setDatabase('jackpot');            // defines the database
        parent::setActiveRecord('Leitura');   // defines the active record
        parent::setDefaultOrder('id', 'desc');         // defines the default order
        parent::addFilterField('maquina', '=', 'maquina'); // filterField, operator, formField

        // creates the form
        $this->form = new BootstrapFormBuilder('form_search_Leitura');
        $this->form->setFormTitle('Leituras');

        // create the form fields
        $id = new THidden('id');
        $maquina = new TEntry('maquina');

        // add the fields
        $this->form->addFields( [new TLabel('Nº da Máquina')], [$maquina] );

        $maquina->setSize('20%');

        // keep the form filled during navigation with session data
        $this->form->setData( TSession::getValue('Leitura_filter_maquina') );

        // add the search form actions
        $btn = $this->form->addAction(_t('Find'), new TAction(array($this, 'onSearch')), 'fa:search');
        $btn->class = 'btn btn-sm btn-primary';

        // creates a DataGrid
        $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
        $this->datagrid->datatable = 'true';
        $this->datagrid->style = 'width: 100%';
        $this->datagrid->setHeight(320);


        // creates the datagrid columns
        $column_dia = new TDataGridColumn('dia', 'Data', 'center');
        $column_ponto = new TDataGridColumn('id_ponto', 'Ponto', 'left');
        $column_maquina = new TDataGridColumn('maquina', 'Nº', 'left');
        $column_tipo = new TDataGridColumn('tipo', 'Tipo', 'left');
        $column_ini_e = new TDataGridColumn('ini_entra', 'Entrada Inicial', 'center');
        $column_fim_e = new TDataGridColumn('fim_entra', 'Entrada Final', 'center');
        $column_ini_s = new TDataGridColumn('ini_sai', 'Saída Inicial', 'center');
        $column_fim_s = new TDataGridColumn('fim_sai', 'Saída Final', 'center');
        $column_entra = new TDataGridColumn('entrada', 'Entrou', 'center');
        $column_saida = new TDataGridColumn('saida', 'Pagou', 'center');
        $column_saldo = new TDataGridColumn('saldo', 'Saldo', 'center');
        $column_oper = new TDataGridColumn('operador', 'Operador', 'center');

        // add the columns to the DataGrid
        $this->datagrid->addColumn($column_dia);
        $this->datagrid->addColumn($column_ponto);
        $this->datagrid->addColumn($column_maquina);
        $this->datagrid->addColumn($column_tipo);
        $this->datagrid->addColumn($column_ini_e);
        $this->datagrid->addColumn($column_fim_e);
        $this->datagrid->addColumn($column_ini_s);
        $this->datagrid->addColumn($column_fim_s);
        $this->datagrid->addColumn($column_entra);
        $this->datagrid->addColumn($column_saida);
        $this->datagrid->addColumn($column_saldo);
        $this->datagrid->addColumn($column_oper);

        $column_ponto->setTransformer( function($value, $object, $row) {
            $usuario = new Ponto($value);
            return $usuario->nome;
        });

        $column_oper->setTransformer( function($value, $object, $row) {
            $usuario = new SystemUser($value);
            return $usuario->login;
        });
        $column_entra->setTransformer( function($value, $object, $row) {
            return number_format($value, 2, ',', '.');
        });
        $column_saida->setTransformer( function($value, $object, $row) {
            return number_format($value, 2, ',', '.');
        });

        $column_saldo->setTransformer( function($value, $object, $row) {
            return number_format($value, 2, ',', '.');
        });

        // creates the datagrid column actions
        $order_name = new TAction(array($this, 'onReload'));
        $order_name->setParameter('order', 'maquina');
        $column_maquina->setAction($order_name);

        $order_porc = new TAction(array($this, 'onReload'));
        $order_porc->setParameter('order', 'ponto');
        $column_ponto->setAction($order_porc);

        $order_oper = new TAction(array($this, 'onReload'));
        $order_oper->setParameter('order', 'operador');
        $column_oper->setAction($order_oper);

        // creates two datagrid actions
        $action1 = new TDataGridAction(array('LeituraView', 'onView'));
        $action1->setLabel('Visualizar');
        $action1->setImage('fa:search green fa-fw');
        $action1->setField('id_movi');
        $this->datagrid->addAction($action1,'Visualizar', 'fa:search green fa-fw');

        // create the datagrid model
        $this->datagrid->createModel();

        // create the page navigation
        $this->pageNavigation = new TPageNavigation;
        $this->pageNavigation->enableCounters();
        $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
        $this->pageNavigation->setWidth($this->datagrid->getWidth());

        $panel = new TPanelGroup;
        $panel->add($this->datagrid);
        $panel->addFooter($this->pageNavigation);

        // vertical box container
        $container = new TVBox;
        $container->style = 'width: 100%';
        $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
        $container->add($this->form);
        $container->add($panel);

        parent::add($container);
    }
    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    public function onReload($param = NULL)
    {
        try
        {
            // open a transaction with database
            TTransaction::open($this->database);

            // Array Máquinas
            $a_machine = array();
            $repository = new TRepository('Maquina');
            $criteria = new TCriteria;
            $criteria->setProperty('order', 'id asc');
            $machines = $repository->load($criteria);
            foreach ($machines as $machine) {
                $a_machine[$machine->id] = $machine->tipo;
            }


            // instancia um repositório
            $repository = new TRepository($this->activeRecord);
            $limit = isset($this->limit) ? ( $this->limit > 0 ? $this->limit : NULL) : 20;
            // creates a criteria
            $criteria = isset($this->criteria) ? clone $this->criteria : new TCriteria;
            if((in_array('1', TSession::getValue('usergroupids'))) or
                (in_array('2', TSession::getValue('usergroupids')))
                or (in_array('3', TSession::getValue('usergroupids')))) {
            } else {
                $criteria->add(new TFilter('operador', '=', TSession::getValue('userid')));
            }
            if ($this->order)
            {
                $criteria->setProperty('order',     $this->order);
                $criteria->setProperty('direction', $this->direction);
            }
            $criteria->setProperties($param); // order, offset
            $criteria->setProperty('limit', $limit);

            if ($this->formFilters)
            {
                foreach ($this->formFilters as $filterKey => $filterField)
                {
                    $logic_operator = isset($this->logic_operators[$filterKey]) ? $this->logic_operators[$filterKey] : TExpression::AND_OPERATOR;

                    if (TSession::getValue($this->activeRecord.'_filter_'.$filterField))
                    {
                        // add the filter stored in the session to the criteria
                        $criteria->add(TSession::getValue($this->activeRecord.'_filter_'.$filterField), $logic_operator);
                    }
                }
            }

            // load the objects according to criteria
            $objects = $repository->load($criteria, FALSE);

            if (is_callable($this->transformCallback))
            {
                call_user_func($this->transformCallback, $objects);
            }

            $this->datagrid->clear();
            if ($objects)
            {
                // iterate the collection of active records
                foreach ($objects as $object)
                {
                    $object->entrada  = ($object->fim_entra - $object->ini_entra)*$object->credito;
                    $object->saida    = ($object->fim_sai - $object->ini_sai)*$object->credito;
                    $object->saldo    = $object->entrada - $object->saida;
                    $object->dia      = $this->date2time($object->dia);
                    $object->operador = $object->usuario;
                    if(array_key_exists($object->maquina, $a_machine)){
                        $object->tipo = $a_machine[$object->maquina];
                    } else {$object->tipo = '* EXCLUIDA *';}
                    $this->datagrid->addItem($object);
                }
            }

            // reset the criteria for record count
            $criteria->resetProperties();
            $count= $repository->count($criteria);

            if (isset($this->pageNavigation))
            {
                $this->pageNavigation->setCount($count); // count of records
                $this->pageNavigation->setProperties($param); // order, page
                $this->pageNavigation->setLimit($limit); // limit
            }

            // close the transaction
            TTransaction::close();
            $this->loaded = true;
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());
            // undo all pending operations
            TTransaction::rollback();
        }
    }

    public function date2time($date)
    {
        if ($date)
        {
            // get the date parts
            $mon  = substr($date,5,2);
            $day  = substr($date,8,2);
            $hour = substr($date,11,2);
            $minute = substr($date,14,2);
            return "{$day}/{$mon} - {$hour}:{$minute}";
        }
    }

    public function onPrint($param)
    {
        // converts the HTML template into PDF
        $dompdf = new \Dompdf\Dompdf();
        $paginas = file_get_contents('app/resources/styles-print.html').$this->frame->getContents().$this->datagrid->getContents();
        $dompdf->loadHtml($paginas);
//        $dompdf->setPaper('A4', 'landscape');
        $dompdf->setPaper(array(0,0,595,1200),'landscape');
        $dompdf->render();

        // write and open file
        file_put_contents('app/output/document.pdf', $dompdf->output());

        // open window to show pdf
        $window = TWindow::create('Caixa do Dia', 0.8, 0.8);
        $object = new TElement('iframe');
        $object->src  = 'app/output/document.pdf';
        $object->type  = 'application/pdf';
        $object->style = "width: 100%; height:calc(100% - 10px)";
        $window->add($object);
        $window->show();
    }

}
