<?php
use Adianti\Control\TAction;
use Adianti\Control\TPage;
use Adianti\Database\TTransaction;
use Adianti\Widget\Container\TVBox;
use Adianti\Widget\Dialog\TMessage;
use Adianti\Widget\Form\TEntry;
use Adianti\Widget\Form\THidden;

class MaquinaForm extends TPage
{
    protected $form; // form
    protected $program_list;

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

        // creates the form
        $this->form = new BootstrapFormBuilder('form_Maquina');
        $this->form->setFormTitle( 'Máquinas' );
        // create the form fields
        $id          = new TEntry('id');
        $tipo        = new TEntry('tipo');
        $credito     = new TEntry('credito');
        $ilha        = new TEntry('ilha');
        $fabricante  = new TEntry('fabricante');
        $porcento    = new TEntry('porcento');
        $leitura     = new TEntry('leitura');
        $sangria     = new THidden('sangria');

        $tipo->forceUpperCase();

        $btn = $this->form->addAction( _t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o');
        $btn->class = 'btn btn-sm btn-primary';
        $this->form->addAction( _t('Clear'), new TAction(array($this, 'onEdit')), 'fa:eraser red');
        $this->form->addAction( _t('Back'), new TAction(array('MaquinaList','onReload')), 'fa:arrow-circle-o-left blue');

        /* define the sizes
        $id->setSize('50%');
        $tipo->setSize('100%');
        $credito->setSize('100%');
        $ilha->setSize('100%');
        $fabricante->setSize('100%');
        $porcento->setSize('100%');
        $leitura->setSize('100%');
        */

        // outros
        $id->setEditable(false);

        // validations
        $tipo->addValidation('Tipo de Máquina', new TRequiredValidator);
        $credito->addValidation('Crédito', new TRequiredValidator);
        $ilha->addValidation('Ilha', new TRequiredValidator);
        $fabricante->addValidation('Fabricante', new TRequiredValidator);
        $porcento->addValidation('Comissão', new TRequiredValidator);
        $leitura->addValidation('Leitura', new TRequiredValidator);

        $this->form->addFields( [new TLabel('Máquina')], [$id] );
        $this->form->addFields( [new TLabel('Tipo de Máquina')], [$tipo]);
        $this->form->addFields( [new TLabel('Crédito (0,01) (0,05) (0,25)')], [$credito]);
        $this->form->addFields( [new TLabel('Ilha')], [$ilha]);
        $this->form->addFields( [new TLabel('Fabricante')], [$fabricante]);
        $this->form->addFields( [new TLabel('Comissão')], [$porcento]);
        $this->form->addFields( [new TLabel('Leitura 0=Livre 1=Seq 2=Créd*4 3=Créd*100')], [$leitura]);
        $this->form->addFields( [$sangria]);

        $container = new TVBox;
        $container->style = 'width: 90%';
        $container->add($this->form);

        // add the container to the page
        parent::add($container);

    }

    /**
     * method onSave()
     * Executed whenever the user clicks at the save button
     */
    public function onSave($param)
    {

//        var_dump($param);exit;

        try
        {
            // open a transaction with database 'permission'
            TTransaction::open('unit_database');
            $maquina = new maquina;
            $maquina->fromArray( $param );
            $maquina->credito = str_replace(',', '.', $maquina->credito);
            $maquina->sangria = 904;
            $maquina->store();

            // Salva Leitura Nova
            if(TSession::getValue('maquina_nova')){
                $obj = new leitura;
                $obj->dia = date('Y-m-d H:i:s');;
                $obj->maquina = $maquina->id;
                $obj->id_ponto = $maquina->id_ponto;
                $obj->ini_entra=0;
                $obj->fim_entra=0;
                $obj->ini_sai=0;
                $obj->fim_sai=0;
                $obj->credito = $maquina->credito;
                $obj->fabricante = $maquina->fabricante;
                $obj->porcento = $maquina->porcento;
                $obj->usuario = TSession::getValue('userid');
                $obj->sangria = 904;
                $obj->id_movi = 0;
                $obj->store();
                config::setConfig('equips', $maquina->id);
                TToast::show('success', 'Total de Máquinas Atualizado', 'top right', 'far:check-circle' );

            } else {
                $codigo = $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];
                    $leitura = new leitura($item->id);
                    $leitura->credito = $maquina->credito;
                    $leitura->fabricante = $maquina->fabricante;
                    $leitura->porcento = $maquina->porcento;
                    $leitura->store();
                }
                catch (Exception $e)
                {
                    // does nothing
                }

            }

//            $data = new stdClass;
//            $data->id = $maquina->id;
//            TForm::sendData('form_Maquina', $data);

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

            // shows the success message
            TToast::show('success', 'Registro Salvo com Sucesso', 'top right', 'far:check-circle' );

            TApplication::loadPage('MaquinaList','onReload');

        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());

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

    /**
     * method onEdit()
     * Executed whenever the user clicks at the edit button da datagrid
     */
    function onEdit($param)
    {
        try
        {
            if (isset($param['key']))
            {
                TSession::setValue('maquina_nova', 0);

                // get the parameter $key
                $key=$param['key'];

                // open a transaction with database 'permission'
                TTransaction::open('unit_database');

                // instantiates object System_user
                $maquina = new maquina($key);

                // fill the form with the active record data
                $this->form->setData($maquina);

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

            }
            else
            {
                $this->form->clear();
                $maquina = new maquina;
                $maquina->fabricante = 'CASA';
                $maquina->porcento = 0;
                $maquina->leitura = 0;
                $this->form->setData($maquina);
                TSession::setValue('maquina_nova', 1);

            }
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());

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