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

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');
        $ponto       = new TDBCombo('id_ponto','jackpot','Ponto','id','nome', 'nome');
        $tipo        = new TEntry('tipo');
        $credito     = new TEntry('credito');
        $entrada     = new TEntry('entrada');
        $saida       = new TEntry('saida');

        $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%');
        $ponto->setSize('100%');
        $tipo->setSize('100%');
        $credito->setSize('100%');
        $entrada->setSize('100%');
        $saida->setSize('100%');

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

        // validations
        $ponto->addValidation('ponto', new TRequiredValidator);
        $tipo->addValidation('tipo', new TRequiredValidator);
        $credito->addValidation('credito', new TRequiredValidator);

        $this->form->addFields( [new TLabel('ID')], [$id] );
        $this->form->addFields( [new TLabel('Ponto')], [$ponto]);
        $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('Entrada Atual')], [$entrada]);
        $this->form->addFields( [new TLabel('Saida Atual')], [$saida]);

        $container = new TVBox;
        $container->style = 'width: 90%';
        $container->add(new TXMLBreadCrumb('menu.xml', 'MaquinaList'));
        $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 static function onSave($param)
    {

//        var_dump($param);exit;

        try
        {
            // open a transaction with database 'permission'
            TTransaction::open('jackpot');

            $object = new Maquina;
            $object->fromArray( $param );
            $object->credito = str_replace(',', '.', $object->credito);
            $object->store();

            // Salva Leitura Nova
            if(TSession::getValue('maquina_nova')){
                $obj = new Leitura;
                $obj->dia = date('Y-m-d H:i:s');;
                $obj->maquina = $object->id;
                $obj->id_ponto = $object->id_ponto;
                if(!$param['entrada']){
                    $obj->ini_entra=0;
                    $obj->fim_entra=0;
                } else {
                    $obj->ini_entra = $param['entrada'];
                    $obj->fim_entra = $param['entrada'];
                }
                if(!$param['saida']){
                    $obj->ini_sai=0;
                    $obj->fim_sai=0;
                } else {
                    $obj->ini_sai = $param['saida'];
                    $obj->fim_sai = $param['saida'];
                }
                $obj->credito = $object->credito;
                $obj->usuario = TSession::getValue('userid');
                $obj->id_movi = 0;
                $obj->store();
            }

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

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

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

            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']))
            {
                TEntry::disableField('form_Maquina', 'entrada');
                TEntry::disableField('form_Maquina', 'saida');
                TSession::setValue('maquina_nova', 0);

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

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

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

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

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

            }
            else
            {
                $this->form->clear();
                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();
        }
    }
}
