<?php

use Adianti\Widget\Wrapper\TQuickGrid;

class Semanal extends TPage
{
    private $datagrid;

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

        $operador = $param['method'];

        $dia = date("Y-m-d");
//        $dia = "2020-05-10";

        while(date("w", strtotime($dia)) != "1"){

            $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
       }
        $dia_sem5[0] = date('Y-m-d', strtotime($dia));
        $dia_sem5[1] = date('d', strtotime($dia));
        $dia_sem5[2] = date('Y-m-d', strtotime("+6 days",strtotime($dia)));
        $dia_sem5[3] = $dia_sem5[1]." a ".date('d/m', strtotime("+6 days",strtotime($dia)));

        $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
        while(date("w", strtotime($dia)) != "1"){

            $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
       }
        $dia_sem4[0] = date('Y-m-d', strtotime($dia));
        $dia_sem4[1] = date('d', strtotime($dia));
        $dia_sem4[2] = date('Y-m-d', strtotime("+6 days",strtotime($dia)));
        $dia_sem4[3] = $dia_sem4[1]." a ".date('d/m', strtotime("+6 days",strtotime($dia)));

        $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
        while(date("w", strtotime($dia)) != "1"){

            $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
       }
        $dia_sem3[0] = date('Y-m-d', strtotime($dia));
        $dia_sem3[1] = date('d', strtotime($dia));
        $dia_sem3[2] = date('Y-m-d', strtotime("+6 days",strtotime($dia)));
        $dia_sem3[3] = $dia_sem3[1]." a ".date('d/m', strtotime("+6 days",strtotime($dia)));

        $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
        while(date("w", strtotime($dia)) != "1"){

            $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
       }
        $dia_sem2[0] = date('Y-m-d', strtotime($dia));
        $dia_sem2[1] = date('d', strtotime($dia));
        $dia_sem2[2] = date('Y-m-d', strtotime("+6 days",strtotime($dia)));
        $dia_sem2[3] = $dia_sem2[1]." a ".date('d/m', strtotime("+6 days",strtotime($dia)));

        $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
        while(date("w", strtotime($dia)) != "1"){

            $dia = date('Y-m-d', strtotime("-1 days",strtotime($dia)));
       }
        $dia_sem1[0] = date('Y-m-d', strtotime($dia));
        $dia_sem1[1] = date('d', strtotime($dia));
        $dia_sem1[2] = date('Y-m-d', strtotime("+6 days",strtotime($dia)));
        $dia_sem1[3] = $dia_sem1[1]." a ".date('d/m', strtotime("+6 days",strtotime($dia)));

        TTransaction::open('jackpot');

        // Lista de Pontos
        $itens = array();
        $criteria = new TCriteria();
        $criteria->add(new TFilter('operador', '=', $operador));
        $criteria->setProperty('order', 'nome');
        TTransaction::open('jackpot');
        $repository = new TRepository('Ponto');
        $result = $repository->load($criteria);
        foreach ($result as $item){
            $itens[] = array($item->nome, $item->id);
        }
        TTransaction::close();

        // create the datagrid - Contadores
        $this->datagrid0 = new TQuickGrid;
        $this->datagrid0->style = 'width: 100%';
        $dias_semana = array(0=>$dia_sem1[3],1=>$dia_sem2[3],2=>$dia_sem3[3],3=>$dia_sem4[3],4=>$dia_sem5[3]);
        $this->datagrid0->addQuickColumn('PONTO / SEMANA'  ,'tipo'  ,'left', 150);

        $dia1 = $this->datagrid0->addQuickColumn($dias_semana[0],'dia1','center', 150);$dia1->setTransformer(array($this, 'formatsaldo'));
        $dia2 = $this->datagrid0->addQuickColumn($dias_semana[1],'dia2','center', 150);$dia2->setTransformer(array($this, 'formatsaldo'));
        $dia3 = $this->datagrid0->addQuickColumn($dias_semana[2],'dia3','center', 150);$dia3->setTransformer(array($this, 'formatsaldo'));
        $dia4 = $this->datagrid0->addQuickColumn($dias_semana[3],'dia4','center', 150);$dia4->setTransformer(array($this, 'formatsaldo'));
        $dia5 = $this->datagrid0->addQuickColumn($dias_semana[4],'dia5','center', 150);$dia5->setTransformer(array($this, 'formatsaldo'));
        $total=$this->datagrid0->addQuickColumn('TOTAL','total','center', 150);
        $total->setTransformer(array($this, 'formatsaldo'));
        $this->datagrid0->createModel();

        TTransaction::open('jackpot');
        $pontos = new SplFixedArray(count($itens));
        $total1=0;
        $total2=0;
        $total3=0;
        $total4=0;
        $total5=0;
        for($nloop=0;$nloop < count($itens);$nloop++){
            $repository = new TRepository('Movimento');

            $criteria = new TCriteria();
            $criteria->add(new TFilter('id_ponto', '=', $itens[$nloop][1]));
            $criteria->add(new TFilter('dia', 'BETWEEN', $dia_sem5[0]));
            $criteria->add(new TFilter('', '', $dia_sem5[2]));
            $objetos = $repository->load($criteria);
            $sub_total5=0;
            foreach ($objetos as $objeto)
            {
                $sub_total5+= $objeto->pago;
            }
            $total5 += $sub_total5;

            $criteria = new TCriteria();
            $criteria->add(new TFilter('id_ponto', '=', $itens[$nloop][1]));
            $criteria->add(new TFilter('dia', 'BETWEEN', $dia_sem4[0]));
            $criteria->add(new TFilter('', '', $dia_sem4[2]));
            $objetos = $repository->load($criteria);
            $sub_total4=0;
            foreach ($objetos as $objeto)
            {
                $sub_total4+= $objeto->pago;
            }
            $total4 += $sub_total4;

            $criteria = new TCriteria();
            $criteria->add(new TFilter('id_ponto', '=', $itens[$nloop][1]));
            $criteria->add(new TFilter('dia', 'BETWEEN', $dia_sem3[0]));
            $criteria->add(new TFilter('', '', $dia_sem3[2]));
            $objetos = $repository->load($criteria);
            $sub_total3=0;
            foreach ($objetos as $objeto)
            {
                $sub_total3+= $objeto->pago;
            }
            $total3 += $sub_total3;

            $criteria = new TCriteria();
            $criteria->add(new TFilter('id_ponto', '=', $itens[$nloop][1]));
            $criteria->add(new TFilter('dia', 'BETWEEN', $dia_sem2[0]));
            $criteria->add(new TFilter('', '', $dia_sem2[2]));
            $objetos = $repository->load($criteria);
            $sub_total2=0;
            foreach ($objetos as $objeto)
            {
                $sub_total2+= $objeto->pago;
            }
            $total2 += $sub_total2;

            $criteria = new TCriteria();
            $criteria->add(new TFilter('id_ponto', '=', $itens[$nloop][1]));
            $criteria->add(new TFilter('dia', 'BETWEEN', $dia_sem1[0]));
            $criteria->add(new TFilter('', '', $dia_sem1[2]));
            $objetos = $repository->load($criteria);
            $sub_total1=0;
            foreach ($objetos as $objeto)
            {
                $sub_total1+= $objeto->pago;
            }
            $total1 += $sub_total1;

            $pontos[$nloop] = new stdclass();$pontos[$nloop]->tipo = $itens[$nloop][0];$pontos[$nloop]->dia1 = $sub_total1;$pontos[$nloop]->dia2 = $sub_total2;$pontos[$nloop]->dia3 = $sub_total3;$pontos[$nloop]->dia4 = $sub_total4;$pontos[$nloop]->dia5 = $sub_total5;$pontos[$nloop]->total = $sub_total1+$sub_total2+$sub_total3+$sub_total4+$sub_total5;
        }

        for($nloop=0;$nloop < count($itens);$nloop++){
            $this->datagrid0->addItem($pontos[$nloop]);
        }

        $totaliza = new stdclass();$totaliza->tipo = "TOTAL";$totaliza->dia1 = $total1;$totaliza->dia2 = $total2;$totaliza->dia3 = $total3;$totaliza->dia4 = $total4;$totaliza->dia5 = $total5;$totaliza->total = $total1+$total2+$total3+$total4+$total5;
        $this->datagrid0->addItem($totaliza);

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

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

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

    }

    /**
     * Format saldo
     */
    public function formatSaldo($stock, $object, $row)
    {

        if($stock == '9999999999'){return "";}
        $number = number_format($stock, 2, ',', '.');
        if($stock < 0){$number = number_format($stock*-1, 2, ',', '.');}
//        if($object->maquinas =='TOTAL DE ENTRADAS'){$row->style = "background: #00BFFF";}
//        if($object->maquinas =='TOTAL DE PAGAMENTOS'){$row->style = "background: #FF3030";}
        $row->style = "background: #C1CDC1";
        if($object->tipo =='SALDO DAS MÁQUINAS'){$row->style = "background: #90EE90";}
        if($object->tipo =='SALDO DOS VALES'){$row->style = "background: #90EE90";}
        if($object->tipo =='TOTAL DE DESPESAS'){$row->style = "background: #90EE90";}
        if($object->tipo =='LUCRO DA SEMANA'){$row->style = "background: #00BFFF";}
        if($object->tipo =='PREJUÍZO DA SEMANA'){$row->style = "background: #FFFF00";}

        if ($stock < 0)
        {
            return "<span style='color:red'>$number</span>";
        }
        else
        {
            return "<span style='color:blue'>$number</span>";
        }
    }
    function onGenerate()
    {
        try
        {
            // write and open file
            file_put_contents('app/output/document.pdf', $this->dompdf->output());

            // open window to show pdf
            $window = TWindow::create(_t('Document HTML->PDF'), 0.8, 0.8);
            $object = new TElement('object');
            $object->data  = 'app/output/document.pdf';
            $object->type  = 'application/pdf';
            $object->style = "width: 100%; height:calc(100% - 10px)";
            $window->add($object);
            $window->show();

        }
        catch (Exception $e) // in case of exception
        {
            new TMessage('error', $e->getMessage());
            TTransaction::rollback();
        }
    }


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

    // creates a frame
$this->frame = new TFrame;
$lab_cxdia = new TLabel('dia');
$lab_cxdia->setFontSize(17);
$lab_cxdia->setFontFace('Trebuchet MS');
$lab_cxdia->setValue('CAIXA DO DIA - ' . substr($param["method"], 8, 2) . '/' . substr($param["method"], 5, 2) . '/' . substr($param["method"], 0, 4));
$this->frame->add($lab_cxdia);

    // creates a DataGrid
$this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
$this->datagrid->datatable = 'true';
$this->datagrid->style = 'width: 100%';
$this->datagrid->setHeight(320);

    // creates the datagrid columns
//        $column_id       = new TDataGridColumn('id'       , 'Id'           , 'center');
$column_dia = new TDataGridColumn('dia', 'Dia', 'center');
$column_ponto = new TDataGridColumn('ponto', 'Ponto', 'center');
$column_entrada = new TDataGridColumn('entrada', 'Entrada', 'right');
$column_saida = new TDataGridColumn('saida', 'Saida', 'right');
$column_apurado = new TDataGridColumn('apurado', 'Apurado', 'right');
$column_comissao = new TDataGridColumn('comissao', 'Comissão', 'right');
$column_saldo = new TDataGridColumn('saldo', 'Saldo', 'right');
$column_despesas = new TDataGridColumn('despesas', 'Despesas', 'right');
$column_pago = new TDataGridColumn('pago', 'Pago', 'right');
$column_deve_ant = new TDataGridColumn('deve_ant', 'Prej Anterior', 'right');
$column_deve_atu = new TDataGridColumn('deve_atu', 'Prej Atual   ', 'right');
$column_cx_atu = new TDataGridColumn('cx_atu', 'Caixa Atual   ', 'right');
$column_usuario = new TDataGridColumn('usuario', 'Operador', 'center');

    // add the columns
//        $this->datagrid->addColumn($column_id);
$this->datagrid->addColumn($column_ponto);
$this->datagrid->addColumn($column_entrada);
$this->datagrid->addColumn($column_saida);
$this->datagrid->addColumn($column_apurado);
$this->datagrid->addColumn($column_deve_ant);
$this->datagrid->addColumn($column_despesas);
$this->datagrid->addColumn($column_saldo);
$this->datagrid->addColumn($column_comissao);
$this->datagrid->addColumn($column_pago);
$this->datagrid->addColumn($column_deve_atu);
$this->datagrid->addColumn($column_cx_atu);
$this->datagrid->addColumn($column_dia);
$this->datagrid->addColumn($column_usuario);

$column_dia->setTransformer(function ($value, $object, $row)
{
    return substr($value, 8, 2) . '/' . substr($value, 5, 2) . ' - ' . substr($value, 11, 5);
});
$column_ponto->setTransformer(function ($value, $object, $row)
{
    If (substr($value, 0, 3) == '***') {
        $row->style = "color: white; background: red";
    };
    If (substr($value, 0, 13) == '*** TOTAL ***') {
        $row->style = "background: lightblue";
    };
    return $value;
});


$column_entrada->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_saida->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_apurado->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_comissao->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_saldo->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_despesas->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_pago->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_deve_ant->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_deve_atu->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});
$column_cx_atu->setTransformer(function ($value, $object, $row)
{
    return number_format($value, 2, ',', '.');
});

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

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

function onReload($param)
{

    TTransaction::open('jackpot');

    $dia00 = $this->primeirodia . ' 00:00:00';
    $dia99 = $this->primeirodia . ' 23:59:59';

    // Recupera Lançamentos
    $repository = new TRepository('Movimento');
    $criteria = new TCriteria;
    $criteria->setProperty('order', 'usuario asc');
    $criteria->add(new TFilter('dia', 'BETWEEN', $dia00, $dia99));
    $customers = $repository->load($criteria);

    $this->datagrid->clear();
    $quebra = '';
    $pula = 1;
    $sub_entrada = 0;
    $sub_saida = 0;
    $sub_apurado = 0;
    $sub_despesas = 0;
    $sub_saldo = 0;
    $sub_comissao = 0;
    $sub_pago = 0;
    $tot_entrada = 0;
    $tot_saida = 0;
    $tot_apurado = 0;
    $tot_despesas = 0;
    $tot_saldo = 0;
    $tot_comissao = 0;
    $tot_pago = 0;
    $conteudo = '';
    foreach ($customers as $customer) {
        if ($quebra != $customer->usuario) {
            $quebra = $customer->usuario;
            if ($pula == 1) {
                $pula = 0;
            } else {
                $obj = new StdClass;
                $obj->ponto = '*** TOTAL ***';
                $obj->dia = date('Y-m-d H:i:s');
                $obj->entrada = $sub_entrada;
                $obj->saida = $sub_saida;
                $apurado = $sub_apurado;
                $obj->apurado = $apurado;
                $obj->deve_ant = 0;
                $obj->despesas = $sub_despesas;
                $obj->saldo = $sub_saldo;
                $obj->comissao = $sub_comissao;
                $obj->pago = $sub_pago;
                $obj->cx_atu = 0;
                $obj->deve_atu = 0;
                $obj->usuario = $usuario->name;
                $row = $this->datagrid->addItem($obj);

                if ($sub_despesas != 0) {
                    $row->popover = 'true';
                    $row->popside = 'top';
                    $row->popcontent = '<tr><th>Ponto</th><th>Descrição</th><th>Valor</th></tr>' . $conteudo . '</table>';
                    $row->poptitle = 'Despesas';
                    $conteudo = '';
                }

                $sub_entrada = 0;
                $sub_saida = 0;
                $sub_apurado = 0;
                $sub_despesas = 0;
                $sub_saldo = 0;
                $sub_comissao = 0;
                $sub_pago = 0;
            }
        }
        $obj = new StdClass;
        $obj->id = $customer->id;
        $ponto = new Ponto($customer->id_ponto);
        $obj->ponto = $ponto->nome;
        $obj->dia = $customer->dia;
        $obj->entrada = $customer->entrada;
        $obj->saida = $customer->saida;
        $apurado = $customer->entrada - $customer->saida;
        $obj->apurado = $apurado;
        $obj->deve_ant = $customer->deve_anterior;
        $obj->despesas = $customer->despesas;
        $saldo = $apurado + $customer->deve_anterior - $customer->despesas;
        $obj->saldo = $saldo;
        $obj->comissao = $customer->comissao;
        $obj->pago = $customer->pago;
        $obj->cx_atu = $customer->cx_atual;
        $obj->deve_atu = $customer->deve_atual;
        $usuario = new SystemUser($customer->usuario);
        $obj->usuario = $usuario->name;
        $row = $this->datagrid->addItem($obj);
        // Despesas
        if ($customer->despesas != 0) {
            // Recupera Despesas
            $repository = new TRepository('Despesa');
            $criteria = new TCriteria;
            $criteria->add(new TFilter('id_movi', '=', $customer->id));
            $debitos = $repository->load($criteria);
            foreach ($debitos as $debito) {
                $quem = new Ponto($debito->id_ponto);
                $conteudo = $conteudo . '<tr><td>' . $quem->nome . '</td><td> | ' . $debito->descricao . '</td><td> | ' . number_format($debito->valor, 2, ',', '.') . '</td></tr>';
            }
        }
        // Sub-totais
        $sub_entrada += $obj->entrada;
        $sub_saida += $obj->saida;
        $sub_apurado += $obj->apurado;
        $sub_despesas += $obj->despesas;
        $sub_saldo += $obj->saldo;
        $sub_comissao += $obj->comissao;
        $sub_pago += $obj->pago;
        // Totais
        $tot_entrada += $obj->entrada;
        $tot_saida += $obj->saida;
        $tot_apurado += $obj->apurado;
        $tot_despesas += $obj->despesas;
        $tot_saldo += $obj->saldo;
        $tot_comissao += $obj->comissao;
        $tot_pago += $obj->pago;
    }

    if ($sub_entrada != 0 or $sub_despesas != 0) {
        $obj = new StdClass;
        $obj->ponto = '*** TOTAL ***';
        $obj->dia = date('Y-m-d H:i:s');
        $obj->entrada = $sub_entrada;
        $obj->saida = $sub_saida;
        $obj->apurado = $sub_apurado;
        $obj->deve_ant = 0;
        $obj->despesas = $sub_despesas;
        $obj->saldo = $sub_saldo;
        $obj->comissao = $sub_comissao;
        $obj->pago = $sub_pago;
        $obj->cx_atu = 0;
        $obj->deve_atu = 0;
        $obj->usuario = $usuario->name;
        $row = $this->datagrid->addItem($obj);
        if ($sub_despesas != 0) {
            $row->popover = 'true';
            $row->popside = 'top';
            $row->popcontent = '<tr><th>Ponto</th><th>Descrição</th><th>Valor</th></tr>' . $conteudo . '</table>';
            $row->poptitle = 'Despesas';
            $conteudo = '';
        }
    }
    // Total Geral
    $obj = new StdClass;
    $obj->ponto = '*** GERAL ***';
    $obj->dia = date('Y-m-d H:i:s');
    $obj->entrada = $tot_entrada;
    $obj->saida = $tot_saida;
    $obj->apurado = $tot_apurado;
    $obj->deve_ant = 0;
    $obj->despesas = $tot_despesas;
    $obj->saldo = $tot_saldo;
    $obj->comissao = $tot_comissao;
    $obj->pago = $tot_pago;
    $obj->cx_atu = 0;
    $obj->deve_atu = 0;
    $obj->usuario = 'GERAL';
    $this->datagrid->addItem($obj);

    TTransaction::close();

}

function show()
{
    $this->onReload(func_get_arg(0));
    parent::show();
}
*/
}
