<?php
use Adianti\Control\TAction;
use Adianti\Control\TPage;
use Adianti\Database\TCriteria;
use Adianti\Database\TFilter;
use Adianti\Database\TTransaction;
use Adianti\Registry\TSession;
use Adianti\Validator\TRequiredValidator;
use Adianti\Widget\Container\TTable;
use Adianti\Widget\Container\TVBox;
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;

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

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

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

        /*
                $cliente_nome = new TCombo('cliente_nome');
                $criteria = new TCriteria();
                $criteria->add(new TFilter('saida', 'IS', NULL));         // create the form fields
                $combo_items = array();
                TTransaction::open('unit_database');
                $repository = new TRepository('visita');
                $visitas = $repository->load($criteria);
                TTransaction::close();
                foreach ($visitas as $visita)
                {
                    // add the object inside the datagrid
                    $combo_items[$visita->id_cliente.'/'.$visita->tipo_cliente.'/'.$visita->name] =$visita->name;
                }
                $cliente_nome->addItems($combo_items);

        */
        $codigo_id = new TCombo('codigo_id');
        $validacao = new TEntry('descricao');
        $valor     = new TEntry('valor');

        $combo_items = array();
        TTransaction::open('unit_database');
        $codigos = codigo::select('*')->load();
        TTransaction::close();

        foreach ($codigos as $codigo)
        {
            if($codigo->validacliente == 1){
                $combo_items[$codigo->id.$codigo->descricao] =$codigo->id.' - '.$codigo->descricao;
            }
        }
        $codigo_id->addItems($combo_items);

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

        // add validators
        $codigo_id->addValidation('Código', new TRequiredValidator);
        $valor->addValidation('Valor', new TRequiredValidator);
//        $cliente_nome->addValidation('Cliente', new TRequiredValidator);

        // define some attributes
//        $cliente_nome->style = 'font-size: 17pt; height: 30px';
        $codigo_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
        $codigo_id->setSize(300);
//        $valor->setNumericMask(2, '.', ',');
        $aparelho = strpos($_SERVER['HTTP_USER_AGENT'],'Android');
        If($aparelho){
            $valor->setInputType('tel');
        } else {
            $valor->setInputType('number step=0.01');
        }
        $valor->setSize(200);
//        $cliente_nome->setSize(300);

        // add a row for the form title
        $row  = $table_item->addRow();
        $row->class = 'tformtitle'; // CSS class
        $cell = $row->addCell( new TLabel('LANÇAMENTO DE CAIXA'))->style = 'text-align: center;';

        // create the field labels
        $lab_maq = new TLabel('CÓDIGO');
        $lab_des = new TLabel('DESCRIÇÃO');
        $lab_val = new TLabel('VALOR');
        $lab_cli = new TLabel('CLIENTE');
        $lab_cli->setFontSize(17);
        $lab_maq->setFontSize(17);
        $lab_des->setFontSize(17);
        $lab_val->setFontSize(17);
        $lab_cli->setFontFace('Trebuchet MS');
        $lab_maq->setFontFace('Trebuchet MS');
        $lab_des->setFontFace('Trebuchet MS');
        $lab_val->setFontFace('Trebuchet MS');
//        $lab_cli->setFontColor('red');
//        $lab_val->setFontColor('red');

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

        // add the form fields
        $table_item->addRowSet($lab_maq)->style = 'text-align: center;';
        $table_item->addRowSet($codigo_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($lab_cli)->style = 'text-align: center;';
//        $table_item->addRowSet($cliente_nome)->style = 'text-align: center;';
        $table_item->addRowSet('')->style = 'text-align: center;';
        $table_item->addRowSet(array($button1))->style = 'text-align: center;';

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

        // create the datagrid
        $this->datagrid = new TQuickGrid;

        // add the columns
        $this->datagrid->addQuickColumn('Data','dia','center', 150, new TAction(array($this, 'onReload')), array('order', 'dia'));
        $this->datagrid->addQuickColumn('Código','maquina','center', 30, 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', 170, new TAction(array($this, 'onReload')), array('order', 'valor'));
        $valor->setTransformer(array($this, 'formatsaldo'));

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

        $this->datagrid->setGroupColumn('maquina', '<b>Código da Despesa</b>: <strong>{maquina}</strong>');
        $this->datagrid->disableDefaultClick();

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

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

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
        $vbox->add($this->form_item);
        $vbox->add($btsaldo);
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        parent::add($vbox);
    }
    /**
     * Saves the cart
     */
    public function onSave()
    {
        try
        {
            $this->form_item->validate(); // validate form data
            $data = $this->form_item->getData();

            $data->valor = str_replace(',', '.', $data->valor);

            TTransaction::open('unit_database');
            /*            $codi = new codigo(substr($data->codigo_id,0,3));

                        // Validador Cliente
                        If($codi->validacliente == 1){
                            If($data->cliente_nome == ''){
                                throw new Exception('O campo Cliente é obrigatório.');
                            }
                            $dados=explode('/',$data->cliente_nome);
                        } else {
                            $dados[0]='0';$dados[1]='0';$dados[2]='';
                        }
            */
            $registro = new Movimento;
            $registro->usuario = TSession::getValue('userid');
            $registro->maquina = substr($data->codigo_id,0,3);
//            if($dados[1] == 0){
//                $registro->descricao = substr($data->codigo_id,3,50).' '.$dados[2].' '.$data->descricao;
//            } else {
            $registro->descricao = substr($data->codigo_id,3,50).' '.$data->descricao;
//            }
            if($registro->maquina < 950) {
                $registro->valor = ($data->valor);
            } else {
                $registro->valor = (($data->valor) * -1);
            }
//            if($registro->maquina == 899) {
//                $registro->valor = (($data->valor) * -1);
//            }
//            $registro->visita = $dados[0];
//            if($dados[0]==0){
            $registro->visita=999;
            $registro->store();
//            };

            // Transfere Caixa Inicial
            $criteria = new TCriteria();
            $criteria->add(new TFilter('usuario', '=', 0));
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $repository = new TRepository('Movimento');
            $count = $repository->count($criteria);
            $result = $repository->load($criteria);
            if($count == 2){
                foreach ($result as $item){
                    if($item->maquina == 901) {
                        $registro = new Movimento;
                        $registro->usuario = TSession::getValue('userid');
                        $registro->maquina = '0';
                        $registro->visita = '999';
                        $registro->descricao = 'TRANSFERÊNCIA DE CAIXA INICIAL';
                        $registro->valor = $item->valor;
                        $registro->store();
                        $registro = new Movimento;
                        $registro->usuario = '0';
                        $registro->maquina = '0';
                        $registro->visita = '999';
                        $registro->descricao = 'TRANSFERÊNCIA DE CAIXA INICIAL';
                        $registro->valor = (($item->valor) * -1);
                        $registro->store();
                    }
                }
            }
            $this->form_item->clear(); // clear form
            TToast::show('success', 'Registro Salvo com Sucesso', 'top right', 'far:check-circle' );

            // Verifica Caixa Fechado
            $criteria = new TCriteria();
            $criteria->add(new TFilter('maquina', '=', 904));
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $repository = new TRepository('Movimento');
            $result = $repository->load($criteria);
            $messageshow = False;
            foreach ($result as $item) {
                if ($item->usuario != TSession::getValue('userid')) {
                    $messageshow = True;
                }
            }
            if($messageshow){
                // shows a dialog to the user
                echo "<embed src='app/images/notificacao.mp3'width='0' height='0'>";
                new TMessage('warning', 'Lançamentos feitos por 2 caixas diferentes. O Caixa anterior esta mesmo fechado ?');
            }
            TTransaction::close();
            AdiantiCoreApplication::loadPage('LancaForm');
        }catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {
            $this->totalgeral = 0;
            $this->totalMarca = 0;

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

            // 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(!Utils::isCaixa()){
                $criteria->add(new TFilter('usuario', '=', TSession::getValue('userid')));
            }
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $criteria->add(new TFilter('maquina', '>', 798));

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

            $machine='999';
            $total_machine=0;

            if ($customers)
            {
                foreach ($customers as $customer)
                {
                    if($machine != $customer->maquina AND $machine != '999'){
                        $obj = new stdclass();
                        $obj->id = '';
                        $obj->dia = '';
                        $obj->maquina = $machine;
                        $obj->usuario = 0;
                        $obj->valor = ($total_machine * -1);
                        $obj->descricao = 'SUB-TOTAL';
                        $this->datagrid->addItem($obj);

                        $total_machine = 0;

                    };
                    $total_machine += $customer->valor * -1;
                    $machine = $customer->maquina;
                    $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);
                    // add the object inside the datagrid
                    $this->datagrid->addItem($customer);
                    $this->totalgeral += $customer->valor;
                }
                $obj = new stdclass();
                $obj->id = '';
                $obj->dia = '';
                $obj->maquina = $machine;
                $obj->usuario = 0;
                $obj->valor = ($total_machine * -1);
                $obj->descricao = 'SUB-TOTAL';
                $this->datagrid->addItem($obj);
            }

            // 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, ',', '.'));
        }
        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('unit_database');

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

            if($object->maquina == 0){
                throw new Exception('Lançamentos do sistema não podem ser excluídos');
            };

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

            if($object->maquina == 903){
                throw new Exception('Vales pagos não podem ser excluídos, lance um Vale para estornar');
            };

            if($object->maquina == 958){
                throw new Exception('Vales não podem ser excluídos, lance um Vale Pago para estornar');
            };

            // 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('LancaForm');
        }
        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>";
        }
    }

    /**
     * Define when the action can be displayed
     */
    public function displayColumn( $object )
    {
        if ($object->usuario > 0)
        {
            return TRUE;
        }
        return FALSE;
    }

}