<?php

use Adianti\Control\TAction;
use Adianti\Control\TPage;
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\Form\THidden;
use Adianti\Widget\Form\TRadioGroup;
use Adianti\Widget\Wrapper\TDBCombo;

class ValeForm extends TPage
{
    public function __construct()
    {
        parent::__construct();

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

        $cod_cliente = new TDBCombo('cod_cliente','bingo','cliente','id','nome','nome');
        $cod_cliente->setChangeAction(new TAction(array($this, 'onExitCliente')));
        $nome_cliente = new THidden('nome_cliente');

        $saldo = new THidden('saldo');
        $dsp_saldo = new TEntry('dsp_saldo');
        $disponivel = new THidden('disponivel');
        $dsp_disponivel = new TEntry('dsp_disponivel');

        $radio = new TRadioGroup('radio');
        $radio->setLayout('horizontal');
        $items = array();
        $items[0] = 'RETIRADA';
        $items[1] = 'PAGAMENTO';
        $radio->addItems($items);

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

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

        // define some attributes
        $cod_cliente->style = 'font-size: 17pt; height: 30px; text-align: center;';
        $valor->style = 'font-size: 17pt; height: 30px; text-align: center;';
        $dsp_saldo->style = 'font-size: 17pt; height: 30px; text-align: center;';
        $dsp_saldo->setNumericMask(2, ',', '.');
        $dsp_saldo->setEditable(FALSE);
        $dsp_disponivel->style = 'font-size: 17pt; height: 30px; text-align: center;';
        $dsp_disponivel->setNumericMask(2, ',', '.');
        $dsp_disponivel->setEditable(FALSE);

        // define some properties
        $valor->setInputType('tel');
        $valor->setSize(200);
        $cod_cliente->setSize(300);

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

        // create the field labels
        $lab_cli = new TLabel('CLIENTE');
        $lab_maq = new TLabel('SALDO');
        $lab_dsp = new TLabel('DISPONÍVEL');
        $lab_des = new TLabel('TRANSAÇÃO');
        $lab_val = new TLabel('VALOR');
        $lab_cli->setFontSize(17);
        $lab_dsp->setFontSize(17);
        $lab_maq->setFontSize(17);
        $lab_des->setFontSize(17);
        $lab_val->setFontSize(17);
        $lab_cli->setFontFace('Trebuchet MS');
        $lab_dsp->setFontFace('Trebuchet MS');
        $lab_maq->setFontFace('Trebuchet MS');
        $lab_des->setFontFace('Trebuchet MS');
        $lab_val->setFontFace('Trebuchet MS');
//        $lab_cli->setFontColor('red');
//        $lab_dsp->setFontColor('red');
//        $lab_des->setFontColor('red');
//        $lab_val->setFontColor('red');
//        $lab_maq->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('ext');
        $button2->setAction(new TAction(array($this, 'onReload')), 'EXTRATO');
        $button2->class = 'btn btn-info btn-lg btn-block';

        $button3 = new TButton('back');
        $button3->setAction(new TAction(array('CaixaDiaList', 'onReload')), 'VOLTAR');
        $button3->class = 'btn btn-danger btn-lg btn-block';

        // add the form fields
        $table_item->addRowSet($lab_cli)->style = 'text-align: center;';
        $table_item->addRowSet($cod_cliente)->style = 'text-align: center;';
        $table_item->addRowSet($saldo)->style = 'text-align: center;';
        $table_item->addRowSet('')->style = 'text-align: center;';
        $table_item->addRowSet($lab_maq)->style = 'text-align: center;';
        $table_item->addRowSet($dsp_saldo)->style = 'text-align: center;';
        $table_item->addRowSet($disponivel)->style = 'text-align: center;';
        $table_item->addRowSet('')->style = 'text-align: center;';
        $table_item->addRowSet($lab_dsp)->style = 'text-align: center;';
        $table_item->addRowSet($dsp_disponivel)->style = 'text-align: center;';
        $table_item->addRowSet($nome_cliente)->style = 'text-align: center;';
        $table_item->addRowSet('')->style = 'text-align: center;';
        $table_item->addRowSet($lab_des)->style = 'text-align: center;';
        $table_item->addRowSet($radio)->style = 'text-align: center;';
        $table_item->addRowSet('')->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, $button3))->style = 'text-align: center;';

        // define the form fields
        $this->form_item->setFields(array($cod_cliente, $nome_cliente, $saldo, $disponivel, $valor, $radio, $button1, $button2, $button3));

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

        // add the columns
        $this->datagrid->addQuickColumn('Data','dia','center', 150);
        $this->datagrid->addQuickColumn('Usuário','usuario','center', 30);
        $this->datagrid->addQuickColumn('Descrição','descricao','left', 150);
        $valor = $this->datagrid->addQuickColumn('Valor', 'valor', 'right', 170);
        $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();
            if($data->valor > $data->disponivel AND $data->radio == 0){
                new TMessage('error', 'Saldo disponível insuficiente para a transação');
            } elseif($data->valor > $data->saldo AND $data->radio == 1) {
                new TMessage('error', 'Pagamento maior que saldo devedor');
            } else {
                TTransaction::open('bingo');
                $registro = new Movimento;
                $registro->usuario = TSession::getValue('userid');
                if($data->radio == 0){
                    $registro->maquina = '158';
                    $registro->valor = ($data->valor)*-1;
                    $registro->descricao = 'VALE '.$data->nome_cliente;
                } else {
                    $registro->maquina = '103';
                    $registro->valor = $data->valor;
                    $registro->descricao = 'VALE PAGO '.$data->nome_cliente;
                }
                $registro->visita = $data->cod_cliente;
                $vltr = $registro->valor;
                $registro->store();
                $registro = new cliente($data->cod_cliente);
                $novo_saldo = $registro->saldo - $vltr;
                $registro->saldo = $novo_saldo;
                $registro->store();
                TTransaction::close();
                $this->form_item->clear(); // clear form
                new TMessage('info', 'Registro Salvo com Sucesso');
            }
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function  onReload($param = NULL)
    {
        try
        {
            $data = $this->form_item->getData();

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

            // creates a repository for Customer
            $repository = new TRepository('movimento');

            // creates a criteria
            $criteria = new TCriteria;
            $criteria->setProperty('order', 'dia');
            $criteria->add(new TFilter('visita', '=', $data->cod_cliente));
            $criteria->add(new TFilter('maquina', '>', 100));
            $criteria->add(new TFilter('maquina', '<', 400));

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

            if ($customers)
            {
                foreach ($customers as $customer)
                {
                    $busca = new SystemUser($customer->usuario); // reads the product
                    $customer->usuario = $busca->name;
                    $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;
            TSession::setValue('parametro','999');
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());

            // undo all pending operations
            TTransaction::rollback();
        }
    }

    /**
     * Exit action for the field product
     * Fill some form fields (sale_price, amount, discount, total)
     */
    public static function onExitCliente($param)
    {
        $codigo = $param['cod_cliente']; // get the product code
        try
        {
            TTransaction::open('bingo');
            $cliente = new cliente($codigo); // reads the product
            $obj = new StdClass;
            $obj->dsp_saldo  = 'R$ '.number_format($cliente->saldo*-1, 2,',', '.');
            $obj->saldo  = $cliente->saldo;
            $obj->dsp_disponivel  = 'R$ '.number_format($cliente->limite - $cliente->saldo, 2,',', '.');
            $obj->disponivel  = $cliente->limite - $cliente->saldo;
            $obj->nome_cliente = $cliente->nome;
            $obj->radio = 0;
            TTransaction::close();
            TForm::sendData('form_atendente', $obj);
        }
        catch (Exception $e)
        {
            // does nothing
        }
    }

    /**
     * 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>";
        }
    }

}