<?php

use Adianti\Control\TAction;
use Adianti\Control\TPage;
use Adianti\Core\AdiantiCoreTranslator;
use Adianti\Database\TCriteria;
use Adianti\Database\TFilter;
use Adianti\Database\TRepository;
use Adianti\Database\TTransaction;
use Adianti\Registry\TSession;
use Adianti\Widget\Container\TVBox;
use Adianti\Widget\Datagrid\TDataGridAction;
use Adianti\Widget\Dialog\TMessage;
use Adianti\Widget\Dialog\TQuestion;
use Adianti\Widget\Form\TEntry;
use Adianti\Widget\Form\THidden;
use Adianti\Widget\Wrapper\TQuickForm;
use Adianti\Widget\Wrapper\TQuickGrid;

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

    /**
     * Page constructor
     */
    public function __construct()
    {
        parent::__construct();

        parent::setDatabase('jackpot');            // defines the database
        parent::setActiveRecord('Ponto');   // defines the active record
        parent::setDefaultOrder('id', 'asc');         // defines the default order
        parent::addFilterField('nome', 'like', 'nome'); // filterField, operator, formField
        parent::addFilterField('operador', 'like', 'operador'); // filterField, operator, formField

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


        // create the form fields
        $id = new THidden('id');
        $name = new TEntry('nome');
        $operador = new TDBCombo('operador','permission','SystemUser','id','name');

        // add the fields
        $this->form->addFields( [new TLabel('Nome')], [$name] );
        $this->form->addFields( [new TLabel('Operador')], [$operador] );

        $name->setSize('30%');
        $operador->setSize('30%');

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

        // 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';
        $this->form->addAction(_t('New'),  new TAction(array('PontoForm', 'onEdit')), 'bs:plus-sign green');

        // 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_id = new TDataGridColumn('id', 'Id', 'center');
        $column_name = new TDataGridColumn('nome', _t('Name'), 'left');
        $column_porc = new TDataGridColumn('porc_ponto', 'Porcentagem', 'center', 30);
        $column_oper = new TDataGridColumn('operador', 'Operador', 'center');
        $column_caixa = new TDataGridColumn('caixa', 'Caixa', 'center');
        $column_deve = new TDataGridColumn('deve', 'Deve', 'center');
        $column_cadastro = new TDataGridColumn('cadastro', 'Cadastro', 'center');
        $column_last = new TDataGridColumn('last_visita', 'Última Leitura', 'center');

        // add the columns to the DataGrid
        $this->datagrid->addColumn($column_id);
        $this->datagrid->addColumn($column_name);
        $this->datagrid->addColumn($column_porc);
        $this->datagrid->addColumn($column_oper);
        $this->datagrid->addColumn($column_caixa);
        $this->datagrid->addColumn($column_deve);
        $this->datagrid->addColumn($column_cadastro);
        $this->datagrid->addColumn($column_last);

        $column_oper->setTransformer( function($value, $object, $row) {
            $usuario = new SystemUser($value);
            return $usuario->login;
        });
        $column_cadastro->setTransformer( function($value, $object, $row) {
            return substr($value,8,2).'/'.substr($value,5,2).'/'.substr($value,0,4).' - '.substr($value,11,5);
        });
        $column_last->setTransformer( function($value, $object, $row) {
            return substr($value,8,2).'/'.substr($value,5,2).'/'.substr($value,0,4).' - '.substr($value,11,5);
        });
        $column_caixa->setTransformer( function($value, $object, $row) {
            return number_format($value, 2, ',', '.');
        });
        $column_deve->setTransformer( function($value, $object, $row) {
            return number_format($value, 2, ',', '.');
        });

        // creates the datagrid column actions
        $order_id = new TAction(array($this, 'onReload'));
        $order_id->setParameter('order', 'id');
        $column_id->setAction($order_id);

        $order_name = new TAction(array($this, 'onReload'));
        $order_name->setParameter('order', 'nome');
        $column_name->setAction($order_name);

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

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

        // create EDIT action
        $action_edit = new TDataGridAction(array('PontoForm', 'onEdit'));
        $action_edit->setButtonClass('btn btn-default');
        $action_edit->setLabel(_t('Edit'));
        $action_edit->setImage('far:edit fa-fw blue');
        $action_edit->setField('id');
        $this->datagrid->addAction($action_edit);

        if((in_array('1', TSession::getValue('usergroupids'))) or
            (in_array('2', TSession::getValue('usergroupids')))) {
            // create DELETE action
            $action_del = new TDataGridAction(array($this, 'onDelete'));
            $action_del->setButtonClass('btn btn-default');
            $action_del->setLabel(_t('Delete'));
            $action_del->setImage('fa:trash red');
            $action_del->setField('id');
            $this->datagrid->addAction($action_del);
        }

        // 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: 90%';
        $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
        $container->add($this->form);
        $container->add($panel);

        parent::add($container);
    }

    /**
     * Delete a record
     */
    public function Delete($param)
    {
        try
        {
            // get the parameter $key
            $key=$param['key'];
            // open a transaction with database
            TTransaction::open($this->database);

            $class = $this->activeRecord;

            // instantiates object
            $object = new $class($key, FALSE);

            // deletes the object from the database
            $object->delete();

            // close the transaction
            TTransaction::close();

            // reload the listing
            $this->onReload( $param );
            // shows the success message
            new TMessage('info', AdiantiCoreTranslator::translate('Record deleted'));
        }
        catch (Exception $e) // in case of exception
        {
            if($e->getCode() == 23000){
                new TMessage('error', "Ponto possue máquinas cadastradas. Exclua as máquinas primeiro.");
            } else {
                // shows the exception error message
                new TMessage('error', $e->getMessage());
            }
            // undo all pending operations
            TTransaction::rollback();
        }
    }

}
