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

        $destino = new TCombo('destino');
        $criteria = new TCriteria();
        $criteria->add(new TFilter('system_group_id', '=', 5));         // create the form fields
        $criteria->setProperty('order', 'system_user_id');
        TTransaction::open('bingo');
        $repository = new TRepository('SystemUserGroup');
        $result = $repository->load($criteria);
        $combo_items = array();
        foreach ($result as $item){
            $quem = new SystemUser($item->system_user_id);
            $combo_items[$item->system_user_id] = strtoupper($quem->name);
        }
        TTransaction::close();
        asort($combo_items);
        $destino->additems($combo_items);

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

        // 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');
        $valor->setSize(200);

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

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

        // define the form fields
        $this->form_item->setFields(array($destino, $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('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;';
        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);
            $registro = new Movimento;
            $registro->usuario = TSession::getValue('userid');
            $registro->maquina = '0';
            $registro->visita = '999';
            $registro->descricao = "PAGOU PARA ".strtoupper($quem->name);
            $registro->valor = ($data->valor) * -1;
            $registro->store();

            $registro = new Movimento;
            $registro->usuario = $data->destino;
            $registro->maquina = '0';
            $registro->visita = '999';
            $registro->descricao = "RECEBEU DE ".strtoupper(TSession::getValue('username'));
            $registro->valor = ($data->valor);
            $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('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('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>";
        }
    }
}