<?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 LeiInicialForm extends TPage
{
    public function __construct()
    {
        parent::__construct();
        new TSession;

        // 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 TDBCombo('maquina_id','unit_database','maquina','id','id','id');
        $maquina_id->setChangeAction(new TAction(array($this, 'onExitMaquina')));

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

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

        $entant->setEditable(FALSE);
        $saiant->setEditable(FALSE);

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

        // add validators
        $maquina_id->addValidation('Máquina', new TRequiredValidator);

        // define some attributes
        $maquina_id->style = 'font-size: 23pt; height: 40px; width: 140px; text-align: center; autocomplete="off";';
        $tipo->style = 'font-size: 16pt; height: 40px; width: 270px; text-align: center; background-color: #FF0000;';
        $entrada->style = 'font-size: 28pt; height: 60px; width: 270px; text-align: center; autocomplete="off";';
        $entant->style = 'font-size: 28pt; height: 60px; width: 270px; text-align: center; background-color: #ffff99; ';
        $saida->style = 'font-size: 28pt; height: 60px; width: 270px; text-align: center; autocomplete="off";';
        $saiant->style = 'font-size: 28pt; height: 60px; width: 270px; text-align: center; background-color: #ffff99; ';

        $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('LEITURA INICIAL DO CAIXA'))->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($tipo)->style = 'text-align: center;';
        $table->addRowSet($entant)->style = 'text-align: center;';
        $table->addRowSet($saiant)->style = 'text-align: center;';
        $table->addRowSet($entrada)->style = 'text-align: center;';
        $table->addRowSet($saida)->style = 'text-align: center;';
        $table->addRowSet($registro)->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, $tipo, $entrada, $entant, $saida, $saiant, $registro, $button1));

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
        $vbox->add($this->form_item);
        parent::add($vbox);
    }
    /**
     * Saves the cart
     */
    public function onSave()
    {
        try
        {
            TTransaction::open('unit_database');
            $equips = config::getConfig('equips');
            TTransaction::close();

            $this->form_item->validate(); // validate form data
            $data = $this->form_item->getData();
            $alterada = 1;
            if($data->entrada == NULL AND $data->saida == NULL){$alterada=0;}
            if($data->entrada == NULL){$data->entrada = $data->entant;}
            if($data->saida == NULL){$data->saida = $data->saiant;}
            if($data->entrada < 0){$data->entrada = $data->entrada + $data->entant;}
            if($data->saida < 0){$data->saida = $data->saida + $data->saiant;}
            TTransaction::open('unit_database');
            $leitura = new leitura($data->registro);
            $leitura->ini_entra = $data->entrada;
            $leitura->fim_entra = $data->entrada;
            $leitura->ini_sai = $data->saida;
            $leitura->fim_sai = $data->saida;
            $leitura->ok = 2;
            $leitura->store();
            $this->form_item->clear(); // clear form
            if($alterada){
                TToast::show('info', 'Leitura Salva com Sucesso', 'top right', 'far:check-circle' );
//                SystemNotification::register( 2, 'Alteração de Leitura Inicial', 'A Leitura Inicial da Máquina '.$data->maquina_id.' foi alterada', 'class=LoginForm&method=reloadPermissions&static=1', 'OK', 'fa fa-pencil-square-o blue' );
            }
            $object = new config;
            $object->{'id'}    = 'Reabre';
            $object->{'value'} = 0;
            $object->store();
            TTransaction::close();

            if($leitura->maquina < $equips){
                $obj = new StdClass;
                $obj->maquina_id = $leitura->maquina+1;
                $this->form_item->setData($obj);
                TForm::sendData('form_atendente', $obj);
            }
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    /**
     * Exit action for the field product
     * Fill some form fields (sale_price, amount, discount, total)
     */
    public static function onExitMaquina($param)
    {
        try
        {
            $codigo = $param['maquina_id']; // get the product code
            TTransaction::open('unit_database');
            $criteria = new TCriteria();
            $criteria->add(new TFilter('maquina', '=', $codigo));
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $repository = new TRepository('leitura');
            $machine = $repository->load($criteria);
            $item = $machine[0];
            $tipo = new maquina($item->maquina);
            $leitura = new leitura($item->id);
            $registro = $item->id;
            $obj = new StdClass;
            $obj->entant   = $leitura->fim_entra;
            $obj->saiant   = $leitura->fim_sai;
            $obj->registro = $registro;
            $obj->tipo = $tipo->tipo.' ('.$tipo->credito.')';
            TTransaction::close();
            TForm::sendData('form_atendente', $obj);
            TScript::create('$("input[name=\'entrada\']").focus();');
        }
        catch (Exception $e)
        {
            // does nothing
        }
    }

}