<?php
use Adianti\Widget\Form\TLabel;

class LeituraForm extends TPage
{
    function __construct($param)
    {
        parent::__construct();

        // creates the form
        $this->form = new BootstrapFormBuilder('form_LeituraFinal');

        // Recupera máquinas do ponto escolhido
        TTransaction::open('jackpot');
        $point = new Ponto($param['method']);

        // creates the containers for each notebook page
        $lab_point = new THidden('ponto');
        $lab_point->setValue($param['method']);
        $lab_point->style = 'font-size: 24pt; height: 50px; width: 300px; text-align: center; autocomplete="off"; background-color: #ffff99;';

        $lab_nome  = new TEntry('nome');
        $lab_nome->setValue($point->nome);
        $lab_nome->style = 'font-size: 18pt; height: 50px; width: 300px; text-align: center; autocomplete="off"; background-color: #ffff99;';

        $lab_porc  = new TEntry('porc');
        $lab_porc->setValue($point->porc_ponto);
        $lab_porc->style = 'font-size: 20pt; height: 50px; width: 300px; text-align: center; autocomplete="off"; background-color: #ffff99;';

        $oper = new SystemUser($point->operador);
        $lab_oper  = new TEntry('oper');
        $lab_oper->setValue($oper->name);
        $lab_oper->style = 'font-size: 20pt; height: 50px; width: 300px; text-align: center; autocomplete="off"; background-color: #ffff99;';

        $campo_cx  = new THidden('caixa');
        $campo_cx->setValue( $point->caixa);

        $lab_cx  = new TEntry('cx');
        $lab_cx->setValue(number_format( $point->caixa, 2, ',', '.'));
        $lab_cx->style = 'font-size: 20pt; height: 50px; width: 300px; text-align: center; autocomplete="off"; background-color: #ffff99;';

        $campo_dv  = new THidden('saldo');
        $campo_dv->setValue( $point->deve);

        $lab_dv  = new TEntry('deve');
        $lab_dv->setValue(number_format( $point->deve, 2, ',', '.'));
        $lab_dv->style = 'font-size: 20pt; height: 50px; width: 300px; text-align: center; autocomplete="off"; background-color: #ffff99;';

        $dia = substr($point->last_visita,8,2).'/'.substr($point->last_visita,5,2).'/'.substr($point->last_visita,0,4).' - '.substr($point->last_visita,11,8);
        $lab_ult  = new TEntry('ult');
        $lab_ult->setValue($dia);
        $lab_ult->style = 'font-size: 20pt; height: 50px; width: 300px; text-align: center; autocomplete="off"; background-color: #ffff99;';

        $this->form->appendPage('Ponto');
        $this->form->addFields( [ $lab_point ], [$campo_cx], [$campo_dv] );
        $this->form->addFields( [ $lab_nome ] );
        $this->form->addFields( [ new TLabel('Porcentagem') ], [ $lab_porc ] );
        $this->form->addFields( [ new TLabel('Operador')    ], [ $lab_oper ] );
        $this->form->addFields( [ new TLabel('Saldo Ponto (Caixa)') ], [ $lab_cx ]);
        $this->form->addFields( [ new TLabel('Saldo Máquina') ], [ $lab_dv ]);
        $this->form->addFields( [ new TLabel('Últ. Leitura') ], [ $lab_ult ]);

        // Recupera Máquinas
        $repository = new TRepository('Maquina');
        $criteria = new TCriteria;
        $criteria->add(new TFilter('id_ponto', '=', $param['method']));
        $objects  = $repository->load($criteria);

        $maquinas = array();
        if ($objects)
        {
            // iterate the collection of active records
            foreach ($objects as $object)
            {
                $criteria = new TCriteria();
                $criteria->add(new TFilter('Maquina', '=', $object->id));
                $criteria->setProperty('order', 'id');
                $criteria->setProperty('direction', 'desc');
                $criteria->setProperty('limit' , 1);
                $repository = new TRepository('Leitura');
                $machine = $repository->load($criteria);
                if($machine) {
                    $item = $machine[0];
                    $obj = new StdClass;
                    $obj->entant = $item->fim_entra;
                    $obj->saiant = $item->fim_sai;
                } else {
                    $obj = new StdClass;
                    $obj->entant = 0;
                    $obj->saiant = 0;
                }
                $maquinas[$object->id] = array('tipo'=>$object->tipo,'credito'=>$object->credito,'ul'=>$object->last_visita,'ei'=>$obj->entant,'si'=>$obj->saiant,'ea'=>$obj->entant,'sa'=>$obj->saiant);
            }
        }

        if ($maquinas)
        {
            // iterate the collection of active records
            foreach ($maquinas as $key => $object)
            {

                // creates the items form and add a table inside
                $table = new TTable;
                $table-> width = '80%';

                $uniqid = $key;

                $entrada  = new TEntry('entrada'.$uniqid);
                $saida    = new TEntry('saida'.$uniqid);
                $entant   = new TEntry('entant'.$uniqid);
                $saiant   = new TEntry('saiant'.$uniqid);
                $creditos = new TEntry('creditos'.$uniqid);
                $pagos    = new TEntry('pagos'.$uniqid);
                $saldo    = new TEntry('saldo'.$uniqid);
                $moeda    = new THidden('moeda'.$uniqid);

                $entant->setValue($object['ei']);
                $saiant->setValue($object['si']);
                $moeda->setValue($object['credito']);

                $entrada->setExitAction(new TAction( [ $this, 'onUpdateLeitura' ] , ['maquina'=>$maquinas]));
                $saida->setExitAction(new TAction( [ $this, 'onUpdateLeitura' ] , ['maquina'=>$maquinas]));

                $entrada->placeholder = 'Entrada Atual';
                $saida->placeholder = 'Saída Atual';

                $entant->setEditable(FALSE);
                $saiant->setEditable(FALSE);
                $creditos->setEditable(FALSE);
                $pagos->setEditable(FALSE);
                $saldo->setEditable(FALSE);

                $entrada->autocomplete = 'off';
                $saida->autocomplete = 'off';

                // define some attributes
                $entrada->style = 'font-size: 24pt; height: 40px; width: 300px; text-align: center; autocomplete="off";';
                $entant->style = 'font-size: 24pt; height: 40px; width: 300px; text-align: center; background-color: #ffff99; ';
                $saida->style = 'font-size: 24pt; height: 40px; width: 300px; text-align: center; autocomplete="off";';
                $saiant->style = 'font-size: 24pt; height: 40px; width: 300px; text-align: center; background-color: #ffff99; ';
                $creditos->style = 'font-size: 24pt; height: 40px; width: 300px; text-align: center; background-color: #bfefff; ';
                $pagos->style = 'font-size: 24pt; height: 40px; width: 300px; text-align: center; background-color: #ff6a6a; ';
                $saldo->style = 'font-size: 24pt; height: 40px; width: 300px; text-align: center; background-color: #30ee90; ';

                $entrada->setInputType('number');
                $saida->setInputType('number');

                // add a row for the form title
                $row  = $table->addRow();
                $row->class = 'tformtitle'; // CSS class
                $row->addCell( new TLabel(strtoupper ($object['tipo'])))->style = 'text-align: center; width:100%;';

                // add the form fields
//                $table->addRowSet(new TLabel('ENTRADA ANTERIOR', 0, 17))->style = 'text-align: center;';
                $table->addRowSet($entant)->style = 'text-align: center;';
                $table->addRowSet($entrada)->style = 'text-align: center;';
//                $table->addRowSet(new TLabel('SAIDA ANTERIOR', 0, 17))->style = 'text-align: center;';
                $table->addRowSet($saiant)->style = 'text-align: center;';
                $table->addRowSet($saida)->style = 'text-align: center;';
                $table->addRowSet(new TLabel('CRÉDITOS', 0, 17))->style = 'text-align: center;';
                $table->addRowSet($creditos)->style = 'text-align: center;';
                $table->addRowSet(new TLabel('PAGAMENTOS', 0, 17))->style = 'text-align: center;';
                $table->addRowSet($pagos)->style = 'text-align: center;';
                $table->addRowSet(new TLabel('SALDO', 0, 17))->style = 'text-align: center;';
                $table->addRowSet($saldo)->style = 'text-align: center;';

                $this->form->appendPage($object['tipo']);
                $this->form->addFields( [ $entant ] );
                $this->form->addFields( [ $entrada ] );
                $this->form->addFields( [ $saiant ] );
                $this->form->addFields( [ new TLabel('Saida Atual') ], [ $saida ] );
                $this->form->addFields( [ new TLabel('Créditos')    ], [ $creditos ]);
                $this->form->addFields( [ new TLabel('Pagamentos')  ], [ $pagos ]);
                $this->form->addFields( [ new TLabel('Saldo')       ], [ $saldo ]);
                $this->form->addFields( [ $moeda ]);
            }

            // Despesas
            $dsp_descricao_1 = new TEntry('dsp_descricao_1');
            $dsp_valor_1     = new TEntry('dsp_valor_1');
            $dsp_descricao_2 = new TEntry('dsp_descricao_2');
            $dsp_valor_2     = new TEntry('dsp_valor_2');
            $dsp_descricao_3 = new TEntry('dsp_descricao_3');
            $dsp_valor_3     = new TEntry('dsp_valor_3');

            $dsp_valor_1->setInputType('number');
            $dsp_valor_2->setInputType('number');
            $dsp_valor_3->setInputType('number');

            $dsp_valor_1->setExitAction(new TAction( [ $this, 'onUpdateLeitura' ] , ['maquina'=>$maquinas]));
            $dsp_valor_2->setExitAction(new TAction( [ $this, 'onUpdateLeitura' ] , ['maquina'=>$maquinas]));
            $dsp_valor_3->setExitAction(new TAction( [ $this, 'onUpdateLeitura' ] , ['maquina'=>$maquinas]));

            // define some attributes
            $dsp_descricao_1->style = 'font-size: 15pt; height: 30px; width: 270px; text-align: left; autocomplete="off";';
            $dsp_valor_1->style     = 'font-size: 15pt; height: 30px; width: 100px; text-align: left; ';
            $dsp_descricao_2->style = 'font-size: 15pt; height: 30px; width: 270px; text-align: left; autocomplete="off";';
            $dsp_valor_2->style     = 'font-size: 15pt; height: 30px; width: 100px; text-align: center; ';
            $dsp_descricao_3->style = 'font-size: 15pt; height: 30px; width: 270px; text-align: left; autocomplete="off";';
            $dsp_valor_3->style     = 'font-size: 15pt; height: 30px; width: 100px; text-align: center; ';

            $this->form->appendPage('Despesas');
            $this->form->addFields( [ new TLabel('1) Despesa') ], [ $dsp_descricao_1 ]);
            $this->form->addFields( [ new TLabel('1) Valor')   ], [ $dsp_valor_1 ]);
            $this->form->addFields( [ new TLabel('2) Despesa') ], [ $dsp_descricao_2 ]);
            $this->form->addFields( [ new TLabel('2) Valor')   ], [ $dsp_valor_2 ]);
            $this->form->addFields( [ new TLabel('3) Despesa') ], [ $dsp_descricao_3 ]);
            $this->form->addFields( [ new TLabel('3) Valor')   ], [ $dsp_valor_3 ]);

            // Acerto

            $entrou = new TEntry('entrou');
            $pagou  = new TEntry('pagou');
            $sobrou = new TEntry('sobrou');
            $comissao = new TEntry('comissao');
            $apagar = new TEntry('apagar');
            $debitos = new TEntry('debitos');
            $valor_pago = new TEntry('v_pago');
            $cx_ant = new TEntry('cx_ant');
            $cx_atu = new TEntry('cx_atu');
            $deve_ant = new TEntry('deve_ant');
            $deve_atu = new TEntry('deve_atu');

            $entrou->setEditable(FALSE);
            $pagou->setEditable(FALSE);
            $sobrou->setEditable(FALSE);
            $comissao->setEditable(FALSE);
            $apagar->setEditable(FALSE);
            $debitos->setEditable(FALSE);
            $cx_ant->setEditable(FALSE);
            $cx_atu->setEditable(FALSE);
            $deve_ant->setEditable(FALSE);
            $deve_atu->setEditable(FALSE);

            $valor_pago->setInputType('tel');

            $cx_ant->setValue(number_format(  $point->caixa, 2, ',', '.'));
            $deve_ant->setValue(number_format( $point->deve , 2, ',', '.'));

            $valor_pago->setExitAction(new TAction( [ $this, 'onUpdateLeitura' ] , ['maquina'=>$maquinas]));

            // define some attributes
            $entrou->style     = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; background-color: #bfefff;';
            $pagou->style      = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; background-color: #ff6a6a; ';
            $sobrou->style     = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; background-color: #30ee90; ';
            $deve_ant->style   = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; background-color: #ffd39b; ';
            $deve_atu->style   = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; background-color: #30ee90; ';

            $comissao->style   = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; background-color: #ff6a6a; ';

            $debitos->style    = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; background-color: #ff6a6a;';

            $apagar->style     = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; background-color: #bfefff;';
            $valor_pago->style = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; ';
            $cx_ant->style     = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; ';
            $cx_atu->style     = 'font-size: 22pt; height: 40px; width: 300px; text-align: center; autocomplete="off"; ';

            $this->form->appendPage('Acerto');
            $this->form->addFields( [ new TLabel('ENTRADAS')       ], [ $entrou ]);
            $this->form->addFields( [ new TLabel('SAIDAS')         ], [ $pagou ]);
            $this->form->addFields( [ new TLabel('APURADO')        ], [ $sobrou ]);
            $this->form->addFields( [ new TLabel('SALDO ANTERIOR MÁQUINA') ], [ $deve_ant ]);
            $this->form->addFields( [ new TLabel('DESPESAS')       ], [ $debitos ]);
            $this->form->addFields( [ new TLabel('SALDO ATUAL')    ], [ $deve_atu ]);

            $this->form->addFields( [ new TLabel('', '#7D78B6', 12, 'bi')]);

            $this->form->addFields( [ new TLabel('COMISSÃO')       ], [ $comissao ]);

            $this->form->addFields( [ new TLabel('', '#7D78B6', 12, 'bi')]);

            $this->form->addFields( [ new TLabel('A PAGAR')         ], [ $apagar ]);
            $this->form->addFields( [ new TLabel('VALOR RECEBIDO(+)/PAGO(-)') ], [ $valor_pago ]);

            $this->form->addFields( [ new TLabel('', '#7D78B6', 12, 'bi')]);

            $this->form->addFields( [ new TLabel('SALDO ANTERIOR CAIXA') ], [ $cx_ant ]);
            $this->form->addFields( [ new TLabel('SALDO ATUAL CAIXA')    ], [ $cx_atu ]);

            // creates the action button
            $button1 = new TButton('ok');
            $button1->setAction(new TAction( [ $this, 'onOk' ], ['maquina'=>$maquinas]), 'OK');
            $button1->class = 'btn btn-warning btn-lg btn-block';

            // creates the action button
            $button2 = new TButton('add');
            $button2->setAction(new TAction( [ $this, 'onSalva' ] , ['maquina'=>$maquinas]), 'SALVAR');
            $button2->class = 'btn btn-success btn-lg btn-block';
            TButton::disableField('form_LeituraFinal', 'add');

            $this->form->addFields( [ $button1 ], [ $button2 ]);

        }

        // add the form inside the page
        parent::add($this->form);

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

    public static function onUpdateLeitura($param)
    {
        try {

//            var_dump($param);exit;

            $obj = new StdClass;
            $obj->entrou = 0;
            $obj->pagou = 0;
            $obj->sobrou = 0;
            foreach ($param['maquina'] as $key => $machine) {
                $ent_ant = $param['entant'.$key];
                $ent_atu = $param['entrada'.$key];
                $sai_ant = $param['saiant'.$key];
                $sai_atu = $param['saida'.$key];
                $moeda   = $param['moeda'.$key];
                if ($ent_atu == 0 or $ent_atu == NULL) {$ent_atu = $ent_ant;}
                if ($sai_atu == 0 or $sai_atu == NULL) {$sai_atu = $sai_ant;}
                $creditos = ($ent_atu - $ent_ant) * $moeda;
                if ($creditos < 0) {
                    throw new Exception('Entrada Menor que Anterior');
                };
                $pagos = ($sai_atu - $sai_ant) * $moeda;
                if ($pagos < 0) {
                    throw new Exception('Saida Menor que Anterior');
                };
                $saldo = ($creditos - $pagos);

                $obj->entrou += $creditos;
                $obj->pagou += $pagos;
                $obj->sobrou += $saldo;

                $obj->{'creditos' . $key} = number_format($creditos, 2, ',', '.');
                $obj->{'pagos' . $key} = number_format($pagos, 2, ',', '.');
                $obj->{'saldo' . $key} = number_format($saldo, 2, ',', '.');
            }

            $cx_anterior = $param['caixa'];
            $deve_anterior = $param['saldo'];
            if(empty($param['v_pago'])){
                $param['v_pago'] = 0;
            }
            $v_pago = $param['v_pago'];

            $tot_desp = 0;
            if($param['dsp_valor_1'] != NULL){$tot_desp += $param['dsp_valor_1'];}
            if($param['dsp_valor_2'] != NULL){$tot_desp += $param['dsp_valor_2'];}
            if($param['dsp_valor_3'] != NULL){$tot_desp += $param['dsp_valor_3'];}

            $apurado = $obj->entrou - $obj->pagou;

            $deve_atu = $apurado + $deve_anterior - $tot_desp;
            if($deve_atu < 0){$comissao = 0;}else{$comissao = $deve_atu * ($param['porc']/100);}

            $apagar = $deve_atu - $comissao;
            if($deve_atu < 0 and $deve_anterior < 0){
                $apagar -= $deve_anterior;
            }

            if($deve_anterior < 0 and $apagar > 0 and $deve_atu > 0){
                $apagar += ($deve_anterior * -1);
            }

            if($v_pago == null){$v_pago = 0;}
            $cx_atual = $cx_anterior - $apagar + $v_pago;

            $obj->entrou   = number_format($obj->entrou, 2, ',', '.');
            $obj->pagou    = number_format($obj->pagou, 2, ',', '.');
            $obj->sobrou   = number_format($obj->sobrou, 2, ',', '.');
            $obj->deve_ant = number_format( $deve_anterior, 2, ',', '.');
            $obj->debitos  = number_format( $tot_desp, 2, ',', '.');
            $obj->deve_atu = number_format( $deve_atu, 2, ',', '.');
            $obj->comissao = number_format( $comissao, 2, ',', '.');
            $obj->apagar   = number_format( $apagar, 2, ',', '.');
            $obj->cx_ant   = number_format( $cx_anterior, 2, ',', '.');
            $obj->cx_atu   = number_format( $cx_atual, 2, ',', '.');

            TForm::sendData('form_LeituraFinal', $obj);
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    public static function Salva($param)
    {
        try
        {
            $hoje = date('Y-m-d H:i:s');
            TTransaction::open('jackpot');

            // Salva Movimento
            $record = new Movimento;
            $record->dia           = $hoje;
            $record->entrada       = self::formatMoneyDb($param['entrou']);
            $record->saida         = self::formatMoneyDb($param['pagou']);
            $record->deve_anterior = self::formatMoneyDb($param['deve_ant']);
            $deve_atual            = self::formatMoneyDb($param['deve_atu']);
            if($deve_atual > 0){$deve_atual = 0;}
            $record->deve_atual    = $deve_atual;
            $record->comissao      = self::formatMoneyDb($param['comissao']);
            $record->despesas      = self::formatMoneyDb($param['debitos']);
            if($param['v_pago'] == null){$param['v_pago'] = 0;}
//            $record->pago          = self::formatMoneyDb($param['v_pago']);
            $record->pago          = $param['v_pago'];
            $record->cx_anterior   = self::formatMoneyDb($param['cx_ant']);
            $record->cx_atual      = self::formatMoneyDb($param['cx_atu']);
            $record->usuario = TSession::getValue('userid');
            $record->id_ponto = $param['ponto'];
            $record->store();
            $registro  = Movimento::last();
            $proximo = $registro->id;

            // Salva Leituras
            foreach ($param['maquina'] as $key => $machine) {
                $numero  =  $key;
                $ent_ant = $param['entant'.$key];
                $ent_atu = $param['entrada'.$key];
                $sai_ant = $param['saiant'.$key];
                $sai_atu = $param['saida'.$key];
                $moeda   = $param['moeda'.$key];
                if ($ent_atu == 0 or $ent_atu == NULL) {$ent_atu = $ent_ant;}
                if ($sai_atu == 0 or $sai_atu == NULL) {$sai_atu = $sai_ant;}
                $creditos = ($ent_atu - $ent_ant) * $moeda;
                if ($creditos < 0) {
                    throw new Exception('Entrada Menor que Anterior');
                };
                $pagos = ($sai_atu - $sai_ant) * $moeda;
                if ($pagos < 0) {
                    throw new Exception('Saida Menor que Anterior');
                };
                $saldo = ($creditos - $pagos);

                if($creditos > 0) {
                    $obj = new Leitura;
                    $obj->dia = $hoje;
                    $obj->maquina = $numero;
                    $obj->id_ponto = $param['ponto'];
                    $obj->ini_entra = $ent_ant;
                    $obj->ini_sai = $sai_ant;
                    $obj->fim_entra = $ent_atu;
                    $obj->fim_sai = $sai_atu;
                    $obj->credito = $moeda;
                    $obj->usuario = TSession::getValue('userid');
                    $obj->id_movi = $proximo;
                    $obj->store();
                    $obj = new Maquina($numero);
                    $obj->last_visita = $hoje;
                    $obj->store();
                }
            }

            // Salva Saldo
            $obj = new Ponto($param['ponto']);
            $obj->deve  = $deve_atual;
            $obj->caixa = self::formatMoneyDb($param['cx_atu']);
            $obj->last_visita = $hoje;
            $obj->store();

            // Salva despesas
            if($param['dsp_valor_1'] != NULL){
                $obj = new Despesa;
                $obj->dia = $hoje;
                $obj->id_ponto = $param['ponto'];
                $obj->id_movi = $proximo;
                if($param['dsp_descricao_1'] == NULL){
                    throw new Exception('Falta descrição da Despesa 1');
                } else {
                    $obj->descricao = $param['dsp_descricao_1'];
                }
                $obj->valor = $param['dsp_valor_1'];
                $obj->usuario = TSession::getValue('userid');
                $obj->store();
            }
            if($param['dsp_valor_2'] != NULL){
                $obj = new Despesa;
                $obj->dia = $hoje;
                $obj->id_ponto = $param['ponto'];
                $obj->id_movi = $proximo;
                if($param['dsp_descricao_2'] == NULL){
                    throw new Exception('Falta descrição da Despesa 2');
                } else {
                    $obj->descricao = $param['dsp_descricao_2'];
                }
                $obj->valor = $param['dsp_valor_2'];
                $obj->usuario = TSession::getValue('userid');
                $obj->store();
            }
            if($param['dsp_valor_3'] != NULL){
                $obj = new Despesa;
                $obj->dia = $hoje;
                $obj->id_ponto = $param['ponto'];
                $obj->id_movi = $proximo;
                if($param['dsp_descricao_3'] == NULL){
                    throw new Exception('Falta descrição da Despesa 3');
                } else {
                    $obj->descricao = $param['dsp_descricao_3'];
                }
                $obj->valor = $param['dsp_valor_3'];
                $obj->usuario = TSession::getValue('userid');
                $obj->store();
            }

            // close the transaction
            TTransaction::close();

            // shows the success message
            new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));

            TApplication::loadPage('Escolhe');


        } catch (Exception $e){
            new TMessage('error', $e->getMessage());

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

    public static function onSalva($param)
    {
        // define the delete action
        $action = new TAction(array('LeituraForm', 'Salva'));
        $action->setParameters($param); // pass the key parameter ahead

        // shows a dialog to the user
        new TQuestion('Confirma o fechamento da leitura ?', $action);
    }

    public static function onOk()
    {
        TButton::enableField('form_LeituraFinal', 'add');
        TButton::disableField('form_LeituraFinal', 'ok');
    }

    /**
     * @param $str
     *
     * @return null|string|string[]
     */
    public static function onlyNumbers($str)
    {
        $str = str_replace('.', '', $str);
        $str = str_replace(',', '.', $str);
        return $str;
    }

    /**
     * @param $str
     * @return string
     */
    public static function formatMoneyDb($str)
    {
        $str = str_replace('.', '', $str);
        $str = str_replace(',', '.', $str);
        return $str;
    }
}



