<?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;
use Adianti\Widget\Wrapper\TDBCombo;

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

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

        TTransaction::open('bingo');
        $usuarios = SystemUserGroup::where('system_group_id', '>', '2')->load();

        $combo_items = array();
        foreach ($usuarios as $usuario){
            $quem = new SystemUser($usuario->system_user_id);
            $unidades = $quem->getSystemUserUnits();
            foreach ($unidades as $unidade){
                if($quem->active == 'Y' and $usuario->system_user_id <> TSession::getValue('userid') and $unidade->id == TSession::getValue('userunitid')){
                    $combo_items[$usuario->system_user_id] = strtoupper($quem->name);
                }
            }
        }
        TTransaction::close();
        asort($combo_items);
        $destino = new TCombo('destino');
        $destino->additems($combo_items);

        $valor        = new TEntry('valor');

        // add validators
        $destino->addValidation('Destino', new TRequiredValidator);
        $valor->addValidation('Valor', new TRequiredValidator);

        // define some attributes
        $destino->style = 'font-size: 17pt; height: 30px';
        $valor->style = 'font-size: 17pt; height: 30px;';

        // define some properties
      //  $valor->setInputType('tel');
           $aparelho = strpos($_SERVER['HTTP_USER_AGENT'],'Android');
        If($aparelho){
            $valor->setInputType('tel');
        } else {
            $valor->setInputType('number step=0.01');
        }
        $valor->setSize(200);
        $valor->autocomplete = 'off';

        // add a row for the form title
        $row  = $table_item->addRow();
        $row->class = 'tformtitle'; // CSS class
        $cell = $row->addCell( new TLabel('TRANSFERÊNCIA (CÂMBIO)'))->style = 'text-align: center;';

        // create the field labels
        $lab_ori = new TLabel('ORIGEM (DE)');
        $lab_ori->setFontSize(17);
        $lab_ori->setFontFace('Trebuchet MS');
        $lab_ori->setFontColor('white');

        $origem = new TLabel(TSession::getValue('username'));
        $origem->setFontSize(17);
        $origem->setFontFace('Trebuchet MS');

        $lab_des = new TLabel('DESTINO (PARA)');
        $lab_des->setFontSize(17);
        $lab_des->setFontFace('Trebuchet MS');
        $lab_des->setFontColor('white');

        $lab_val = new TLabel('VALOR');
        $lab_val->setFontSize(17);
        $lab_val->setFontFace('Trebuchet MS');

        // 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_ori)->style = 'text-align: center; background-color: green;';
        $table_item->addRowSet($origem)->style = 'text-align: center;';
        $table_item->addRowSet($lab_des)->style = 'text-align: center; background-color: red;';
        $table_item->addRowSet($destino)->style = 'text-align: center;';
        $table_item->addRowSet($lab_val)->style = 'text-align: center;';
        $table_item->addRowSet($valor)->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($destino, $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('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'));

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

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
//        $vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
        $vbox->add($this->form_item);
        $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();

            TTransaction::open('bingo');
            $quem = new SystemUser($data->destino);
            TTransaction::close();

            TTransaction::open('unit_database');
            $registro = new movimento;
            $registro->usuario = TSession::getValue('userid');
            $registro->maquina = '0';
            $registro->visita = '999';
            if($data->valor > 0){
                $registro->descricao = "PAGOU PARA ".strtoupper($quem->name);
            } else {
                $registro->descricao = "RECEBEU DE ".strtoupper($quem->name);

            }
            $registro->valor = ($data->valor) * -1;
            $registro->store();

            $registro = new movimento;
            $registro->usuario = $data->destino;
            $registro->maquina = '0';
            $registro->visita = '999';
            if($data->valor > 0){
                $registro->descricao = "RECEBEU DE ".strtoupper(TSession::getValue('username'));
            } else {
                $registro->descricao = "PAGOU PARA ".strtoupper(TSession::getValue('username'));

            }
            $registro->valor = ($data->valor);
            $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();
                    }
                }
            }

            TTransaction::close();
            $this->form_item->clear(); // clear form
            TToast::show('success', 'Registro Salvo com Sucesso', 'top right', 'far:check-circle' );
            AdiantiCoreApplication::loadPage('TransferForm');
        }
        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

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

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

            if ($customers)
            {
                foreach ($customers as $customer)
                {
                    $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;
                }
            }

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

            // close the transaction
            TTransaction::close();
            $this->loaded = true;
        }
        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('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' );
        }
        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>";
        }
    }
}