<?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\Wrapper\TDBCombo;

class LeiCorrForm extends TPage
{
    public function __construct($param)
    {
        parent::__construct();
        new TSession;

        $this->dias = array();

        // creates the items form and add a table inside
        $this->form_item = new TForm('form_atendente');
        $this->form_item->class = 'tform';
        $table = new TTable;
        $table-> width = '100%';
        $this->form_item->add($table);

        $maquina_id = new TEntry('maquina_id');
        $maquina_id->setValue($param['maquina_id']);
        $maquina_id->style = 'font-size: 23pt; height: 40px; width: 140px; text-align: center; autocomplete="off";';
        $maquina_id->setEditable(FALSE);

        $this->dia_view = new TCombo('dia_view');
        $this->dia_view->style = 'font-size: 17pt; height: 30px; text-align: center;';
        $this->dia_view->setChangeAction(new TAction(array($this, 'onExitDia')));

        $entrada  = new TEntry('entrada');
        $saida    = new TEntry('saida');
        $entant   = new TEntry('entant');
        $saiant   = new TEntry('saiant');

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

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

        // define some attributes
        $entrada->style = 'font-size: 26pt; height: 60px; width: 270px; text-align: center; autocomplete="off";';
        $saida->style = 'font-size: 26pt; height: 60px; width: 270px; text-align: center; autocomplete="off";';
        $entant->style = 'font-size: 26pt; height: 60px; width: 270px; text-align: center; background-color: #ffff99; ';
        $saiant->style = 'font-size: 26pt; height: 60px; width: 270px; text-align: center; background-color: #ffff99; ';

        $entant->setInputType('tel');
        $saiant->setInputType('tel');
        $entrada->setInputType('tel');
        $saida->setInputType('tel');

        // add a row for the form title
        $row  = $table->addRow();
        $row->class = 'tformtitle'; // CSS class
        $row->addCell( new TLabel('CORREÇÃO DE LEITURA'))->style = 'text-align: center; width:100%;';

        // create the field labels
        $lab_maq = new TLabel('MÁQUINA');
        $lab_maq->setFontSize(17);
        $lab_maq->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';

        // add the form fields
        $table->addRowSet($lab_maq)->style = 'text-align: center;';
        $table->addRowSet($maquina_id)->style = 'text-align: center;';
        $table->addRowSet($this->dia_view)->style = 'text-align: center;';
        $table->addRowSet($entant)->style = 'text-align: center;';
        $table->addRowSet($entrada)->style = 'text-align: center;';
        $table->addRowSet($saiant)->style = 'text-align: center;';
        $table->addRowSet($saida)->style = 'text-align: center;';
        $table->addRowSet('');
        $table->addRowSet(array($button1))->style = 'text-align: center;';

        // define the form fields
        $this->form_item->setFields(array($maquina_id, $this->dia_view, $entrada, $entant, $saida, $saiant, $button1));

        // create the datagrid
        $this->datagrid = new TQuickGrid;
        $this->datagrid->addQuickColumn('Inicial (E)', 'ini_entra', 'right', "15%");
        $this->datagrid->addQuickColumn('Inicial (S)', 'ini_sai', 'right', "15%");
        $this->datagrid->addQuickColumn('Final (E)', 'fim_entra', 'right', "15%");
        $this->datagrid->addQuickColumn('Final (S)', 'fim_sai', 'right', "15%");
        $this->datagrid->addQuickColumn('Fechado', 'fechado', 'center', "40%");
        $this->datagrid->createModel();

        // create the datagrid
        $this->datagrid1 = new TQuickGrid;
        $this->datagrid1->addQuickColumn('Dia', 'dia', 'right', "30%", new TAction(array($this, 'onReload')), array('order', 'ini_entra'));
        $this->datagrid1->addQuickColumn('Validação', 'descricao', 'right', "20%", new TAction(array($this, 'onReload')), array('order', 'ini_sai'));
        $valor = $this->datagrid1->addQuickColumn('Valor', 'valor', 'right', "20%", new TAction(array($this, 'onReload')), array('order', 'fim_entra'));
        $this->datagrid1->addQuickColumn('Fechado', 'fechado', 'center', "30%", new TAction(array($this, 'onReload')), array('order', 'fechado'));
        $this->datagrid1->createModel();

        $this->onReload(array(0=>$maquina_id->getValue()));

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
        $vbox->add($this->form_item);
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        $vbox->add($this->datagrid1)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        parent::add($vbox);
    }

    function onReload($param = NULL)
    {
        try
        {
            $maquina = $param[0];
            TTransaction::open('unit_database');
            $leituras = leitura::where('maquina', '=', $maquina)->orderBy('id','desc')->take(10)->load();
            foreach ($leituras as $read){
                if($read->fechado == null){
                    $this->dias[$read->id] = "CAIXA ATUAL";
                }else{
                    $this->dias[$read->id] = $read->fechado;
                }
            }
            asort($leituras);
            $this->datagrid->clear();
            $this->datagrid->addItems($leituras);
            asort($this->dias);
            $this->dia_view->addItems($this->dias);

            $movimento = movimento::where('maquina', '=', $maquina)->orderBy('id','desc')->take(10)->load();
            $this->datagrid1->clear();
            asort($movimento);
            if ($movimento){
                foreach ($movimento as $registro){$this->datagrid1->addItem($registro);}
            }

            TTransaction::close();

            // close the transaction
            $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();
        }
    }

    public function onSave()
    {
        try
        {
            $this->form_item->validate(); // validate form data
            $data = $this->form_item->getData();
            TTransaction::open('unit_database');
            foreach ($this->dias as $id=>$fecha){
                if($id < $data->dia_view){
                    continue;
                }
                if($id == $data->dia_view){
                    $leitura = new leitura($id);
                    $leitura->fim_entra = $data->entrada;
                    $leitura->fim_sai = $data->saida;
                    $leitura->store();
                }
                if($id > $data->dia_view){
                    $leitura = new leitura($id);
                    if($leitura->ini_entra == $data->entant){
                        $leitura->ini_entra = $data->entrada;
                    }
                    if($leitura->ini_sai == $data->saiant){
                        $leitura->ini_sai = $data->saida;
                    }
                    if($leitura->fim_entra == $data->entant){
                        $leitura->fim_entra = $data->entrada;
                    }
                    if($leitura->fim_sai == $data->saiant){
                        $leitura->fim_sai = $data->saida;
                    }
                    $leitura->store();
                }
            }
            TTransaction::close();
            $maquina=$data->maquina_id;
            $this->form_item->clear(); // clear form
            TToast::show('info', 'Leitura Atualizada', 'top right', 'far:check-circle' );
            TApplication::gotoPage('LeiCorrForm',NULL, array('maquina_id'=>$maquina));
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    public static function onExitDia($param)
    {
        try
        {
            TTransaction::open('unit_database');
            $leitura = new leitura($param['key']);
            $obj = new StdClass;
            $obj->entant   = $leitura->fim_entra;
            $obj->saiant   = $leitura->fim_sai;
            $obj->entrada  = $leitura->fim_entra;
            $obj->saida    = $leitura->fim_sai;
            TTransaction::close();
            TForm::sendData('form_atendente', $obj);
            TScript::create('$("input[name=\'entrada\']").focus();');
        }
        catch (Exception $e)
        {
            // does nothing
        }
    }


}