<?php
class ExtratoForm 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('Extrato');
        $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');
        $descricao = new TEntry('descricao');

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

        // add the form fields
        $this->form->addQuickField('Descrição',$descricao, '100%');

        $descricao->setValue(TSession::getValue('customer_descricao'));

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

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

        // add the columns
        $this->datagrid->addQuickColumn('Data','dia','center', 150, new TAction(array($this, 'onReload')), array('order', 'dia'));
        $this->datagrid->addQuickColumn('Máquina','maquina','center', 30, new TAction(array($this, 'onReload')), array('order', 'maquina'));
        $this->datagrid->addQuickColumn('Descrição','descricao','left', 150, new TAction(array($this, 'onReload')), array('order', 'descricao'));
        $valor = $this->datagrid->addQuickColumn('Valor', 'valor', 'right', 170, new TAction(array($this, 'onReload')), array('order', 'valor'));
        $valor->setTransformer(array($this, 'formatsaldo'));

        // add the actions
        $this->datagrid->addQuickAction('Deleta', new TDataGridAction(array($this, 'onDelete')), 'id', 'fa:trash red');

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

        $bt3c = new TButton('bt3c');
        $bt3c->setLabel($this->labelTotal);
        $bt3c->class = 'btn btn-info btn-lg';
        $hbox3 = new THBox;
        $hbox3->addRowSet( $bt3c );
        $frame3 = new TFrame;
        $frame3->setLegend('Saldo');
        $frame3->add($hbox3);

        // wrap objects inside a table
        $vbox = new TVBox;
        $vbox->add($this->form);
        $vbox->add($frame3);
        $vbox->add($this->datagrid);
        // 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->descricao) AND ($data->descricao))
        {
            // creates a filter using what the user has typed
            $filter = new TFilter('descricao', 'like', "%{$data->descricao}%");

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

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

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

            // creates a repository for Customer
            $repository = new TRepository('movimento');

            // creates a criteria
            $criteria = new TCriteria;
            $criteria->setProperty('order', 'maquina,dia');
            $criteria->add(new TFilter('usuario', '=', TSession::getValue('userid')));
            $criteria->add(new TFilter('fechado', 'IS', NULL));

            // 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
                    $this->datagrid->addItem($customer);
                    $this->totalgeral += $customer->valor;
                }
            }

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

            // close the transaction
            TTransaction::close();
            $this->loaded = true;
            $this->labelTotal->setValue('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('bingo');

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

            // deletes the object from the database
            $object->delete();
            // close the transaction
            TTransaction::close();
            // reload the listing
            $this->onReload( $param );
            // shows the success message
            new TMessage('info', AdiantiCoreTranslator::translate('Record deleted'));
        }
        catch (Exception $e) // in case of exception
        {
            // 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)
        {
            return "<span style='color:red'>$number</span>";
        }
        else
        {
            $row->style = "background: #FFF9A7";
            return "<span style='color:blue'>$number</span>";
        }
    }
}
