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

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

        TSession::setValue('cartao_inicial',0);
        TSession::setValue('qtde_cartoes',0);
        TSession::setValue('arrecadado',0);
        TSession::setValue('valor',2);
        TSession::setValue('linha',0);
        TSession::setValue('bingo',0);
        TSession::setValue('bingo2',0);
        TSession::setValue('extra',0);
        TSession::setValue('qtdeserie',1);

        // creates the items form and add a table inside
        $this->form_item = new TForm('form_partida');
        $this->form_item->class = 'tform';
        $table = new TTable;
        $table->width = '100%';
        $table->addRowSet(new TLabel('CADASTRO DE PARTIDAS'), '')->class = 'tformtitle';
        $this->form_item->add($table);

        TTransaction::open('bingo');
        $repository = new TRepository('leitura');
        $criteria = new TCriteria;
        $criteria->add(new TFilter('fechado', 'IS', NULL));
        $count = $repository->count($criteria) + 1;
        $partida   = new TEntry('partida');
        $partida->setValue($count);
        TSession::setValue('partida',$count-1);

        $qtdeserie = new TRadioGroup('qtdeserie');
        $qtdeserie->setLayout('horizontal');
        $qtdeserie->setValue(1);
        $items = array();
        $items['1'] ='12.000';
        $items['2'] ='24.000';
        $items['3'] ='36.000';
        $qtdeserie->addItems($items);

        $inicial    = new TEntry('inicial');
        $final      = new TEntry('final');
        $qtde       = new TEntry('qtde');
        $cortesia   = new TEntry('cortesia');
        $valor      = new TEntry('valor');
        $arrecadado = new TEntry('arrecadado');
        $linha      = new TEntry('linha');
        $bingo      = new TEntry('bingo');
        $bingo2     = new TEntry('bingo2');
        $extra      = new TEntry('extra');
        $premios    = new TEntry('premios');
        $lucro      = new TEntry('lucro');
        $bola_top   = new TEntry('top');
        $saldo_atu  = new TEntry('saldo_atu');

        $partida->setEditable(FALSE);
        $qtde->setEditable(FALSE);
        $arrecadado->setEditable(FALSE);
        $premios->setEditable(FALSE);
        $lucro->setEditable(FALSE);
        $saldo_atu->setEditable(FALSE);

        $valor->setNumericMask(2, ',', '.', true);
        $valor->setValue(2);
        $cortesia->setValue(0);
        $extra->setValue(0);
        $bola_top->setValue(TSession::getValue('bola_top'));
        $inicial->setValue(TSession::getValue('final')+1);
        $arrecadado->setNumericMask(2, ',', '.', true);
        $premios->setNumericMask(2, ',', '.', true);

        $inicial->setInputType('number');
        $final->setInputType('number');
        $cortesia->setInputType('number');
        $linha->setInputType('number');
        $bingo->setInputType('number');
        $bingo2->setInputType('number');
        $extra->setInputType('number');
        $bola_top->setInputType('number');

        // add validators
        $inicial->addValidation('Inicial', new TRequiredValidator);
        $final->addValidation('Final', new TRequiredValidator);
        $valor->addValidation('Valor da Série', new TRequiredValidator);
        $linha->addValidation('Linha', new TRequiredValidator);
        $bingo->addValidation('Bingo', new TRequiredValidator);
        $bingo2->addValidation('Bingo2', new TRequiredValidator);
        $extra->addValidation('Extra', new TRequiredValidator);
        $cortesia->addValidation('Cortesia', new TRequiredValidator);

        $qtdeserie->setChangeAction(new TAction(array($this, 'onExitQtdeSerie')));
        $valor->setExitAction(new TAction(array($this, 'onExitValor')));
        $inicial->setExitAction(new TAction(array($this, 'onExitInicial')));
        $final->setExitAction(new TAction(array($this, 'onExitFinal')));
        $cortesia->setExitAction(new TAction(array($this, 'onExitCortesia')));
        $linha->setExitAction(new TAction(array($this, 'onExitLinha')));
        $bingo->setExitAction(new TAction(array($this, 'onExitBingo')));
        $bingo2->setExitAction(new TAction(array($this, 'onExitBingo2')));
        $extra->setExitAction(new TAction(array($this, 'onExitExtra')));
        $bola_top->setExitAction(new TAction(array($this, 'onExitTop')));

        // define some attributes
        $partida->style    = 'font-size: 17pt; height: 30px; width: 80px; text-align: center; autocomplete="off";';
        $inicial->style    = 'font-size: 17pt; height: 30px; width: 100px; text-align: center; autocomplete="off";';
        $final->style      = 'font-size: 17pt; height: 30px; width: 100px; text-align: center; autocomplete="off";';
        $qtde->style       = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; background-color: #ffff99; ';
        $cortesia->style   = 'font-size: 17pt; height: 30px; width: 100px; text-align: center; autocomplete="off";';
        $valor->style      = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; autocomplete="off";';
        $arrecadado->style = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; background-color: #ffff99; ';
        $linha->style      = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; autocomplete="off";';
        $bingo->style      = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; autocomplete="off";';
        $bingo2->style     = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; autocomplete="off";';
        $extra->style      = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; autocomplete="off";';
        $premios->style    = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; background-color: #ffff99; ';
        $lucro->style      = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; background-color: #ffff99; ';
        $bola_top->style   = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; background-color: #bbffff; ';
        $saldo_atu->style   = 'font-size: 17pt; height: 30px; width: 140px; text-align: center; background-color: #90EE90; ';
        foreach ($qtdeserie->getLabels() as $key => $label)
        {
            $label->style = 'font-size: 15pt; height: 20px; width: 100px; text-align: left;';
        }

        // create the field labels
        $l_partida    = new TLabel('PARTIDA', 'black', 15,     NULL, 50);
        $l_qtdeserie  = new TLabel('TIPO DE SÉRIE',   'black', 15,     NULL, 200);
        $l_valor      = new TLabel('PREÇO SÉRIE',   'black', 15,     NULL, 150);
        $l_inicial    = new TLabel('INICIAL', 'black', 15,     NULL, 50);
        $l_final      = new TLabel('FINAL',   'black', 15,     NULL, 50);
        $l_qtde       = new TLabel('QTDE CARTÕES',   'black', 15,     NULL, 200);
        $l_cortesia   = new TLabel('CORTESIA',   'black', 15,     NULL, 150);
        $l_arrecadado = new TLabel('ARRECADADO',   'blue', 15,     NULL, 150);
        $l_linha      = new TLabel('LINHA',   'red', 15,     NULL, 150);
        $l_bingo      = new TLabel('BINGO',   'red', 15,     NULL, 150);
        $l_bingo2     = new TLabel('2º BINGO',   'red', 15,     NULL, 150);
        $l_extra      = new TLabel('EXTRA',   'red', 15,     NULL, 150);
        $l_premios    = new TLabel('TOTAL PRÊMIOS',   'red', 15,     NULL, 200);
        $l_lucro      = new TLabel('LUCRO',   'blue', 15,     NULL, 200);
        $l_bola_top   = new TLabel('BOLA TOP',   'black', 15,     NULL, 200);
        $l_saldo_atu  = new TLabel('SALDO ATUAL',   'black', 15,     NULL, 200);

        // 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->addRowSet($l_partida, $partida, $l_bola_top)->style = 'text-align: left;';
        $table->addRowSet($l_qtdeserie, $qtdeserie, $bola_top)->style = 'text-align: left;';
        $table->addRowSet($l_valor, $valor)->style = 'text-align: left;';
        $table->addRowSet($l_linha, $linha)->style = 'text-align: left;';
        $table->addRowSet($l_bingo, $bingo)->style = 'text-align: left;';
        $table->addRowSet($l_bingo2, $bingo2)->style = 'text-align: left;';
        $table->addRowSet($l_extra, $extra)->style = 'text-align: left;';
        $table->addRowSet($l_inicial, $inicial)->style = 'text-align: left;';
        $table->addRowSet($l_final, $final)->style = 'text-align: left;';
        $table->addRowSet($l_cortesia, $cortesia)->style = 'text-align: left;';
        $table->addRowSet($l_qtde, $qtde)->style = 'text-align: left;';
        $table->addRowSet($l_arrecadado, $arrecadado, $l_saldo_atu)->style = 'text-align: left;';
        $table->addRowSet($l_premios, $premios, $saldo_atu)->style = 'text-align: left;';
        $table->addRowSet($l_lucro, $lucro)->style = 'text-align: left;';

        $table->addRowSet('');
        $table->addRowSet('');
        $table->addRowSet('');
        $table->addRowSet(array($button1));

        // define the form fields
        $this->form_item->setFields(array($partida, $inicial, $final, $qtde, $cortesia, $valor, $arrecadado, $linha, $bingo, $bingo2, $extra, $premios, $lucro, $qtdeserie, $bola_top, $saldo_atu, $button1));

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

        // add the columns
        $this->datagrid->addQuickColumn('Partida','partida','center', "5%", new TAction(array($this, 'onReload')), array('order', 'partida'));
        $this->datagrid->addQuickColumn('Inicial','inicial','center', "5%", new TAction(array($this, 'onReload')), array('order', 'inicial'));
        $this->datagrid->addQuickColumn('Final','final','center', "5%", new TAction(array($this, 'onReload')), array('order', 'final'));
        $this->datagrid->addQuickColumn('Cortesia','cortesia','center', "5%", new TAction(array($this, 'onReload')), array('order', 'cortesia'));
        $this->datagrid->addQuickColumn('Vendidos','qtde','center', "5%", new TAction(array($this, 'onReload')), array('order', 'qtde'));
        $coluna = $this->datagrid->addQuickColumn('P.Série','valor','center', "5%", new TAction(array($this, 'onReload')), array('order', 'valor'));
        $coluna->setTransformer(array($this, 'formatSaldo'));
        $coluna = $this->datagrid->addQuickColumn('Arrecadado','arrecadado','center', "10%", new TAction(array($this, 'onReload')), array('order', 'arrecadado'));
        $coluna->setTransformer(array($this, 'formatSaldo'));
        $coluna = $this->datagrid->addQuickColumn('Linha','linha','center', "10%", new TAction(array($this, 'onReload')), array('order', 'linha'));
        $coluna->setTransformer(array($this, 'formatSaldo'));
        $coluna = $this->datagrid->addQuickColumn('Bingo','bingo','center', "10%", new TAction(array($this, 'onReload')), array('order', 'bingo'));
        $coluna->setTransformer(array($this, 'formatSaldo'));
        $coluna = $this->datagrid->addQuickColumn('2º Bingo','bingo2','center', "10%", new TAction(array($this, 'onReload')), array('order', 'bingo2'));
        $coluna->setTransformer(array($this, 'formatSaldo'));
        $coluna = $this->datagrid->addQuickColumn('Extra','extra','center', "10%", new TAction(array($this, 'onReload')), array('order', 'extra'));
        $coluna->setTransformer(array($this, 'formatSaldo'));
        $coluna = $this->datagrid->addQuickColumn('Total Prêmios','premios','center', "10%", new TAction(array($this, 'onReload')), array('order', 'premios'));
        $coluna->setTransformer(array($this, 'formatSaldox'));
        $coluna = $this->datagrid->addQuickColumn('Lucro','lucro','center', "10%", new TAction(array($this, 'onReload')), array('order', 'lucro'));
        $coluna->setTransformer(array($this, 'formatSaldo'));
        $coluna = $this->datagrid->addQuickColumn('Saldo','saldo','center', "10%", new TAction(array($this, 'onReload')), array('order', 'saldo'));
        $coluna->setTransformer(array($this, 'formatSaldo'));

        // creates two datagrid actions
        $action1 = new TDataGridAction(array($this, 'onDelete'));
        $action1->setLabel('Deleta');
        $action1->setImage('fa:trash red');
        $action1->setField('id');
        $action1->setDisplayCondition( array($this, 'displayColumn') );

        // add the actions
        $this->datagrid->addQuickAction('Deleta', $action1, 'id', 'fa:trash red');

        // 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;overflow-x:auto;';
        $vbox->add($this->form_item)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        parent::add($vbox);

        // Desabilita ENTER nos campos
        TScript::create('$("input, select, text, button").keypress(
        function (e)
            {
var self = $(this)
  , form = self.parents(\'form:eq(0)\')
  , focusable
  , next
  , prev
  ;
if (e.shiftKey) {
 if (e.keyCode == 13) {
     focusable =   form.find(\'input,select,button,textarea\').filter(\':visible\');
     prev = focusable.eq(focusable.index(this)-1); 
     if (prev.length) {
        prev.focus();
    }
  }
}
  else
if (e.keyCode == 13) {
    focusable = form.find(\'input,select,button,textarea\').filter(\':visible\');
    next = focusable.eq(focusable.index(this)+1);
    if (next.length) {
        next.focus();
    }
    return false;
}
}
            )
            ;');

    }
    /**
     * Saves the cart
     */
    public function onSave()
    {
        try
        {
            $this->form_item->validate(); // validate form data
            $data = $this->form_item->getData();
            TTransaction::open('bingo');
            $leitura = new leitura();
            $leitura->partida = $data->partida;
            $leitura->inicial = $data->inicial;
            $leitura->final = $data->final;
            $leitura->qtde = $data->qtde;
            $leitura->cortesia = $data->cortesia;
            $leitura->valor = $data->valor;
            $leitura->linha = $data->linha;
            $leitura->bingo = $data->bingo;
            $leitura->bingo2 = $data->bingo2;
            $leitura->extra = $data->extra;
            $leitura->store();
            TTransaction::close();
            $this->form_item->clear(); // clear form
            new TMessage('info', 'Partida Salva com Sucesso');
            TSession::setValue('final',$data->final);
            AdiantiCoreApplication::loadPage('LeiFinalForm', 'onReload');
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {
            TTransaction::open('bingo');
            $repository = new TRepository('leitura');
            $criteria = new TCriteria;
            $newparam = $param; // define new parameters
            // default order
            if (empty($newparam['order']))
            {
                $newparam['order'] = 'partida';
                $newparam['direction'] = 'asc';
            }

            $criteria->setProperties($newparam); // order, offset
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $customers = $repository->load($criteria, FALSE);
            $this->datagrid->clear();

            if ($customers)
            {
                $saldo = 0;
                foreach ($customers as $customer)
                {
                    $customer->arrecadado = ($customer->qtde/6) * $customer->valor;
                    $customer->premios = $customer->linha + $customer->bingo + $customer->bingo2 + $customer->extra;
                    $customer->lucro = $customer->arrecadado - $customer->premios;
                    $saldo += $customer->lucro;
                    $customer->saldo = $saldo;
                    $this->datagrid->addItem($customer);
                }
            }

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

            $obj = new StdClass;
            $obj->saldo_atu = number_format($saldo, 2, ',', '.');
            TForm::sendData('form_partida', $obj);

            // close the transaction
            $this->loaded = true;
            TScript::create('$("input[name=\'linha\']").focus();');
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());

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

    public static function onExitQtdeSerie($param)
    {
        TSession::setValue('qtdeserie',$param['_field_value']);
    }

    public static function onExitInicial($param)
    {
        TSession::setValue('cartao_inicial',$param['_field_value']);
    }

    public static function onExitValor($param)
    {
        TSession::setValue('valor',str_replace( ',', '.', $param['_field_value']));
    }

    public static function onExitTop($param)
    {
        TSession::setValue('bola_top',$param['_field_value']);
    }

    public static function onExitFinal($param)
    {
        $obj = new StdClass;
        $obj->qtde = (intval($param['_field_value']) - intval(TSession::getValue('cartao_inicial')))+1;
        if(TSession::getValue('cartao_inicial') > $param['_field_value']){$obj->qtde = $obj->qtde + intval(TSession::getValue('qtdeserie'))*12000;}
        TSession::setValue('qtde_cartoes',$obj->qtde);
        TForm::sendData('form_partida', $obj);
    }

    public static function onExitCortesia($param)
    {
        TSession::setValue('cortesia',$param['_field_value']);
        $obj = new StdClass;
        $quant = intval(TSession::getValue('qtde_cartoes')) - intval($param['_field_value']);
        $obj->qtde = $quant;
        $arre = ($quant / 6) * TSession::getValue('valor');
        $obj->arrecadado = number_format($arre , 2, ',', '.') ;
        $tot_pre = intval(TSession::getValue('linha')) + intval(TSession::getValue('bingo')) + intval(TSession::getValue('bingo2')) + intval(TSession::getValue('extra'));
        $obj->lucro = number_format($arre - intval($tot_pre), 2, ',', '.');
        TSession::setValue('arrecadado',$arre);
        TForm::sendData('form_partida', $obj);
    }

    public static function onExitLinha($param)
    {
        TSession::setValue('linha',$param['_field_value']);
        $tot_pre = intval($param['_field_value']) + intval(TSession::getValue('bingo')) + intval(TSession::getValue('bingo2')) + intval(TSession::getValue('extra'));
        $obj = new StdClass;
        $obj->premios = number_format($tot_pre, 2, ',', '.') ;
        $obj->lucro = number_format(intval(TSession::getValue('arrecadado')) - intval($tot_pre), 2, ',', '.');
        TForm::sendData('form_partida', $obj);
    }

    public static function onExitBingo($param)
    {
        TSession::setValue('bingo',$param['_field_value']);
        $tot_pre = intval($param['_field_value']) + intval(TSession::getValue('linha')) + intval(TSession::getValue('bingo2')) + intval(TSession::getValue('extra'));
        $obj = new StdClass;
        $obj->premios = number_format($tot_pre, 2, ',', '.') ;
        $obj->lucro = number_format(intval(TSession::getValue('arrecadado')) - intval($tot_pre), 2, ',', '.');
        TForm::sendData('form_partida', $obj);
    }

    public static function onExitBingo2($param)
    {
        TSession::setValue('bingo2',$param['_field_value']);
        $tot_pre = intval($param['_field_value']) + intval(TSession::getValue('linha')) + intval(TSession::getValue('bingo')) + intval(TSession::getValue('extra'));
        $obj = new StdClass;
        $obj->premios = number_format($tot_pre, 2, ',', '.') ;
        $obj->lucro = number_format(intval(TSession::getValue('arrecadado')) - intval($tot_pre), 2, ',', '.');
        TForm::sendData('form_partida', $obj);
    }

    public static function onExitExtra($param)
    {
        TSession::setValue('extra',$param['_field_value']);
        $tot_pre = intval($param['_field_value']) + intval(TSession::getValue('linha')) + intval(TSession::getValue('bingo')) + intval(TSession::getValue('bingo2'));
        $obj = new StdClass;
        $obj->premios = number_format($tot_pre, 2, ',', '.') ;
        $obj->lucro = number_format(intval(TSession::getValue('arrecadado')) - intval($tot_pre), 2, ',', '.');
        TForm::sendData('form_partida', $obj);
    }

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

    public function formatSaldox($stock, $object, $row)
    {
        $number = number_format($stock, 2, ',', '.');
        if ($stock > 499)
        {
            $row->style = "background: #FF6A6A";
            return "<span style='color:blue'>$number</span>";
        }
        else
        {
            $row->style = "background: #FFF9A7";
            return "<span style='color:blue'>$number</span>";
        }
    }
    /**
     * 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 leitura($key);

            // 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();
        }
        AdiantiCoreApplication::loadPage('LeiFinalForm', 'onReload');
    }

    /**
     * Define when the action can be displayed
     */
    public function displayColumn( $object )
    {
        if((in_array('1', TSession::getValue('usergroupids')))){
            return TRUE;
        }
        if((in_array('2', TSession::getValue('usergroupids')))){
            return TRUE;
        }
        if(TSession::getValue('partida') == $object->partida){
            return TRUE;
        };
        return FALSE;
    }

}
