<?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;
use Adianti\Database\TFilter;

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','unit_database','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');

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

        TEntry::disableField('form_atendente', 'dsp_saldo');
        TEntry::disableField('form_atendente', 'dsp_disponivel');

        // define some properties
        $aparelho = strpos($_SERVER['HTTP_USER_AGENT'],'Android');
        If($aparelho){
            $valor->setInputType('tel');
        } else {
            $valor->setInputType('number step=0.01');
        }
        $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';

        // 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))->style = 'text-align: center;';

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

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

        // add the columns
        $this->datagrid->addQuickColumn('Data','dia','center');
        $this->datagrid->addQuickColumn('Usuário','usuario','center');
        $this->datagrid->addQuickColumn('Descrição','descricao','left');
        $valor = $this->datagrid->addQuickColumn('Valor', 'valor', 'right');
        $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();
            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('unit_database');
                $registro = new Movimento;
                $registro->usuario = TSession::getValue('userid');
                if($data->radio == 0){
                    $registro->maquina = '958';
                    $registro->valor = ($data->valor)*-1;
                    $registro->descricao = 'VALE '.$data->nome_cliente;
                } else {
                    $registro->maquina = '903';
                    $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->last_visita = date('Y-m-d G:i:s');
                $registro->store();
                TTransaction::close();
                $this->form_item->clear(); // clear form
                TToast::show('success', 'Registro Salvo com Sucesso', 'top right', 'far:check-circle' );
                AdiantiCoreApplication::loadPage('ValeForm');
            }
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

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

            if($data->cod_cliente == ''){return;}

            // 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;
            $criteria->setProperty('order', 'dia');
            $criteria->add(new TFilter('visita', '=', $data->cod_cliente));
            // load the objects according to criteria
            $customers = $repository->load($criteria, FALSE);
            $this->datagrid->clear();
            if ($customers)
            {
                TTransaction::open('bingo');
                foreach ($customers as $customer)
                {
                    if(SystemUser::find($customer->usuario)){
                        $busca = new SystemUser($customer->usuario); // reads the product
                        $customer->usuario = $busca->name;
                    } else {
                        $customer->usuario = 'Usuário Excluído';
                    }
                    $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;
                }
                TTransaction::close();
            }

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

}