<?php

use Adianti\Widget\Wrapper\TDBCombo;

class ResuFecList extends TPage
{
    public function __construct($param)
    {
        parent::__construct();
        new TSession;

        $this->primeirodia = $param["method"];

        // create the datagrid
        $this->datagrid = new TQuickGrid;
        $this->datagrid->style = 'width: 100%';

        // add the columns
        $this->datagrid->addQuickColumn('Data','dia','center', "25%", new TAction(array($this, 'onReload')), array('order', 'dia'));
        $this->datagrid->addQuickColumn('Usuário','usuario','center', "17%", new TAction(array($this, 'onReload')), array('order', 'usuario'));
        $this->datagrid->addQuickColumn('Máquina','maquina','center', "8%", new TAction(array($this, 'onReload')), array('order', 'maquina'));
        $this->datagrid->addQuickColumn('Descrição','descricao','left', "25%", new TAction(array($this, 'onReload')), array('order', 'descricao'));
        $valor = $this->datagrid->addQuickColumn('Valor', 'valor', 'right', "25%", new TAction(array($this, 'onReload')), array('order', 'valor'));
        $valor->setTransformer(array($this, 'formatsaldo'));
        $this->datagrid->setGroupColumn('maquina', '<b>Máquina</b>: <strong>{maquina}</strong>');
        $this->datagrid->createModel();

        $this->frame = new TFrame;

        $this->onReload();

        // wrap the page content using vertical box
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
        $vbox->add($this->frame)->style = 'width: 100%; text-align: center;';
        $vbox->add($this->datagrid)->style = 'width: 100%; text-align: center;';
        parent::add($vbox);
    }

    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {
            $this->totalgeral = 0;

            TTransaction::open('bingo');
            $repository = new TRepository('SystemUser');
            $users = $repository->load();
            $cod_users=array();
            $cod_users[0] = array('SISTEMA',0);
            foreach ($users as $user){
                $cod_users[$user->id] = array($user->name, 0);
            }

            $repository = new TRepository('leitura');
            $criteria = new TCriteria;
            $criteria->add(new TFilter('fechado', '=', $this->primeirodia));
            $reads = $repository->load($criteria);
            $leituras=array();
            foreach ($reads as $read){
                $leituras[$read->maquina] = (float)(($read->fim_sai - $read->ini_sai) * $read->credito);
            }

            $repository = new TRepository('movimento');
            $criteria = new TCriteria;
            $criteria->setProperty('order', 'maquina asc, dia asc');
            $criteria->add(new TFilter('fechado', '=', $this->primeirodia));
            $customers = $repository->load($criteria);

            $this->datagrid->clear();

            $machine='999';
            $total_machine=0;

            if ($customers)
            {
                foreach ($customers as $customer)
                {
                    if($machine != $customer->maquina AND $machine != '999'){
                        $obj = new stdclass();
                        $obj->id = '';
                        $obj->dia = '';
                        $obj->usuario = '';
                        $obj->maquina = $machine;
                        $obj->valor = $total_machine;
                        $obj->descricao = 'SUB-TOTAL';
                        $this->datagrid->addItem($obj);

                        if($machine < 100 and $machine > 0){
                            if($leituras[$machine] != $total_machine){
                                $obj = new stdclass();
                                $obj->id = '';
                                $obj->dia = '';
                                $obj->usuario = '';
                                $obj->maquina = $machine;
                                $obj->valor = $leituras[$machine];
                                $obj->descricao = 'LEITURA';
                                $this->datagrid->addItem($obj);

                                $obj = new stdclass();
                                $obj->id = '';
                                $obj->dia = '';
                                $obj->usuario = '';
                                $obj->maquina = $machine;
                                $obj->valor = $total_machine - $leituras[$machine];
                                $obj->descricao = 'DIFERENÇA #';
                                $this->datagrid->addItem($obj);
                            }

                            unset($leituras[$machine]);
                        }

                        $total_machine = 0;

                    };
                    $total_machine += $customer->valor * -1;
                    $machine = $customer->maquina;
                    $customer->dia = substr($customer->dia,8,2).'/'.substr($customer->dia,5,2).'/'.substr($customer->dia,0,4).' - '.substr($customer->dia,11,2).':'.substr($customer->dia,14,2).':'.substr($customer->dia,17,2);

                    $this->totalgeral += $customer->valor;

                    $quem = new SystemUser($customer->usuario);
                    $customer->usuario = $quem->login;

                    // add the object inside the datagrid
                    $this->datagrid->addItem($customer);
                }
                $obj = new stdclass();
                $obj->id = '';
                $obj->dia = '';
                $obj->usuario = '';
                $obj->maquina = $machine;
                $obj->valor = $total_machine;
                $obj->descricao = 'SUB-TOTAL';
                $this->datagrid->addItem($obj);
            }

            foreach($leituras as $chave=>$item){
                if($item != 0){
                    $obj = new stdclass();
                    $obj->id = '';
                    $obj->dia = '';
                    $obj->usuario = '';
                    $obj->maquina = $chave;
                    $obj->valor = 0;
                    $obj->descricao = 'SUB-TOTAL';
                    $this->datagrid->addItem($obj);

                    $obj = new stdclass();
                    $obj->id = '';
                    $obj->dia = '';
                    $obj->usuario = '';
                    $obj->maquina = $chave;
                    $obj->valor = $item;
                    $obj->descricao = 'LEITURA';
                    $this->datagrid->addItem($obj);

                    $obj = new stdclass();
                    $obj->id = '';
                    $obj->dia = '';
                    $obj->usuario = '';
                    $obj->maquina = $chave;
                    $obj->valor = 0 - $item;
                    $obj->descricao = 'DIFERENÇA #';
                    $this->datagrid->addItem($obj);
                }
            }

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

            // close the transaction
            TTransaction::close();
            $this->loaded = true;

            $lab_cxdia = new TLabel('dia');
            $lab_cxdia->setFontSize(17);
            $lab_cxdia->setFontFace('Trebuchet MS');
            $lab_cxdia->setValue('MOVIMENTO DO DIA - ');
            $this->frame->add($lab_cxdia);

            $lab_dia = new TLabel('dia');
            $lab_dia->setFontSize(17);
            $lab_dia->setFontFace('Trebuchet MS');
            $form_dia = substr($this->primeirodia,8,2).'/'.substr($this->primeirodia,5,2).'/'.substr($this->primeirodia,0,4).' - '.substr($this->primeirodia,11,2).':'.substr($this->primeirodia,14,2).':'.substr($this->primeirodia,17,2);
            $lab_dia->setValue($form_dia);
            $this->frame->add($lab_dia);
        }
        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)
        {
            if($object->descricao =='DIFERENÇA #'){$row->style = "background: #00BFFF";}
            return "<span style='color:red'>$number</span>";
        }
        else
        {
            if($object->descricao =='DIFERENÇA #'){$row->style = "background: #00BFFF";}else{$row->style = "background: #FFF9A7";}
            return "<span style='color:blue'>$number</span>";
        }
    }
}