<?php

use Adianti\Control\TAction;
use Adianti\Control\TPage;
use Adianti\Database\TCriteria;
use Adianti\Database\TFilter;
use Adianti\Database\TRepository;
use Adianti\Database\TTransaction;
use Adianti\Registry\TSession;
use Adianti\Validator\TMaxValueValidator;
use Adianti\Validator\TMinValueValidator;
use Adianti\Validator\TRequiredValidator;
use Adianti\Widget\Container\TTable;
use Adianti\Widget\Container\TVBox;
use Adianti\Widget\Datagrid\TDataGridAction;
use Adianti\Widget\Dialog\TMessage;
use Adianti\Widget\Form\TButton;
use Adianti\Widget\Form\TEntry;
use Adianti\Widget\Form\TForm;
use Adianti\Widget\Form\TLabel;
use Adianti\Widget\Form\TRadioGroup;
use Adianti\Widget\Util\TXMLBreadCrumb;
use Adianti\Widget\Wrapper\TDBCombo;
use Adianti\Widget\Wrapper\TQuickGrid;

class PassaCaixaForm extends TPage
{
    public function __construct()
    {
        parent::__construct();
        new TSession;

        $ini  = AdiantiApplicationConfig::get();

        $this->labelTotal = new TLabel(' ');
        $this->labelTotal->setFontSize(17);
        $this->labelTotal->setFontFace('Trebuchet MS');
        $this->labelTotal->setFontColor('white');

        $this->labelMarca = new TLabel(' ');
        $this->labelMarca->setFontSize(15);
        $this->labelMarca->setFontFace('Trebuchet MS');
        $this->labelMarca->setFontColor('white');

        $this->labelPaga = new TLabel(' ');
        $this->labelPaga->setFontSize(15);
        $this->labelPaga->setFontFace('Trebuchet MS');
        $this->labelPaga->setFontColor('white');

        // 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);

        /*
                $criteria = new TCriteria();
                $criteria->add(new TFilter('saida', 'IS', NULL));         // create the form fields
                $cliente_nome = new TDBCombo('cliente_nome','bingo','visita','id_cliente','name','name', $criteria);
                $cliente_nome->setChangeAction(new TAction(array($this, 'onExitCliente')));
        */

        $maquina_id   = new TEntry('maquina_id');
        $validacao    = new TEntry('descricao');
        $valor        = new TEntry('valor');
        $radio        = new TRadioGroup('radio');

        $radio->setLayout('horizontal');
        $radio->setValue(1);
        $items = array();
        $items['1'] ='Pagamento';
        $items['2'] ='Marcação Débito';
        $items['3'] ='Marcação Crédito';
        $radio->addItems($items);

        // add validators
        $maquina_id->addValidation('Máquina', new TRequiredValidator);
        $maquina_id->addValidation('Máquina', new TMinValueValidator, array(1)); // cannot be less the 1
        $maquina_id->addValidation('Máquina', new TMaxValueValidator, array($ini['general']['equips'])); // cannot be greater the 10

        $valor->addValidation('Valor', new TRequiredValidator);
//        $cliente_nome->addValidation('Cliente', new TRequiredValidator);

        // define some attributes
//        $cliente_nome->style = 'font-size: 17pt; height: 30px';
        $maquina_id->style = 'font-size: 17pt; height: 30px; autocomplete="off";';
        $validacao->style = 'font-size: 17pt; height: 30px; autocomplete="off";';
        $valor->style = 'font-size: 17pt; height: 30px; autocomplete="off";';

        // define some properties
        $maquina_id->setSize(100);
        $maquina_id->setInputType('tel');
        $validacao->setInputType('tel');
        $valor->setInputType('tel');
        $valor->setSize(200);
        /*        $cliente_nome->setSize(300);

                // Bloqueio de Campos
                $maquina_id->setEditable(FALSE);
                $validacao->setEditable(FALSE);
                $valor->setEditable(FALSE);
        */
        // add a row for the form title
        $row  = $table_item->addRow();
        $row->class = 'tformtitle'; // CSS class
        $row->addCell( new TLabel('PASSA CAIXA'))->style = 'text-align: center; width:100%;';

        // create the field labels
        $lab_maq = new TLabel('MÁQUINA', 'red', 17,'b');
        $lab_val = new TLabel('VALOR', 'red', 17,'b');
        $lab_des = new TLabel('VALIDAÇÃO', 'red', 17,'b');
        $lab_cli = new TLabel('CLIENTE', 'red', 17,'b');

        // creates the action button
        $button1 = new TButton('add');
        $button1->setAction(new TAction(array($this, 'onSave')), 'SALVAR');
        $button1->class = 'btn btn-success btn-lg btn-block';

        $button2 = new TButton('back');
        $button2->setAction(new TAction(array('CaixaDiaList', 'onReload')), 'VOLTAR');
        $button2->class = 'btn btn-danger btn-lg btn-block';

        // add the form fields
        $table_item->addRowSet($lab_maq)->style = 'text-align: center;';
        $table_item->addRowSet($maquina_id)->style = 'text-align: center;';
        $table_item->addRowSet($lab_des)->style = 'text-align: center;';
        $table_item->addRowSet($validacao)->style = 'text-align: center;';
        $table_item->addRowSet($lab_val)->style = 'text-align: center;';
        $table_item->addRowSet($valor)->style = 'text-align: center;';
//        $table_item->addRowSet($radio);
        $table_item->addRowSet('');
        if((in_array('1', TSession::getValue('usergroupids'))) or
            (in_array('2', TSession::getValue('usergroupids'))) or
            (in_array('3', TSession::getValue('usergroupids'))) or
            (in_array('4', TSession::getValue('usergroupids')))) {
            $table_item->addRowSet(array($button1, $button2))->style = 'text-align: center;';
        }else{
            $table_item->addRowSet(array($button1))->style = 'text-align: center;';
        }

        // define the form fields
//        $this->form_item->setFields(array($cliente_nome, $maquina_id, $validacao, $valor, $button1, $radio));
        $this->form_item->setFields(array($maquina_id, $validacao, $valor, $button1, $button2, $radio));

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

        // add the columns
//        $this->datagrid->addQuickColumn('Fecha','fechado','center', 150, new TAction(array($this, 'onReload')), array('order', 'dia'));
        $this->datagrid->addQuickColumn('Data','dia','center', 150, new TAction(array($this, 'onReload')), array('order', 'dia'));
        $this->datagrid->addQuickColumn('Máquina','maquina','center', 10, new TAction(array($this, 'onReload')), array('order', 'maquina'));
        $this->datagrid->addQuickColumn('Descrição','descricao','left', 150, new TAction(array($this, 'onReload')), array('order', 'descricao'));
        $valor = $this->datagrid->addQuickColumn('Valor', 'valor', 'right', 150, new TAction(array($this, 'onReload')), array('order', 'valor'));

        if((in_array('1', TSession::getValue('usergroupids'))) or
            (in_array('2', TSession::getValue('usergroupids')))
            or (in_array('3', TSession::getValue('usergroupids')))
            or (in_array('4', TSession::getValue('usergroupids')))) {
            $this->datagrid->addQuickColumn('Usuário','usuario','center', 150, new TAction(array($this, 'onReload')), array('order', 'usuario'));
        } else {
        }

        $valor->setTransformer(array($this, 'formatsaldo'));

        // creates two datagrid actions
        $action1 = new TDataGridAction(array($this, 'onDelete'));
        $action1->setLabel('Deleta');
        $action1->setImage('fa:trash red');
        $action1->setField('id');
        $action1->setDisplayCondition( array($this, 'displayColumn') );

        // add the actions
        $this->datagrid->addQuickAction('Deleta', $action1, 'id', 'fa:trash red');
//        $this->datagrid->addQuickAction('Deleta', new TDataGridAction(array($this, 'onDelete')), 'id', 'fa:trash red');

        $this->datagrid->setGroupColumn('maquina', '<b>Máquina</b>: <strong>{maquina}</strong>');
        // create the datagrid model
        $this->datagrid->createModel();
        $this->onReload();

        $btsaldo = new TButton('saldo');
        $btsaldo->setLabel($this->labelTotal);
        $btsaldo->class = 'btn btn-danger btn-lg';

        $btmarca = new TButton('marca');
        $btmarca->setLabel($this->labelMarca);
        $btmarca->class = 'btn btn-primary btn-sm';

        $btpaga = new TButton('marca');
        $btpaga->setLabel($this->labelPaga);
        $btpaga->class = 'btn btn-warning btn-sm';

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
        $vbox->add($this->form_item);
//        $vbox->add($btmarca);
        $vbox->add($btpaga);
//        $vbox->add($btsaldo);
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;';
        parent::add($vbox);

//        TScript::create('$("input[name=\'maquina_id\']").focus();');

    }
    /**
     * Saves the cart
     */
    public function onSave()
    {
        try
        {
            $this->form_item->validate(); // validate form data
            $data = $this->form_item->getData();
            TTransaction::open('bingo');

            // Testa Leitura Feita
            $repository = new TRepository('leitura');
            $criteria = new TCriteria;
            $criteria->add(new TFilter('maquina', '=', $data->maquina_id));
            $criteria->add(new TFilter('ok', '=', 0));
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $consulta = $repository->load($criteria);
            if($consulta){throw new Exception('Leitura da Máquina ainda não realizada');}


            //            $machine = new maquina($data->maquina_id);
//            $tipo_leitura = $machine->leitura;
//            $grava_centavo = $machine->credito == 1.00 ? FALSE : TRUE;

            $registro = new Movimento;

            // Preenche Validação em branco
            if($data->descricao == NULL){
                $registro->descricao = time();
            }else{
                $registro->descricao = $data->descricao;
            };

            // Consulta Validação Duplicada
            $repository = new TRepository('movimento');
            $criteria =new TCriteria();
            $criteria->add(new TFilter('maquina', "=", $data->maquina_id));
            $criteria->add(new TFilter('descricao', "=", $registro->descricao));
            $criteria->add(new TFilter('fechado', "IS", NULL));
            $count = $repository->count($criteria);
            if($count > 0){throw new Exception('Validação Duplicada');};

/*            if($tipo_leitura != 0){
                $repository = new TRepository('leitura');
                $criteria =new TCriteria();
                $criteria->add(new TFilter('maquina', "=", $data->maquina_id));
                $criteria->add(new TFilter('fechado', "IS", NULL));
                $records = $repository->load($criteria);
                foreach ($records as $record){
                    $ultimo = $record->valida;
                }
                if($tipo_leitura == 1){
                    $next = $ultimo + ($data->valor * 4);
                }else{
                    $next = $ultimo + 1;
                }
                if($registro->descricao != $next){throw new Exception('Validação Incorreta');};
                $leitura = new leitura($record->id);
                $leitura->valida = $registro->descricao;
                if($tipo_leitura == 1) {
                    $leitura->fim_sai = $registro->descricao;
                }
                $leitura->store();
            }
*/
            // Importa campos e salva
//            if($data->radio == 1){
            $registro->maquina = $data->maquina_id;
            /*            }else{
                            $registro->maquina = (int)$data->cliente_nome + 500;
                            $registro->descricao = 'MARCAÇÃO '.$consulta->nome;
                        };
                        if($data->radio == 3){
                            $registro->descricao = 'MARCAÇÃO PAGA '.$consulta->nome;
                        };
            */
            $registro->dia = date('Y-m-d G:i:s');
            $registro->usuario = TSession::getValue('userid');

/*            // Grava Centavo?
            If(!$grava_centavo){
                $data->valor = intval($data->valor);
            }
*/
            $registro->valor = ($data->valor) * -1;
//            }
//            $registro->visita = $data->cliente_nome;
            $registro->visita = 999;
            $registro->fechado = '2019-01-01 00:00:00';
            $registro->store();
            $this->form_item->clear(); // clear form
            new TMessage('info', 'Registro Salvo com Sucesso');
            TTransaction::close();
            $this->onReload();
        }catch (Exception $e){
            new TMessage('error', $e->getMessage());

            // undo all pending operations
            TTransaction::rollback();
        }
    }

    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {

            $this->totalgeral = 0;
            $this->totalMarca = 0;
            $this->totalCambio = 0;
            $this->totalPaga = 0;
            // open a transaction with database 'samples'
            TTransaction::open('bingo');

            // creates a repository for Customer
            $repository = new TRepository('movimento');

            // creates a criteria
            $criteria = new TCriteria;
            $newparam = $param; // define new parameters
            // default order
            if (empty($newparam['order']))
            {
                $newparam['order'] = 'dia';
                $newparam['direction'] = 'desc';
            }

            $criteria->setProperties($newparam); // order, offset

            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('usuario', '=', TSession::getValue('userid')));
            }
            $criteria->add(new TFilter('fechado', '=', '2019-01-01 00:00:00'));
            $criteria->add(new TFilter('maquina', '<', 100));

            // load the objects according to criteria
            $customers = $repository->load($criteria);
            $this->datagrid->clear();

            if ($customers)
            {
                foreach ($customers as $customer)
                {
                    $pode = new DateTime($customer->dia);
                    $pode->modify('+5 minutes');
                    $customer->fechado = $pode->format('Y-m-d H:i:s');

                    $customer->dia = substr($customer->dia,8,2).'/'.substr($customer->dia,5,2).'/'.substr($customer->dia,0,4).' - '.substr($customer->dia,11,2).':'.substr($customer->dia,14,2).':'.substr($customer->dia,17,2);
                    $usuario = new SystemUser($customer->usuario);
                    $customer->usuario = $usuario->login;

                    // add the object inside the datagrid
                    $this->datagrid->addItem($customer);
                    $this->totalgeral += $customer->valor;
                    if($customer->maquina > 500){$this->totalMarca += $customer->valor * -1;};
                    if($customer->maquina == 0){$this->totalCambio += $customer->valor;}else{$this->totalPaga += $customer->valor;};
                }
            }

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

            // close the transaction
            TTransaction::close();
            $this->loaded = true;
            $this->labelTotal->setValue('SALDO: R$ '.number_format($this->totalgeral, 2, ',', '.'));
            $this->labelMarca->setValue('CÂMBIO: R$ '.number_format($this->totalCambio, 2, ',', '.'));
            $this->labelPaga->setValue('PAGAMENTOS: R$ '.number_format($this->totalPaga, 2, ',', '.'));

            /*            If($this->totalgeral < 1){
                            new TMessage('error', 'Atendente sem caixa para trabalhar.');
                            // reload the listing
                            TApplication::loadPage('CommonPage');
                        } */


        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());

            // undo all pending operations
            TTransaction::rollback();
        }
    }

    /**
     * method onDelete()
     * executed whenever the user clicks at the delete button
     * Ask if the user really wants to delete the record
     * @param $param
     */
    public function onDelete($param)
    {
        // define the delete action
        $action = new TAction(array($this, 'Delete'));
        $action->setParameters($param); // pass the key parameter ahead

        // shows a dialog to the user
        new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
    }

    /**
     * method Delete()
     * Delete a record
     * @param $param
     */
    public function Delete($param)
    {
        try
        {
            // get the parameter $key
            $key=$param['key'];

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

            // instantiates object
            $object = new movimento($key);

            if($object->maquina == 0){
                throw new Exception('Transferências não podem ser excluídas');
            };

            if((in_array('1', TSession::getValue('usergroupids'))) or
                (in_array('2', TSession::getValue('usergroupids')))
                or (in_array('3', TSession::getValue('usergroupids')))
                or (in_array('4', TSession::getValue('usergroupids')))) {
            } else {
                $pode = new DateTime($object->dia);
                $pode->modify('+5 minutes');
                $hora = new DateTime();
                if($hora > $pode){
                    throw new Exception('Horário excedido para exclusão');
                };
            }

            // 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
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());
            // undo all pending operations
            TTransaction::rollback();
        }
    }
    /**
     * Format saldo
     */
    public function formatSaldo($stock, $object, $row)
    {
        $number = number_format($stock, 2, ',', '.');
        if ($stock < 0)
        {
            return "<span style='color:red'>$number</span>";
        }
        else
        {
            $row->style = "background: #FFF9A7";
            return "<span style='color:blue'>$number</span>";
        }
    }

    /**
     * Exit action for the field product
     * Fill some form fields (sale_price, amount, discount, total)
     */
    public static function onExitCliente($param)
    {
        try
        {
            TEntry::enableField('form_atendente', 'maquina_id');
            TEntry::enableField('form_atendente', 'descricao');
            TEntry::enableField('form_atendente', 'valor');

        }
        catch (Exception $e)
        {
            // does nothing
        }
    }

    /**
     * Define when the action can be displayed
     */
    public function displayColumn( $object )
    {
        $hora = new DateTime();

//        echo var_dump($hora->format('Y-m-d H:i:s')).'<B>'.var_dump($object->fechado);exit;
        if((in_array('1', TSession::getValue('usergroupids')))){
            return TRUE;
        }
        if($hora->format('Y-m-d H:i:s') < $object->fechado and $object->maquina <> 0){
            return TRUE;
        };
        return FALSE;
    }

}