<?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_atendente');
        $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('bingo');
        $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);

*/
        $criteria = new TCriteria();
        $criteria->add(new TFilter('codigo', '>', 99));         // create the form fields
        $maquina_id   = new TCombo('maquina_id');
        $combo_items = array();
        TTransaction::open('bingo');
        $repository = new TRepository('codigo');
        $codigos = $repository->load();
        TTransaction::close();
        foreach ($codigos as $codigo)
        {
            // add the object inside the datagrid
            $combo_items[$codigo->codigo.$codigo->descricao] =$codigo->codigo.' - '.$codigo->descricao;
        }
        $maquina_id->addItems($combo_items);

        $validacao    = new TEntry('descricao');
        $valor        = new TEntry('valor');
        
        $validacao->autocomplete = 'off';
        $valor->autocomplete = 'off';


        // add validators
        $maquina_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';
        $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(300);
//        $valor->setNumericMask(2, '.', ',');
        $valor->setInputType('tel');
        $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ÇAMENTOS DE CAIXA'))->style = 'text-align: center;';

        // create the field labels
        $lab_maq = new TLabel('CÓDIGO');
        $lab_val = new TLabel('VALOR');
        $lab_des = new TLabel('DESCRIÇÃO');
        $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';

        $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($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, $button2))->style = 'text-align: center;';

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

        // 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
        $this->datagrid->addQuickAction('Deleta', new TDataGridAction(array($this, 'onDelete')), 'id', 'fa:trash red');

        $this->datagrid->setGroupColumn('maquina', '<b>Código da Despesa</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';

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
        $vbox->add($this->form_item)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        $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('bingo');
/*            $codi = new codigo(substr($data->maquina_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->maquina_id,0,3);
//            if($dados[1] == 0){
//                $registro->descricao = substr($data->maquina_id,3,50).' '.$dados[2].' '.$data->descricao;
//            } else {
                $registro->descricao = substr($data->maquina_id,3,50).' '.$data->descricao;
//            }
            if($registro->maquina < 150) {
                $registro->valor = ($data->valor);
            } else {
                $registro->valor = (($data->valor) * -1);
            }
            if($registro->maquina == 99) {
                $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 == 101) {
                        $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
            new TMessage('info', 'Registro Salvo com Sucesso');
            TTransaction::close();
            $this->onReload();
        }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('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

            $criteria->add(new TFilter('usuario', '=', TSession::getValue('userid')));
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $criteria->add(new TFilter('maquina', '<>', 0));

            // 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->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->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('bingo');

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

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

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

            if($object->maquina == 158){
                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
            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>";
        }
    }

}