<?php

use Adianti\Control\TAction;
use Adianti\Control\TPage;
use Adianti\Core\AdiantiCoreTranslator;
use Adianti\Database\TCriteria;
use Adianti\Database\TFilter;
use Adianti\Database\TRepository;
use Adianti\Database\TTransaction;
use Adianti\Registry\TSession;
use Adianti\Widget\Container\TVBox;
use Adianti\Widget\Datagrid\TDataGridAction;
use Adianti\Widget\Dialog\TMessage;
use Adianti\Widget\Dialog\TQuestion;
use Adianti\Widget\Form\TEntry;
use Adianti\Widget\Form\THidden;
use Adianti\Widget\Wrapper\TQuickForm;
use Adianti\Widget\Wrapper\TQuickGrid;

class ClienteForm extends TPage
{
    private $form;      // formulário de cadastro
    private $datagrid;  // listagem
    private $loaded;

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

        // creates the form
        $this->form = new TQuickForm('form_search_customer');
        $this->form->setFormTitle('Clientes');
        $this->form->class = 'tform';

        $this->totalgeral = 0;
        $this->labelTotal = new TLabel('');
        $this->labelTotal->setFontSize(15);
        $this->labelTotal->setFontFace('Trebuchet MS');
        $this->labelTotal->setFontColor('blue');

        // create the form fields
        $id       = new THidden('id');
        $name     = new TEntry('nome');
        if(Utils::isCoordenador()) {
            $limite   = new TEntry('limite');
        } else {
            $limite   = new THidden('limite');
        }

        // make id not editable
        $id->setEditable(FALSE);

        // add the form fields
        $this->form->addQuickField('Nome',$name,         '70%');
        $this->form->addQuickField('Limite',$limite,      '70%');

        $name->setValue(TSession::getValue('customer_name'));
//        $name->addValidation(_t('Name'), new TRequiredValidator);

        $this->form->addQuickAction( 'Procura', new TAction(array($this, 'onSearch')), 'fa:search blue' );
        $this->form->addQuickAction( 'Novo',  new TAction(array('ClienteFormView', 'onEdit')), 'fa:plus green' );

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

        // add the columns
        $this->datagrid->addQuickColumn('Nome',   'nome',   'left'   , 300, new TAction(array($this, 'onReload')), array('order', 'nome'));
        $balance = $this->datagrid->addQuickColumn('Saldo', 'saldo', 'right', 70, new TAction(array($this, 'onReload')), array('order', 'saldo'));
        $balance->setTransformer(array($this, 'formatsaldo'));
        $teto=$this->datagrid->addQuickColumn('Limite', 'limite', 'right'  ,  70, new TAction(array($this, 'onReload')), array('order', 'limite'));
        $teto->setTransformer(array($this, 'formatlimite'));
        $this->datagrid->addQuickColumn('Última Visita',   'last_visita',   'center'   , 300, new TAction(array($this, 'onReload')), array('order', 'last_visita'));

        // add the actions
//        $this->datagrid->addQuickAction('Entrada', new TDataGridAction(array($this, 'onCasa')),   'id', 'fa:home');
        if(Utils::isCoordenador()) {
            $this->datagrid->addQuickAction('Edita', new TDataGridAction(array('ClienteFormView', 'onEdit')), 'id', 'fa:edit blue');
//            $this->datagrid->addQuickAction('Deleta', new TDataGridAction(array($this, 'onDelete')), 'id', 'fa:trash red');
        }

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

        $btsaldo = new TButton('saldo');
        $btsaldo->setLabel($this->labelTotal);
        $btsaldo->class = 'btn btn-danger btn-lg';

        // wrap objects inside a table
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
//        $vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
        $vbox->add($this->form);
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;overflow-x:auto;';
        if(Utils::isCoordenador()) {
            $vbox->add($btsaldo);
        }
        // pack the table inside the page
        parent::add($vbox);
    }

    /**
     * method onSearch()
     * Register the filter in the session when the user performs a search
     */
    function onSearch()
    {
        // get the search form data
        $data = $this->form->getData();

        // check if the user has filled the form
        if (isset($data->nome) AND ($data->nome))
        {
            // creates a filter using what the user has typed
            $filter = new TFilter('nome', 'like', "%{$data->nome}%");

            // stores the filter in the session
            TSession::setValue('customer_filter1', $filter);
            TSession::setValue('customer_name',   $data->nome);

        }
        else
        {
            TSession::setValue('customer_filter1', NULL);
            TSession::setValue('customer_name',   '');
        }

        // fill the form with data again
        $this->form->setData($data);

        $param=array();
        $param['offset']    =0;
        $param['first_page']=1;
        $this->onReload($param);
    }
    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {
            $this->totalgeral = 0;
            // open a transaction with database 'samples'
            TTransaction::open('unit_database');

            // creates a repository for Customer
            $repository = new TRepository('cliente');
            $criteria = new TCriteria;
            $newparam = $param; // define new parameters
            if (empty($newparam['order']))
            {
                $newparam['order'] = 'nome';
                $newparam['direction'] = 'asc';
            }
            $criteria->setProperties($newparam); // order, offset
            $criteria->add(new TFilter('tipo', '=', 0));         // create the form fields
            if (TSession::getValue('customer_filter1'))
            {
                // add the filter stored in the session to the criteria
                $criteria->add(TSession::getValue('customer_filter1'));
            }

            // load the objects according to criteria
            $customers = $repository->load($criteria, FALSE);
            $this->datagrid->clear();
            if ($customers)
            {
                foreach ($customers as $customer)
                {
                    // add the object inside the datagrid
                    $customer->last_visita = substr($customer->last_visita,8,2).'/'.substr($customer->last_visita,5,2).'/'.substr($customer->last_visita,0,4).' - '.substr($customer->last_visita,11,5);
                    $this->datagrid->addItem($customer);
                    $this->totalgeral += $customer->saldo;
                }
            }

            // reset the criteria for record count
            $criteria->resetProperties();
            $count= $repository->count($criteria);

            // close the transaction
            TTransaction::close();
            $this->loaded = true;
            $this->labelTotal->setValue('TOTAL: R$ '.number_format($this->totalgeral, 2, ',', '.'));
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());

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

    /**
     * method onDelete()
     * executed whenever the user clicks at the delete button
     * Ask if the user really wants to delete the record
     * @param $param
     */
    public function onDelete($param)
    {
        // define the delete action
        $action = new TAction(array($this, 'Delete'));
        $action->setParameters($param); // pass the key parameter ahead

        // shows a dialog to the user
        new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
    }

    /**
     * method Delete()
     * Delete a record
     * @param $param
     */
    public function Delete($param)
    {
        try
        {
            // get the parameter $key
            $key=$param['key'];

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

            // instantiates object
            $object = new cliente($key);

            if($object->saldo == '0.00'){
                // deletes the object from the database
                $object->delete();
                // close the transaction
                TTransaction::close();
                // reload the listing
                $this->onReload( $param );
                // shows the success message
                TToast::show('error', AdiantiCoreTranslator::translate('Record deleted'), 'top right', 'far:check-circle' );
                AdiantiCoreApplication::loadPage('ClienteForm');
            } else {
                // close the transaction
                TTransaction::close();
                // shows the success message
                new TMessage('info', 'Registro Não excluído, saldo diferente de 0,00');
            }
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());
            // undo all pending operations
            TTransaction::rollback();
        }
    }

    /**
     * method onSave()
     * Executed whenever the user clicks at the save button
     * @param $param
     * @return cliente|mixed
     */
    public function onCasa($param)
    {
        try
        {
            // get the parameter $key
            $key=$param['key'];

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

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

            // instantiates object
            $object = new cliente($key);
            $repository = new TRepository('visita');
            $criteria = new TCriteria;
            $criteria->add(new TFilter('id_cliente', '=', $key));
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $criteria->add(new TFilter('saida', 'IS', NULL));
            $itens = $repository->count($criteria);

            if($itens > 0){
                // shows the success message
                new TMessage('info', 'Visita Já Adicionada');
            } else {
                $visita = new visita();
                $visita->id_cliente = $key;
                $visita->name = $object->nome;
                $visita->tipo_cliente = $object->tipo;

                // stores the object
                $visita->store();

                // shows the success message
                TToast::show('sucess', 'Visita Adicionada', 'top right', 'far:check-circle' );
            }

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

            // reload the listing
            $this->onReload();

            return $object;
        }
        catch (Exception $e) // in case of exception
        {
            // get the form data
            $object = $this->form->getData($this->activeRecord);

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

            // shows the exception error message
            new TMessage('error', $e->getMessage());

            // undo all pending operations
            TTransaction::rollback();
        }
    }
    /**
     * Format saldo
     */
    public function formatSaldo($stock, $object, $row)
    {
        $number = number_format($stock, 2, ',', '.');
        if ($stock > 0)
        {
            $row->style = "background: #FFF9A7";
            return "<span style='color:red'>$number</span>";
        }
        else
        {
            return "<span style='color:blue'>$number</span>";
        }
    }
    /**
     * Format limite
     */
    public function formatLimite($stock, $object, $row)
    {
        $number = number_format($stock, 2, ',', '.');
        return $number;
    }

}