<?php
class ContagemForm extends TPage
{
    private $form_item;
    private $form_customer;
    private $datagrid;  // listing
    private $total;
    private $cartgrid;
    private $loaded;

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

        // creates the items form and add a table inside
        $this->form_item = new TForm('form_contagem');
        $this->form_item->class = 'tform';
        $table_item = new TTable;
        $table_item-> width = '100%';
        $this->form_item->add($table_item);

        // create the form fields
        $maquina_id = new TDBSeekButton('maquina_id', 'jackpot', 'form_contagem', 'maquina', 'nome_jogo', 'maquina_id', 'jogo');
        $jogo       = new TEntry('jogo');
        $cliente    = new TEntry('cliente');
        $instalacao = new TEntry('instalacao');
        $cobranca   = new TEntry('cobranca');
        $credito    = new THidden('credito');

        // add validators
        $maquina_id->addValidation('Máquina', new TRequiredValidator);

        // define the exit actions
        $maquina_id->setExitAction(new TAction(array($this, 'onExitMaquina')));

        // define some properties
        $maquina_id->setSize(35);
        $instalacao->setSize(80);
        $cobranca->setSize(100);
        $jogo->setEditable(FALSE);
        $cliente->setEditable(FALSE);
        $cobranca->setEditable(FALSE);
        $instalacao->setEditable(FALSE);

//        $total->setNumericMask(2, '.', ',');
//        $sale_price->setSize(100);

        // add a row for the form title
        $row  = $table_item->addRow();
        $row->class = 'tformtitle'; // CSS class
        $cell = $row->addCell( new TLabel('Leitura'));
        $cell->colspan = 4;

        // create the field labels
        $lab_maq = new TLabel('Máquina');
        $lab_maq->setFontColor('red');
        $lab_cli = new TLabel('Cliente');
        $lab_cob = new TLabel('Cobrança');
        $lab_ins = new TLabel('Instalação');

        // add the form fields
        $table_item->addRowSet($lab_maq, $maquina_id);
        $table_item->addRowSet($lab_cli, $cliente);
        $table_item->addRowSet($lab_ins, $instalacao);
        $table_item->addRowSet($lab_cob, $cobranca);
        $table_item->addRowSet($credito);

        // define the form fields
        $this->form_item->setFields(array($maquina_id, $jogo, $cliente, $instalacao, $cobranca, $credito));

        $table_conta = new TTable;
        $table_conta-> width = '100%';
        $this->form_item->add($table_conta);

        // create the form fields
        $ent_ant = new TEntry('ent_ant');
        $ent_atu = new TEntry('ent_atu');
        $sai_ant = new TEntry('sai_ant');
        $sai_atu = new TEntry('sai_atu');
        $entrou  = new TEntry('entrou');
        $saiu    = new TEntry('saiu');

        // add validators
        $ent_atu->addValidation('Entrada Atual', new TRequiredValidator);
        $sai_atu->addValidation('Saída Atual', new TRequiredValidator);

        // define the exit actions
        $ent_atu->setExitAction(new TAction(array($this, 'onExitSaida')));
        $sai_atu->setExitAction(new TAction(array($this, 'onExitSaida')));

        // define some properties
        $ent_ant->setSize(60);
        $ent_atu->setSize(60);
        $sai_ant->setSize(60);
        $sai_atu->setSize(60);
        $entrou->setSize(60);
        $saiu->setSize(60);
        $ent_ant->setEditable(FALSE);
        $sai_ant->setEditable(FALSE);
        $entrou->setEditable(FALSE);
        $saiu->setEditable(FALSE);

//        $entrou->setNumericMask(2, '.', ',');
//        $saiu->setNumericMask(2, '.', ',');

        // create the field labels
        $lab_entrada = new TLabel('Entrada');
        $lab_saida   = new TLabel('Saida');
        $lab_minus   = new TLabel('-');
        $lab_minus2  = new TLabel('-');
        $lab_cifrao  = new TLabel('R$');
        $lab_igual   = new TLabel('=');
        $lab_igual2  = new TLabel('=');
        $lab_cifrao2 = new TLabel('R$');

        // action button
//        $button2 = new TButton('save');
//        $button2->setAction(new TAction(array($this, 'onSave')), 'Save and finish');
//        $button2->setImage('ico_save.png');

        // add the form fields
        $table_conta->addRowSet($lab_entrada, $ent_atu, $lab_minus,  $ent_ant, $lab_igual,  $lab_cifrao, $entrou);
        $table_conta->addRowSet($lab_saida,   $sai_atu, $lab_minus2, $sai_ant, $lab_igual2, $lab_cifrao2, $saiu);

        // define the form fields
        $this->form_item->setFields(array($ent_ant, $ent_atu, $sai_ant, $sai_atu));

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
        $vbox->add($this->form_item);
        $vbox->add(new TLabel('&nbsp;'));
        parent::add($vbox);
    }

    /**
     * Saves the cart
     */
    public function onSave()
    {
        try
        {
            $this->form_customer->validate(); // validate form data

            $data = $this->form_customer->getData();

            TTransaction::open('samples');
            $items = TSession::getValue('items'); // get items
            if ($items)
            {
                $sale = new Sale; // create a new Sale
                $sale->customer_id = $data->customer_id;
                $sale->date = date('Y-m-d');
                $total = 0;
                foreach ($items as $item)
                {
                    $item->sale_price = str_replace(',', '', $item->sale_price);
                    $item->total      = str_replace(',', '', $item->total);
                    $total += str_replace(',', '', $item->total);

                    $sale->addSaleItem($item); // add the item to the Sale
                }
                $sale->total = $total;
                $sale->store(); // store the Sale

                // clear items
                TSession::setValue('items', NULL);
                $this->form_customer->clear(); // clear form
                new TMessage('info', 'Record saved successfully');
            }
            TTransaction::close();
            $this->onReload();
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }
    /**
     * Exit action for the field product
     * Fill some form fields (sale_price, amount, discount, total)
     */
    public static function onExitMaquina($param)
    {
        $dia = array(0 => 'Domingo', 1 => 'Segunda-feira', 2 => 'Terça-feira', 3 => 'Quarta-feira', 4 => 'Quinta-feira', 5 => 'Sexta-feira', 6 => 'Sábado');
        $maquina_id = $param['maquina_id']; // get the product code
        try
        {
            TTransaction::open('jackpot');
            $maquina = new maquina($maquina_id); // reads the product
            $obj = new StdClass;
            $obj->cliente  = $maquina->get_nome_cliente().' - '.$maquina->get_nome_jogo();
            $obj->cobranca = $maquina->get_cobranca();
            $obj->instalacao = $maquina->get_instala();
            $obj->ent_ant = $maquina->entrada;
            $obj->sai_ant = $maquina->saida;
            $obj->credito = $maquina->credito;
            TTransaction::close();
            TForm::sendData('form_contagem', $obj);
        }
        catch (Exception $e)
        {
            // does nothing
        }
    }

    /**
     * Exit action for the field product
     * Fill some form fields (sale_price, amount, discount, total)
     */
    public static function onExitSaida($param)
    {
        try
        {
            $ent_ant = $param['ent_ant']; // get the product code
            $ent_atu = $param['ent_atu']; // get the product code
            $sai_ant = $param['sai_ant']; // get the product code
            $sai_atu = $param['sai_atu']; // get the product code
            $credito = $param['credito']; // get the product code
            $obj = new StdClass;
            $obj->entrou =  number_format(($ent_atu-$ent_ant)*$credito, 2, ',', '.');
            $obj->saiu = number_format(($sai_atu-$sai_ant)*$credito, 2, ',', '.');
            TForm::sendData('form_contagem', $obj);
        }
        catch (Exception $e)
        {
            // does nothing
        }
    }

    /**
     * Update the total based on the sale price, amount and discount
     */
    public static function onUpdateTotal($param)
    {
        $discount   = (double) str_replace(',', '', $param['discount']);
        $sale_price = (double) str_replace(',', '', $param['sale_price']);
        $amount     = (double) str_replace(',', '', $param['amount']);

        $obj = new StdClass;
        $obj->total       = number_format( ($sale_price * $amount) - $discount, 2, '.', ',');
        TForm::sendData('form_pos', $obj);
    }

    /**
     * Remove a product from the cart
     */
    public function onDelete($param)
    {
        // get the cart objects from session
        $items = TSession::getValue('items');
        unset($items[ $param['key'] ]); // remove the product from the array
        TSession::setValue('items', $items); // put the array back to the session

        // reload datagrid
        $this->onReload( func_get_arg(0) );
    }
}
?>