<?php

Use Adianti\Widget\Wrapper\TQuickGrid;

class MoviList extends TPage
{
    Public $param;

    public function __construct($param)
    {
        parent::__construct();

        if(!isset($param['tipo'])){
            $param['tipo'] = 'Dia';
            $param['primeirodia'] = NULL;
            $param['ultimodia'] = NULL;
        }

        if($param['primeirodia'] == 'NULL'){
            $param['primeirodia'] = NULL;
            $param['ultimodia'] = NULL;
        }
        $this->param = $param;

        $this->labelTotal = new TLabel(' ');
        $this->labelTotal->setFontSize(17);
        $this->labelTotal->setFontFace('Trebuchet MS');
        $this->labelTotal->setFontColor('white');

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

        if($this->param['tipo'] == 'Dia') {
            $text_win = 'MOVIMENTO DO DIA';
        }else{
            $text_win = 'MOVIMENTO DO DIA - '.substr($this->param['primeirodia'],8,2).'/'.substr($this->param['primeirodia'],5,2).'/'.substr($this->param['primeirodia'],0,4).' - '.substr($this->param['primeirodia'],11,2).':'.substr($this->param['primeirodia'],14,2).':'.substr($this->param['primeirodia'],17,2);
        }
        $button_win = new TButton('win');
        $button_win->setAction(new TAction(array($this, 'onWin')), $text_win);
        $button_win->class = 'btn btn-danger btn-lg btn-block';
        $this->form_item->setFields(array($button_win));

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

        // add the columns
        $this->datagrid0->addQuickColumn('Usuário','descricao','center', "20%");
        $cambio = $this->datagrid0->addQuickColumn('Cambio', 'cambio', 'center', "20%");
        $cambio->setTransformer(array('Utils', 'formatValueMov'));
        $pagos = $this->datagrid0->addQuickColumn('Pagos', 'pagos', 'center', "20%");
        $pagos->setTransformer(array('Utils', 'formatValueMov'));
        $valor = $this->datagrid0->addQuickColumn('Saldo', 'saldo', 'center', "20%");
        $valor->setTransformer(array('Utils', 'formatValueMov'));
        if($this->param['tipo'] == 'Dia') {
            $passa = $this->datagrid0->addQuickColumn('PassaCX', 'passa', 'center', "20%");
            $passa->setTransformer(array('Utils', 'formatValueMov'));
        }

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

        // 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('Utils', 'formatValueMov'));
        $this->datagrid->setGroupColumn('maquina', '<b>Máquina</b>: <strong>{maquina}</strong>');
        $this->datagrid->createModel();
        $this->onReload();

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

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

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

            TTransaction::open('bingo');
            // Usuários
            $users = SystemUser::Select('*')->load();
            $cod_users=array();
            $cod_users[0] = array('Sistema',0,0,0,0);
            foreach ($users as $user){
                $cod_users[$user->id] = array($user->name, 0, 0, 0, 0);
            }
            $cod_users[1000] = array('Usuário Excluido',0,0,0,0);
            TTransaction::close();

            TTransaction::open('unit_database');
            // Leitura
            if($this->param['tipo'] == 'Dia'){
                $reads = leitura::where('fechado', 'IS', NULL)->orderby('maquina')->load();
            } else {
                $reads = leitura::where('fechado', '=', $this->param['primeirodia'])->orderby('maquina')->load();
            }

            $leituras=array();
            foreach ($reads as $read){
                $leituras[$read->maquina] = (float)(($read->fim_sai - $read->ini_sai) * $read->credito);
            }

            // Movimento
            $repository = new TRepository('movimento');
            $criteria = new TCriteria;
            $criteria->setProperty('order', 'maquina asc, dia asc, id asc');
            // Critério de Datas
            if($this->param['tipo'] == 'Dia'){
                $criteria->add(new TFilter('fechado', 'IS', NULL));
                $criteria->add(new TFilter('fechado', '=', '2019-01-01 00:00:00'), TExpression::OR_OPERATOR);
            } else {
                $criteria->add(new TFilter('fechado', '=', $this->param['primeirodia']));
            }
            $lancamentos = $repository->load($criteria, FALSE);
            TTransaction::close();

            $this->datagrid0->clear();
            $this->datagrid->clear();

            $machine = 0;
            $total_machine=0;

            if ($lancamentos)
            {
                foreach ($lancamentos as $lancamento)
                {
                    if(!array_key_exists($lancamento->usuario, $cod_users)){$lancamento->usuario = 1000;}

                    if($lancamento->usuario == 0) {
                    }elseif($lancamento->maquina == 0){
                        $lancamento->dia = substr($lancamento->dia,8,2).'/'.substr($lancamento->dia,5,2).'/'.substr($lancamento->dia,0,4).' - '.substr($lancamento->dia,11,2).':'.substr($lancamento->dia,14,2).':'.substr($lancamento->dia,17,2);
                        $cod_users[$lancamento->usuario][1] += $lancamento->valor;
                        $cod_users[$lancamento->usuario][3] += $lancamento->valor;
                        $this->totalgeral += $lancamento->valor;
                        $lancamento->usuario = $cod_users[$lancamento->usuario][0];
                        $total_machine = 0;
                        $this->datagrid->addItem($lancamento);
                    } else {
                        if($machine != $lancamento->maquina AND $machine != '0'){
                            if($machine != '850' and $machine != '901'){
                                $obj = new stdclass();
                                $obj->id = '';
                                $obj->dia = '';
                                $obj->usuario = '';
                                $obj->maquina = $machine;
                                $obj->valor = $total_machine;
                                $obj->descricao = 'PAGO POR ATENDENTES';
                                $this->datagrid->addItem($obj);
                            }
                            if($machine < 799 and $machine > 0){
                                if(number_format($total_machine, 2, '.', ',') != number_format($leituras[$machine], 2, '.', ',')){
                                    $obj = new stdclass();
                                    $obj->id = '';
                                    $obj->dia = '';
                                    $obj->usuario = '';
                                    $obj->maquina = $machine;
                                    $obj->valor = $leituras[$machine];
                                    $obj->descricao = 'LEITURA DA MÁQUINA';
                                    $this->datagrid->addItem($obj);

                                    $diferenca = $total_machine - $leituras[$machine];
                                    $obj = new stdclass();
                                    $obj->id = '';
                                    $obj->usuario = '';
                                    if( $diferenca > 0){$obj->dia = 'EXCLUIR';}else{$obj->dia = 'LANÇAR';}
                                    $obj->maquina = $machine;
                                    $obj->valor = $total_machine - $leituras[$machine];
                                    $obj->descricao = 'DIFERENÇA #';
                                    $this->datagrid->addItem($obj);
                                }
                                unset($leituras[$machine]);
                            }
                            $total_machine = 0;
                        }
                        // Se maquina > primeira fila mostra primeira da fila e pula
                        $machine = $lancamento->maquina;
                        while($machine > array_key_first($leituras)){
                            if(empty($leituras)){
                                break;
                            }
                            if($leituras[array_key_first($leituras)] != 0){
                                $obj = new stdclass();
                                $obj->id = '';
                                $obj->dia = '';
                                $obj->usuario = '';
                                $obj->maquina = array_key_first($leituras);
                                $obj->valor = 0;
                                $obj->descricao = 'PAGO POR ATENDENTES';
                                $this->datagrid->addItem($obj);

                                $obj = new stdclass();
                                $obj->id = '';
                                $obj->dia = '';
                                $obj->usuario = '';
                                $obj->maquina = array_key_first($leituras);
                                $obj->valor = $leituras[array_key_first($leituras)];
                                $obj->descricao = 'LEITURA DA MÁQUINA';
                                $this->datagrid->addItem($obj);

                                $obj = new stdclass();
                                $obj->id = '';
                                $obj->dia = 'LANÇAR';
                                $obj->usuario = '';
                                $obj->maquina = array_key_first($leituras);
                                $obj->valor = 0 - $leituras[array_key_first($leituras)];
                                $obj->descricao = 'DIFERENÇA #';
                                $this->datagrid->addItem($obj);
                            }
                            unset($leituras[array_key_first($leituras)]);
                        }
                        $lancamento->dia = substr($lancamento->dia, 8, 2) . '/' . substr($lancamento->dia, 5, 2) . '/' . substr($lancamento->dia, 0, 4) . ' - ' . substr($lancamento->dia, 11, 2) . ':' . substr($lancamento->dia, 14, 2) . ':' . substr($lancamento->dia, 17, 2);
                        If ($lancamento->fechado == $this->param['primeirodia']) {
                            $total_machine += $lancamento->valor * -1;
                            $this->totalgeral += $lancamento->valor;
                            if ($machine > 900 and $machine < 921) {
                                $cod_users[$lancamento->usuario][1] += $lancamento->valor;
                            }elseif($machine < 850 or $machine > 920 and $lancamento->fechado == $this->param['primeirodia']) {
                                $cod_users[$lancamento->usuario][2] += $lancamento->valor;
                            }
                            $cod_users[$lancamento->usuario][3] += $lancamento->valor;
                            $lancamento->usuario = $cod_users[$lancamento->usuario][0];
                            $this->datagrid->addItem($lancamento);
                            $machine = $lancamento->maquina;
                        } else {
                            $cod_users[$lancamento->usuario][4] += $lancamento->valor;
                        }
                    }
                }
                if($machine != '850' and $machine != '901') {
                    $obj = new stdclass();
                    $obj->id = '';
                    $obj->dia = '';
                    $obj->usuario = '';
                    $obj->maquina = $machine;
                    $obj->valor = $total_machine;
                    $obj->descricao = 'PAGO POR ATENDENTES';
                    $this->datagrid->addItem($obj);
                }
                if($machine < 799){
                    if(number_format($total_machine, 2, '.', ',') != number_format($leituras[$machine], 2, '.', ',')){
                        $obj = new stdclass();
                        $obj->id = '';
                        $obj->dia = '';
                        $obj->usuario = '';
                        $obj->maquina = $machine;
                        $obj->valor = $leituras[$machine];
                        $obj->descricao = 'LEITURA DA MÁQUINA';
                        $this->datagrid->addItem($obj);

                        $diferenca = $total_machine - $leituras[$machine];
                        $obj = new stdclass();
                        $obj->id = '';
                        if( $diferenca > 0){$obj->dia = 'EXCLUIR';}else{$obj->dia = 'LANÇAR';}
                        $obj->usuario = '';
                        $obj->maquina = $machine;
                        $obj->valor = $total_machine - $leituras[$machine];
                        $obj->descricao = 'DIFERENÇA #';
                        $this->datagrid->addItem($obj);
                    }

                    unset($leituras[$machine]);
                }
            }

            if ($leituras) {
                foreach ($leituras as $machine=>$leitura) {
                    $total_machine = 0;
                    $obj = new stdclass();
                    $obj->id = '';
                    $obj->dia = '';
                    $obj->usuario = '';
                    $obj->maquina = $machine;
                    $obj->valor = $total_machine;
                    $obj->descricao = 'PAGO POR ATENDENTES';
                    $this->datagrid->addItem($obj);

                    $obj = new stdclass();
                    $obj->id = '';
                    $obj->dia = '';
                    $obj->usuario = '';
                    $obj->maquina = $machine;
                    $obj->valor = $leituras[$machine];
                    $obj->descricao = 'LEITURA DA MÁQUINA';
                    $this->datagrid->addItem($obj);

                    $diferenca = $total_machine - $leituras[$machine];
                    $obj = new stdclass();
                    $obj->id = '';
                    if( $diferenca > 0){$obj->dia = 'EXCLUIR';}else{$obj->dia = 'LANÇAR';}
                    $obj->usuario = '';
                    $obj->maquina = $machine;
                    $obj->valor = $total_machine - $leituras[$machine];
                    $obj->descricao = 'DIFERENÇA #';
                    $this->datagrid->addItem($obj);
                }
            }

            foreach ($cod_users as $item){
                if($item[3]==0 and $item[4]==0) {
                }else{
                    $obj = new stdclass();
                    $obj->descricao = $item[0];
                    $obj->cambio   = $item[1];
                    $obj->pagos   = $item[2];
                    $obj->saldo   = $item[3];
                    $obj->passa   = $item[4];
                    $obj->usuario = '';
                    $this->datagrid0->addItem($obj);
                }
            }

            $this->loaded = true;
            $this->labelTotal->setValue('SALDO: 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();
        }
    }
    public function onWin()
    {
        return;
    }
}