<?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 LeiTesteForm extends TPage
{
    protected $form; // form
    private $frameFoto;
    private $frameFotoWebCan;

    /**
     * Class constructor
     * Creates the page and the registration form
     */
    function __construct()
    {
        parent::__construct();

        // creates the form
        $this->form = new BootstrapFormBuilder('form_atendente');
        $this->form->setFormTitle('Leitura Final');
        $this->form->setFieldSizes('100%');

        // create the form fields
        $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');
        $moeda    = new THidden('moeda');

        $entrada->placeholder = 'Entrada Atual';
        $saida->placeholder = 'Saída Atual';
        $tipo->placeholder = 'Máquina';

        $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: #87CEFF;';
        $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 FINAL DO CAIXA'))->style = 'text-align: center; width:100%;';

        // create the field labels
        $lab_maq = new TLabel('MÁQUINA');
        $lab_maq->setFontSize(12);
        $lab_maq->setFontFace('Trebuchet MS');

        $lab_tip = new TLabel('TIPO');
        $lab_tip->setFontSize(12);
        $lab_tip->setFontFace('Trebuchet MS');

        $lab_enta = new TLabel('ENTRADA ANTERIOR');
        $lab_enta->setFontSize(12);
        $lab_enta->setFontFace('Trebuchet MS');
        $lab_enta->setFontColor('red');

        $lab_ent = new TLabel('ENTRADA ATUAL');
        $lab_ent->setFontSize(12);
        $lab_ent->setFontFace('Trebuchet MS');

        $lab_sai = new TLabel('SAIDA ATUAL');
        $lab_sai->setFontSize(12);
        $lab_sai->setFontFace('Trebuchet MS');

        $lab_saia = new TLabel('SAIDA ANTERIOR');
        $lab_saia->setFontSize(12);
        $lab_saia->setFontFace('Trebuchet MS');
        $lab_saia->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';

        // add one row for each form field
        $this->form->addFields( [ $maquina_id ]);
        $this->form->addFields( [ $tipo ]);
        $this->form->addFields( [ $entant ]);
        $this->form->addFields( [ $entrada ]);
        $this->form->addFields( [ $saiant ]);
        $this->form->addFields( [ $saida ]);
        $this->form->addFields( [ $registro ]);
        $this->form->addFields( [ $moeda ]);


        // create the form actions
        $btn = $this->form->addAction( _t('Save'), new TAction([$this, 'onSave']), 'fa:floppy-o' );
        $btn->class = 'btn btn-success btn-lg btn-block';

        $btn = $this->form->addAction( 'Foto', new TAction([$this, 'onFoto']), 'fa:camera' );
        $btn->class = 'btn btn-success btn-lg btn-block';
//        $btnNovo = $this->form->addAction( _t('New'), new TAction([$this, 'onEdit']), 'fa:eraser red' );
//        $this->form->addAction( _t('Back to the listing'), new TAction(['PessoasList', 'onReload']), 'fa:table blue' );
//        $this->form->addHeaderAction( _t('Save'), new TAction([$this, 'onSave']), 'fa:save green' );
//        $this->form->addHeaderAction( _t('Back'), new TAction(['PessoasList', 'onReload']), 'fa:table blue' );

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

        // add the columns
        $column = $this->datagrid->addQuickColumn('Máquina','maquina','center', "20%", new TAction(array($this, 'onReload')), array('order', 'maquina'));
        $column1 = $this->datagrid->addQuickColumn('Entrada', 'fim_entra', 'right', "40%", new TAction(array($this, 'onReload')), array('order', 'fim_entra'));
        $column2 = $this->datagrid->addQuickColumn('Saida', 'fim_sai', 'right', "40%", new TAction(array($this, 'onReload')), array('order', 'fim_sai'));

        $column->setTransformer( function($value, $object, $row) {
            $div = new TElement('span');
            $div->class="label label-{$value}";
            $div->style="text-shadow:none; font-size:19px; color:black";
            $div->add($object->maquina);
            return $div;
        });
        $column1->setTransformer( function($value, $object, $row) {
            $div = new TElement('span');
            $div->class="label label-{$value}";
            $div->style="text-shadow:none; font-size:19px; color:black";
            $div->add($object->fim_entra);
            return $div;
        });
        $column2->setTransformer( function($value, $object, $row) {
            $div = new TElement('span');
            $div->class="label label-{$value}";
            $div->style="text-shadow:none; font-size:19px; color:black";
            $div->add($object->fim_sai);
            return $div;
        });

        $this->datagrid->addQuickAction('Entrada', new TDataGridAction(array($this, 'onEdit')),   'id', 'fa:edit');

        // create the datagrid model
        $this->datagrid->createModel();
        $this->onReload();


        // wrap the page content
        $vbox = new TVBox;
        $vbox->style = 'width: 98%';
        $vbox->add($this->form);
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;overflow-x:auto;';

        // add the form inside the page
        parent::add($vbox);
    }
    /**
     * Saves the cart
     */
    public function onSave()
    {
        try
        {
            TTransaction::open('unit_database');
            $equips = config::getConfig('equips');
            TTransaction::close();

            $this->form->validate(); // validate form data
            $data = $this->form->getData();

            if($data->maquina_id != 0 and $data->maquina_id != NULL){
                // Testa Leitura Menor que a Anterior
                if($data->entrada == NULL){$data->entrada = $data->entant;}
                if($data->saida == NULL){$data->saida = $data->saiant;}
                if($data->entrada < $data->entant or $data->saida < $data->saiant){throw new Exception('Leitura Menor que Anterior');};
                // Testa Centavo
                $cal_ent = ($data->entrada - $data->entant) * $data->moeda;
                if($cal_ent != intval($cal_ent)){
                    throw new Exception('Entrada com centavos esta incorreta');
                }
                // Testa Foto
                if($data->fotoWebcam == ""){
                    throw new Exception('Leitura sem Foto');
                }
                // Testa Saida sem Entrada
//                if($data->entrada == $data->entant and $data->saida <> $data->saiant){
//                    throw new Exception('Impossível Saída sem Entrada');
//                }

                TTransaction::open('unit_database');
                $leitura = new leitura($data->registro);
                $leitura->fim_entra = $data->entrada;
                $leitura->fim_sai = $data->saida;
                $leitura->ok = 1;
                if($leitura->maquina != 0) {
                    $leitura->store();
                }

                $criteria = new TCriteria();
                $criteria->add(new TFilter('fechado', 'IS', NULL));
                $criteria->add(new TFilter('usuario', '<>', 0));
                $criteria->setProperty('order', 'id');
                $criteria->setProperty('limit' , 1);
                $repository = new TRepository('movimento');
                $result = $repository->load($criteria);
                $diaFecha = $result[0]->dia;
                $casa=config::getConfig('titulo');

                $object = new config;
                $object->{'id'}    = 'Reabre';
                $object->{'value'} = 0;
                $object->store();

                TTransaction::close();

                if ( $data->fotoWebcam != '' )
                {
                    $img = $data->fotoWebcam;
                    $img = str_replace('data:image/jpeg;base64,', '', $img);
                    $img = str_replace(' ', '+', $img);
                    $data = base64_decode($img);

                    $f = $casa.'_'.$diaFecha.'_'.$leitura->maquina.'.jpg';
//                $f = $casa.'_'.$diaFecha.'_'.$leitura->maquina.'_'.date("Y-m-d H:i:s");

                    $success = file_put_contents('app/images/leituras/' . $f, $data);
                }

                $this->form->clear(); // clear form
                TToast::show('info', 'Leitura Atualizada', 'top right', 'far:check-circle' );
            }
            $this->onReload();

            if($leitura->maquina < $equips){
                $obj = new StdClass;
                $obj->maquina_id = $leitura->maquina+1;
                TForm::sendData('form_atendente', $obj);
            }

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

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

            $criteria->setProperties($newparam); // order, offset

            $criteria->add(new TFilter('ok', '!=', 1));
            $criteria->add(new TFilter('fechado', 'IS', NULL));

            $customers = $repository->load($criteria, FALSE);
            $this->datagrid->clear();

            if ($customers)
            {
                foreach ($customers as $customer)
                {
                    $this->datagrid->addItem($customer);
                }
            }

            // reset the criteria for record count
            $criteria->resetProperties();
            $count= $repository->count($criteria);
            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 static function onExitMaquina($param)
    {
        $codigo = $param['maquina_id']; // get the product code
        try
        {
            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->ini_entra;
            $obj->saiant   = $leitura->ini_sai;
            $obj->registro = $registro;
            $obj->moeda = $item->credito;
            $obj->tipo = $tipo->tipo.' ('.$tipo->credito.')';
            TTransaction::close();
            TForm::sendData('form_atendente', $obj);
            TScript::create('$("input[name=\'entrada\']").focus();');
        }
        catch (Exception $e)
        {
            // does nothing
        }
    }

    public function onEdit($param)
    {
        try
        {
            // open a transaction with database
            TTransaction::open('unit_database');

            $leitura = new leitura($param['key']);
            $obj = new StdClass;
            $obj->maquina_id = $leitura->maquina;
            TTransaction::close();
            TForm::sendData('form_atendente', $obj);

            return $leitura;
        }
        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 onFoto($param)
    {
        AdiantiCoreApplication::loadPage('Foto');
//        TApplication::gotoPage('Foto');
    }
}