<?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 ClienteFormView 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 Clientes');

        // 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('15%');
        $name->setSize('70%');
        $limite->setSize('40%');
        $limite->setValue(0);
        if(Utils::isCoordenador()) {
            $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('ClienteForm', '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('unit_database');

            // 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;
                if(Utils::isCoordenador()) {
                    $cliente->limite = $dados->limite;
                } else {
                    $cliente->limite = 0;
                }
                $cliente->tipo = 0;
                $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
            TToast::show('success', 'Registro Salvo com Sucesso', 'top right', 'far:check-circle' );

            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('unit_database');

                // 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();
        }
    }
}
