<?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\TForm;
use Adianti\Widget\Form\TLabel;
use Adianti\Wrapper\BootstrapFormBuilder;

class FuncioFormView extends TPage
{
    private $form; // form
    private $table_contacts;

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

        // creates the form
        $this->form = new BootstrapFormBuilder('form_customer');
        $this->form->setFormTitle('Cadastro de Funcionários');

        // create the form fields
        $id     = new TEntry('id');
        $name   = new TEntry('nome');
        $limite = new TEntry('limite');
        $tipo   = new TEntry('tipo');
        $saldo  = new TEntry('saldo');

        // define some properties for the form fields
        $id->setEditable(FALSE);
        $id->setSize(100);
        $name->setSize(320);
        $limite->setValue(0);
        if((in_array('1', TSession::getValue('usergroupids'))) or
            (in_array('2', TSession::getValue('usergroupids')))
            or (in_array('3', TSession::getValue('usergroupids')))
            or (in_array('4', TSession::getValue('usergroupids')))) {
            $limite->setEditable(TRUE);
        } else {
            $limite->setEditable(FALSE);
        }

        $this->form->addFields( [ new TLabel('Código') ],     [ $id ] );
        $this->form->addFields( [ new TLabel('Nome') ],     [ $name ] );
        $this->form->addFields( [ new TLabel('Limite') ],  [ $limite ] );
        $this->form->addFields( [ new THidden('saldo') ]);
        $this->form->addFields( [ new THidden('tipo') ]);

        $this->form->addAction( 'Salvar', new TAction(array($this, 'onSave')), 'fa:save green' );
        $this->form->addAction( 'Listagem', new TAction(array('FuncioForm', 'onReload')), 'fa:table blue' );

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

        // add the form inside the page
        parent::add($vbox);
    }

    /**
     * method onSave
     * Executed whenever the user clicks at the save button
     */
    function onSave($param)
    {
        try
        {
            $dados = $this->form->getData();

            // open a transaction with database 'samples'
            TTransaction::open('bingo');

            // read the form data and instantiates an Active Record
            $cliente = cliente::find($dados->id);

            if($cliente){
                $cliente->nome = $dados->nome;
                $cliente->limite = $dados->limite;
                $cliente->tipo = $dados->tipo;
                $cliente->saldo = $dados->saldo;
            } else {
                $cliente = new cliente;
                $cliente->nome = $dados->nome.' (Funcionário)';
                if((in_array('1', TSession::getValue('usergroupids'))) or
                    (in_array('2', TSession::getValue('usergroupids')))
                    or (in_array('3', TSession::getValue('usergroupids')))) {
                    $cliente->limite = $dados->limite;
                } else {
                    $cliente->limite = 0;
                }
                $cliente->tipo = 1;
                $cliente->saldo = 0;
            }

            // stores the object in the database
            $cliente->store();

            $data = new stdClass();
            $data->id = $cliente->id;
            $data->nome = $cliente->nome;
            $data->limite = $cliente->limite;
            $data->tipo = $cliente->tipo;
            $data->saldo = $cliente->saldo;
            TForm::sendData('form_customer', $data);

            // shows the success message
            new TMessage('info', 'Registro salvo');

            TTransaction::close(); // close the transaction
        }
        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
     * Edit a record data
     */
    function onEdit($param)
    {
        try
        {
            if (isset($param['id']))
            {
                // open a transaction with database 'samples'
                TTransaction::open('bingo');

                // load the Active Record according to its ID
                $cliente = new cliente($param['id']);

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

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

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