<?php

use Adianti\Core\AdiantiCoreApplication;
use Adianti\Core\AdiantiCoreTranslator;
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\Database\TExpression;
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\Container\THBox;
use Adianti\Widget\Datagrid\TDataGridAction;
use Adianti\Widget\Dialog\TMessage;
use Adianti\Widget\Dialog\TQuestion;
use Adianti\Widget\Form\TButton;
use Adianti\Widget\Form\TEntry;
use Adianti\Widget\Form\THidden;
use Adianti\Widget\Form\TForm;
use Adianti\Widget\Form\TLabel;
use Adianti\Widget\Wrapper\TQuickGrid;
use Adianti\Widget\Dialog\TToast;

class AtendenteForm extends TPage
{
    Public $registro;

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

        TTransaction::open('unit_database');
        $equips = config::getConfig('equips');
        $atecredval = config::getConfig('AteCredVal');
        TTransaction::close();

        // creates the items form and add a table inside
        $this->form = new TForm('form_atendente');
        $this->form->class = 'tform';
        $table_item = new TTable;
        $table_item-> width = '100%';
        $this->form->add($table_item);

        $maquina   = new TEntry('maquina');
        $tipo      = new TEntry('tipo');
        $validacao = new TEntry('descricao');
        $valor     = new TEntry('valor');
        $creditos  = new TEntry('creditos');
        $fechado   = new THidden('fechado');
        $visita    = new THidden('visita');

        $maquina->autocomplete = 'off';
        $validacao->autocomplete = 'off';
        $creditos->autocomplete = 'off';
        $valor->autocomplete = 'off';

        $fechado->setValue(NULL);
        $visita->setValue(999);

        $tipo->setEditable(FALSE);
        $maquina->setExitAction(new TAction(array($this, 'onExitMaquina')));
        $creditos->setExitAction(new TAction(array($this, 'onExitCredito')));

        // add validators
        $maquina->addValidation('Máquina', new TRequiredValidator);
        $maquina->addValidation('Máquina', new TMinValueValidator, array(1)); // cannot be less the 1
        $maquina->addValidation('Máquina', new TMaxValueValidator, array($equips)); // cannot be greater the 10
        if($atecredval){
            $creditos->addValidation('Valor', new TRequiredValidator);
            $valor->setEditable(FALSE);
        } else {
            $creditos->setEditable(FALSE);
            $valor->addValidation('Valor', new TRequiredValidator);
        }

        // define some attributes
        $maquina->style = 'font-size: 17pt; height: 30px; autocomplete="off"; text-align: center;';
        $validacao->style = 'font-size: 17pt; height: 30px; autocomplete="off"; text-align: center;';
        $creditos->style = 'font-size: 17pt; height: 30px; autocomplete="off"; text-align: center;';
        $valor->style = 'font-size: 17pt; height: 30px; autocomplete="off"; text-align: center;';
        $tipo->style = 'font-size: 12pt; height: 20px; autocomplete="off"; text-align: center; background-color: #87CEFF;';

        // define some properties
        $maquina->setSize(100);
        $maquina->setInputType('tel');
        $validacao->setInputType('tel');

//        $valor->setNumericMask(2,',','',NULL,true);
       $aparelho = strpos($_SERVER['HTTP_USER_AGENT'],'Android');
   
        If($aparelho){
            $valor->setInputType('tel');
        } else {
            $valor->setInputType('number step=0.01');
            $valor->setInputMode('decimal');
        }
        $valor->setSize(200);

        // add a row for the form title
        $row  = $table_item->addRow();
        $row->class = 'tformtitle'; // CSS class
        $row->addCell( new TLabel('PAGAMENTO DE MÁQUINAS'))->style = 'text-align: center; width:100%;';

        // create the field labels
        $lab_maq = new TLabel('MÁQUINA');
        $lab_val = new TLabel('VALOR');
        $lab_des = new TLabel('VALIDAÇÃO');
        $lab_crd = new TLabel('CRÉDITOS');
        $lab_cli = new TLabel('CLIENTE');
        $lab_cli->setFontSize(17);
        $lab_maq->setFontSize(17);
        $lab_des->setFontSize(17);
        $lab_val->setFontSize(17);
        $lab_crd->setFontSize(17);
        $lab_cli->setFontFace('Trebuchet MS');
        $lab_maq->setFontFace('Trebuchet MS');
        $lab_des->setFontFace('Trebuchet MS');
        $lab_val->setFontFace('Trebuchet MS');
        $lab_crd->setFontFace('Trebuchet MS');

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

        // add the form fields
        $table_item->addRowSet($lab_maq)->style = 'text-align: center;';
        $table_item->addRowSet($maquina)->style = 'text-align: center;';
        $table_item->addRowSet($tipo)->style = 'text-align: center;';
        $table_item->addRowSet($lab_des)->style = 'text-align: center;';
        $table_item->addRowSet($validacao)->style = 'text-align: center;';
        if($atecredval) {
            $table_item->addRowSet($lab_crd)->style = 'text-align: center;';
            $table_item->addRowSet($creditos)->style = 'text-align: center;';
        }
        $table_item->addRowSet($lab_val)->style = 'text-align: center;';
        $table_item->addRowSet($valor)->style = 'text-align: center;';
        $table_item->addRowSet('');
        $table_item->addRowSet(array($button1))->style = 'text-align: center;';

        // define the form fields
        $this->form->setFields(array($maquina, $tipo, $validacao, $creditos, $valor, $fechado, $visita, $button1));

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

        // add the columns
        $this->datagrid->addQuickColumn('Data','dia','center', 150, new TAction(array($this, 'onReload')), array('order', 'dia'));
        $maquina = $this->datagrid->addQuickColumn('Máquina','maquina','center', 10, new TAction(array($this, 'onReload')), array('order', 'maquina,dia'));
        $validacao = $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(Utils::isCoordenador()) {
            $this->datagrid->addQuickColumn('Usuário','usuario','center', 150, new TAction(array($this, 'onReload')), array('order', 'usuario'));
        }

        $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') );

        $action2 = new TDataGridAction(array($this, 'onPassaCaixa'));
        $action2->setLabel('Passa Caixa');
        $action2->setImage('fas:exchange-alt fa-fw blue');
        $action2->setField('id');
        $action2->setDisplayCondition(array($this, 'displayPassa'));

        $action3 = new TDataGridAction(array($this, 'onEdit'));
        $action3->setField('id');
        if(Utils::isGerente()) {
            $valor->setEditAction($action3);
        }

        $action4 = new TDataGridAction(array($this, 'onEdit'));
        $action4->setField('id');
        if(Utils::isGerente()) {
            $validacao->setEditAction($action4);
        }

        $action5 = new TDataGridAction(array($this, 'onEdit'));
        $action5->setField('id');
        if(Utils::isGerente()) {
            $maquina->setEditAction($action5);
        }

        // add the actions
        $this->datagrid->addQuickAction('Deleta', $action1, 'id', 'fa:trash red');
        if(Utils::isCoordenador()) {
            $this->datagrid->addQuickAction('Passa Caixa', $action2, 'id', 'fas:exchange-alt fa-fw blue');
        }

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

        $this->datagrid->disableDefaultClick();

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

        $this->hbox = new THBox;

        $this->onReload();

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
        $vbox->add($this->form);
        $vbox->add($this->hbox);
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        parent::add($vbox);

    }

    public function onValida()
    {
        try
        {

            $Salvar = 1;
            $this->form->validate(); // validate form data
            $data = $this->form->getData();

            // Testa Validação
            if (strpos($data->descricao,'.') > 0 or strpos($data->descricao,',') > 0)
            {
                echo "<embed src='app/images/notificacao.mp3' width='0' height='0'>";
                throw new Exception('Campo Validação tem que ser numérico');
            }
            // Preenche Validação em branco
            if($data->descricao == NULL){
                $data->descricao = time();
            }else{
                $data->descricao = intval($data->descricao);
            };

            TTransaction::open('unit_database');
            $machine = new maquina($data->maquina);
            $tipo_leitura = $machine->leitura;
            $valor_cred = $machine->credito;

            if(!$data->valor){
                $data->valor = $data->creditos * $valor_cred;
            }
            $data->valor = str_replace(',', '.', $data->valor);

            // Valida Limite Pagamento
            if($data->valor > config::getConfig('LimitePagamento')){throw new Exception('Valor Fora do Padrão');}


            // Consulta Validação Duplicada
            $repository = new TRepository('movimento');
            $criteria =new TCriteria();
            $criteria->add(new TFilter('maquina', "=", $data->maquina));
            $criteria->add(new TFilter('descricao', "=", $data->descricao));

            $criteria2 = new TCriteria;
            $criteria2->add(new TFilter('fechado', 'IS', NULL));
            $criteria2->add(new TFilter('fechado', '=', '2019-01-01 00:00:00'), TExpression::OR_OPERATOR);
            $criteria->add($criteria2);

            $count = $repository->count($criteria);
            if($count > 0){
                echo "<embed src='app/images/notificacao.mp3'width='0' height='0'>";
                throw new Exception('Validação Duplicada');
            }
            $data->visita = 999;
            $data->fechado = NULL;

            // Testa Leitura Feita
            $repository = new TRepository('leitura');
            $criteria = new TCriteria;
            $criteria->add(new TFilter('maquina', '=', $data->maquina));
            $criteria->add(new TFilter('ok', '=', 1));
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $consulta = $repository->load($criteria);
            if ($consulta) {
                if( config::getConfig('passacaixa')) {
                    $data->fechado = '2019-01-01 00:00:00';
                }
            }
            TTransaction::close();
            TSession::setValue('dados', $data);
            if($tipo_leitura != 0){
                TTransaction::open('unit_database');
                $ultimo = '';
                $repository = new TRepository('movimento');
                $criteria =new TCriteria();
                $criteria->add(new TFilter('maquina', "=", $data->maquina));
                $criteria->setProperty('order' , 'id');
                $records = $repository->load($criteria);
                TTransaction::close();

                if ($records) {
                    foreach ($records as $record) {
                        $ultimo = $record->descricao;
                    }
                    if ($tipo_leitura == 1) {
                        $next = $ultimo + 1;
                    } elseif ($tipo_leitura == 2) {
                        $next = $ultimo + ($data->valor * 4);
                    } else {
                        $next = $ultimo + ($data->valor * 100);
                    }
                    if ($data->descricao != $next) {
                        $Salvar = 0;
                        $action1 = new TAction(array($this, 'onSave'));
                        echo "<embed src='app/images/notificacao.mp3'width='0' height='0'>";
                        new TQuestion('Máquina ' . $data->maquina . ' ou Validação ' . $data->descricao . ' parece estar incorreto. Validação prevista seria ' . $next . ' Confirma pagamento ?', $action1);
                    }
                }
            }
            if($Salvar){
                $this->onSave();
            }
        } catch (Exception $e){
            new TMessage('error', $e->getMessage());
        }
    }

    public function onSave()
    {
        try
        {
            if( TSession::getValue('dados')){
                $param = TSession::getValue('dados');
                TTransaction::open('unit_database');
                $registro = new movimento;
                $registro->dia = date('Y-m-d G:i:s');
                $registro->usuario = TSession::getValue('userid');
                $registro->maquina = $param->maquina;
                $registro->valor = $param->valor * -1;
                $registro->descricao = $param->descricao;
                $registro->fechado = $param->fechado;
                $registro->visita = $param->visita;
                $registro->store();
                TTransaction::close();
                TSession::delValue('dados');
                $this->form->clear(); // clear form
                TToast::show('success', 'Pagamento Máq '.$param->maquina.' Valor '.number_format($param->valor, 2, ',', '.').' registrado', 'top right', 'far:check-circle' );
                AdiantiCoreApplication::loadPage('AtendenteForm');
            }
            $this->onReload();
        } catch (Exception $e){
            new TMessage('error', $e->getMessage());

        }
    }
    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {
            $totalgeral = 0;
            $totalCambio = 0;
            $totalPaga = 0;
            $totalPassa = 0;

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

            $ct_at = config::getConfig('contasatendente');

            $repository = new TRepository('movimento');
            $criteria = new TCriteria;
            $newparam = $param; // define new parameters
            if (empty($newparam['order']))
            {
                $newparam['order'] = 'dia';
                $newparam['direction'] = 'desc';
            }
            $criteria->setProperties($newparam); // order, offset
            if(!Utils::isCoordenador()) {
                $criteria->add(new TFilter('usuario', '=', TSession::getValue('userid')));
            }
            $criteria->add(new TFilter('maquina', '<', 800));
            $criteria2 = new TCriteria;
            $criteria2->add(new TFilter('fechado', 'IS', NULL));
            $criteria2->add(new TFilter('fechado', '=', '2019-01-01 00:00:00'), TExpression::OR_OPERATOR);
            $criteria->add($criteria2);

            $customers = $repository->load($criteria);

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

            $this->datagrid->clear();

            if ($customers)
            {
                // open a transaction with database 'samples'
                TTransaction::open('bingo');
                $usuario = New SystemUser();
                foreach ($customers as $customer)
                {
                    if($customer->fechado == '2019-01-01 00:00:00'){$totalPassa += $customer->valor;$totalPaga -= $customer->valor;};
                    $pode = new DateTime($customer->dia);
                    $customer->dia = $pode->format('d/m/Y H:i:s');
                    if(Utils::isCoordenador()) {
                        $teste = $usuario->exists($customer->usuario);
                        if ($teste) {
                            $usuario = New SystemUser($customer->usuario);
                            $customer->usuario = $usuario->name;
                        } else {
                            $customer->usuario = 'Excluido';
                        }
                    }
                    // add the object inside the datagrid
                    $this->datagrid->addItem($customer);
                    $totalgeral += $customer->valor;
                    if($customer->maquina == 0){$totalCambio += $customer->valor;}else{$totalPaga += $customer->valor;};
                }
                // close the transaction
                TTransaction::close();
            }

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

            $this->loaded = true;

            $this->hbox->clearChildren();

            $labelCambio = new TLabel('CÂMBIO: R$ '.number_format($totalCambio, 2, ',', '.'));
            $labelCambio->setFontSize(15);
            $labelCambio->setFontFace('Trebuchet MS');
            $labelCambio->setFontColor('white');

            $labelPaga = new TLabel('PAGAMENTOS: R$ '.number_format($totalPaga, 2, ',', '.'));
            $labelPaga->setFontSize(15);
            $labelPaga->setFontFace('Trebuchet MS');
            $labelPaga->setFontColor('white');

            $labelPassa = new TLabel('PASSA CAIXA: R$ '.number_format($totalPassa, 2, ',', '.'));
            $labelPassa->setFontSize(17);
            $labelPassa->setFontFace('Trebuchet MS');
            $labelPassa->setFontColor('white');

            $labelTotal = new TLabel('SALDO: R$ '.number_format($totalgeral, 2, ',', '.'));
            $labelTotal->setFontSize(17);
            $labelTotal->setFontFace('Trebuchet MS');
            $labelTotal->setFontColor('white');

            $btcambio = new TButton('cambio');
            $btcambio->setLabel($labelCambio);
            $btcambio->class = 'btn btn-primary btn-sm';

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

            $btpassa = new TButton('passa');
            $btpassa->setLabel($labelPassa);
            $btpassa->class = 'btn btn-success btn-lg';

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

            if($ct_at){
                if($totalCambio != 0){$this->hbox->add($btcambio);}
                if($totalPaga   != 0){$this->hbox->add($btpaga);}
                if($totalPassa  != 0){$this->hbox->add($btpassa);}
                if($totalgeral  != 0){$this->hbox->add($btsaldo);}
            }

        }
        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
        TSession::setValue('dados', $param);
        $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);
    }

    public function Delete($param)
    {
        try
        {
            if( TSession::getValue('dados')) {
                $param = TSession::getValue('dados');
                // get the parameter $key
                $key=$param['key'];
                TSession::delValue('dados');

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

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

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

                if(!Utils::isCoordenador()) {
                    $pode = new DateTime($object->dia);
                    $pode->modify('+60 minutes');
                    $hora = new DateTime();
                    if($hora > $pode){
                        throw new Exception('Tempo 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
                TToast::show('error', AdiantiCoreTranslator::translate('Record deleted'), 'top right', 'far:check-circle' );
                AdiantiCoreApplication::loadPage('AtendenteForm');
            }
        }
        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 onPassaCaixa($param)
    {
        try
        {
            // get the parameter $key
            $key=$param['key'];

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

            if(config::getConfig('passacaixa')) {
                // instantiates object
                $object = new movimento($key);

                if ($object->maquina == 0) {
                    throw new Exception('Registro não pode ser alterado');
                };

                if ($object->fechado == '2019-01-01 00:00:00') {
                    $object->fechado = NULL;
                } else {
                    $object->fechado = '2019-01-01 00:00:00';
                }
                $object->store();
                TToast::show('info', 'Registro Atualizado', 'top right', 'far:check-circle' );
            }
            // close the transaction
            TTransaction::close();
            // reload the listing
            $this->onReload( $param );
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());
            // undo all pending operations
            TTransaction::rollback();
        }
    }
    function onEdit($param)
    {
        try
        {
            // get the parameter $key
            $field = $param['field'];
            $key   = $param['key'];
            $value = $param['value'];

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

            // instantiates object Customer
            $customer = new movimento($key);
            $customer->{$field} = $value;
            $customer->store();

            // close the transaction
            TTransaction::close();
            TToast::show('info', 'Registro Atualizado', 'top right', 'far:check-circle' );
            // reload the listing
            $this->onReload($param);
            // shows the success message
        }
        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)
    {

//        var_dump($object);exit;

        $number = number_format($stock, 2, ',', '.');
        if ($stock < 0)
        {
            if($object->fechado == '2019-01-01 00:00:00'){$row->style = "background: #5cb85c";}
            return "<span style='color:red'>$number</span>";
        }
        else
        {
            $row->style = "background: #FFF9A7";
            return "<span style='color:blue'>$number</span>";
        }
    }
    /**
     * Define when the action can be displayed
     */
    public function displayColumn( $object )
    {

        $hora = new DateTime();
        $dia = substr($object->dia,6,4).'-'.substr($object->dia,3,2).'-'.substr($object->dia,0,2).' '.substr($object->dia,11,2).':'.substr($object->dia,14,2).':'.substr($object->dia,17,2);
        $pode = new DateTime($dia);
        $pode->modify('+60 minutes');

        if(Utils::isGerente()) {
            return TRUE;
        }
        if($hora->format('Y-m-d H:i:s') < $pode->format('Y-m-d H:i:s') and $object->maquina <> 0){
            return TRUE;
        };
        return FALSE;
    }

    /**
     * Define when the action can be displayed
     */
    public function displayPassa( $object )
    {
        if(Utils::isCoordenador()) {
            return TRUE;
        }
        return FALSE;
    }

    public static function onExitMaquina($param)
    {
        try
        {
            TTransaction::open('unit_database');
            $machine = new maquina($param['key']);
            TTransaction::close();
            $obj = new StdClass;
            $obj->tipo   = $machine->tipo.' ('.$machine->credito.')';
            TForm::sendData('form_atendente', $obj);
            TScript::create('$("input[name=\'descricao\']").focus();');
        }
        catch (Exception $e)
        {
            // does nothing
        }
    }

    public static function onExitCredito($param)
    {
        try
        {
            TTransaction::open('unit_database');
            $machine = new maquina($param['maquina']);
            TTransaction::close();
            $obj = new StdClass;
            $obj->valor   = $param['creditos'] * $machine->credito;
            TForm::sendData('form_atendente', $obj);
            TScript::create('$("input[name=\'descricao\']").focus();');
        }
        catch (Exception $e)
        {
            // does nothing
        }
    }

}
