<?php
class VisitaFormView extends TPage
{
    /**
     * Class constructor
     * Creates the page and the registration form
     */
    function __construct()
    {
        parent::__construct();
        new TSession;

        // 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);

        $visitor = new THidden('visitor');

        // create the datagrid
        $this->datagrid0 = new TQuickGrid;
        $this->datagrid0->style = 'width: 100%';
        $this->datagrid0->addQuickColumn('Visitante',  'visita',  'center', 150);
        $this->datagrid0->addQuickColumn('Entrada',    'entrada', 'center', 150);
        $this->datagrid0->addQuickColumn('Saída',      'saida',   'center', 150);
        $this->datagrid0->addQuickColumn('Permanência','perma',   'center', 150);
        $this->datagrid0->createModel();

        // create the datagrid
        $this->datagrid1 = new TQuickGrid;
        $this->datagrid1->style = 'width: 100%';
        $this->datagrid1->addQuickColumn('Despesas', 'dia', 'center', 150);
        $this->datagrid1->addQuickColumn('Descrição', 'descricao', 'left', 150);
        $valor = $this->datagrid1->addQuickColumn('Valor', 'valor', 'right', 150);
        $valor->setTransformer(array($this, 'formatsaldo'));
        $this->datagrid1->createModel();

        // create the datagrid
        $this->datagrid2 = new TQuickGrid;
        $this->datagrid2->style = 'width: 100%';
        $this->datagrid2->addQuickColumn('Pagamentos', 'dia', 'center', 150);
        $this->datagrid2->addQuickColumn('Máquina', 'maquina', 'center', 10);
        $this->datagrid2->addQuickColumn('Validação', 'descricao', 'left', 150);
        $pagamento = $this->datagrid2->addQuickColumn('Valor', 'valor', 'right', 150);
        $pagamento->setTransformer(array($this, 'formatsaldo'));
        $this->datagrid2->createModel();

        // create the datagrid
        $this->datagrid3 = new TQuickGrid;
        $this->datagrid3->style = 'width: 100%';
        $this->datagrid3->addQuickColumn('Leituras', 'maquina', 'center', 10);
        $this->datagrid3->addQuickColumn('Tipo', 'descricao', 'center', 10);
        $entrada = $this->datagrid3->addQuickColumn('Entrada', 'jogou', 'right', 150);
        $entrada->setTransformer(array($this, 'formatsaldo'));
        $saida = $this->datagrid3->addQuickColumn('Saida', 'pagou', 'right', 150);
        $saida->setTransformer(array($this, 'formatsaldo'));
        $lp = $this->datagrid3->addQuickColumn('Saldo', 'saldo', 'right', 150);
        $lp->setTransformer(array($this, 'formatsaldo'));
        $this->datagrid3->createModel();

//        $this->onReload();

        $this->btsaldo = new TButton('vai');
        $this->btsaldo->class = 'btn btn-info btn-lg';
        $this->btsaldo->setAction(new TAction(array($this, 'onSaida')), 'Confirma Fim da Visita');

        $this->btvolta = new TButton('volta');
        $this->btvolta->class = 'btn btn-danger btn-lg';
        $this->btvolta->setAction(new TAction(array($this, 'onVoltar')), 'Voltar');

        // define the form fields
        $this->form_item->setFields(array($this->btsaldo, $visitor, $this->btvolta));

        // 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;';
        $vbox->add($this->datagrid1)->style = 'width: 100%; text-align: center;';
        $vbox->add($this->datagrid2)->style = 'width: 100%; text-align: center;';
        $vbox->add($this->datagrid3)->style = 'width: 100%; text-align: center;';
        $vbox->add($this->btsaldo);
        $vbox->add($this->btvolta);
        parent::add($vbox);
    }

    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param)
    {
        try {
            TTransaction::open('unit_database');
            $visita = new visita($param['id']);

            // Resgata Visita
            $obj = new stdclass();
            $obj->visita = $visita->name;
            $obj->entrada = $visita->entrada;
            $obj->saida = $visita->saida;
            $obj->perma = $this->ago($visita->entrada,$visita->saida);
            $this->datagrid0->clear();
            $this->datagrid0->addItem($obj);

            // Muda Botão se Visita Encerrada
            if($visita->saida){
                $this->btsaldo->setLabel('Visita Já Encerrada');
                $this->btsaldo->class = 'btn btn-success btn-lg';
            }

            TSession::setValue('visitor',$param['id']);

            // Resgata Despesas e Pagamentos
            $repository = new TRepository('movimento');
            $criteria = new TCriteria;
            $newparam['order'] = 'maquina';
            $newparam['direction'] = 'asc';
            $criteria->setProperties($newparam); // order, offset
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $criteria->add(new TFilter('visita', '=', $visita->id_cliente));
            $registros = $repository->load($criteria);
            $this->datagrid1->clear();
            $total_desp=0;
            $total_paga=0;
            $mjogadas=array();
            if ($registros){
                foreach ($registros as $item){
                    if($item->maquina > 800){
                        $obj = new stdclass();
                        $obj->dia = substr($item->dia, 8, 2) . '/' . substr($item->dia, 5, 2) . '/' . substr($item->dia, 0, 4) . ' - ' . substr($item->dia, 11, 2) . ':' . substr($item->dia, 14, 2) . ':' . substr($item->dia, 17, 2);
                        $obj->descricao = $item->descricao;
                        $obj->valor = $item->valor;
                        $this->datagrid1->addItem($obj);
                        $total_desp += $item->valor;
                    } else {
                        $obj = new stdclass();
                        $obj->dia = substr($item->dia, 8, 2) . '/' . substr($item->dia, 5, 2) . '/' . substr($item->dia, 0, 4) . ' - ' . substr($item->dia, 11, 2) . ':' . substr($item->dia, 14, 2) . ':' . substr($item->dia, 17, 2);
                        $obj->maquina = $item->maquina;
                        $obj->descricao = $item->descricao;
                        $obj->valor = $item->valor;
                        $this->datagrid2->addItem($obj);
                        $total_paga += $item->valor;
                        if(in_array($item->maquina, $mjogadas) == false){$mjogadas[] = $item->maquina;}
                    }
                }
                $obj = new stdclass();
                $obj->dia = '';
                $obj->descricao = 'TOTAL';
                $obj->valor = $total_desp;
                $this->datagrid1->addItem($obj);

                $obj = new stdclass();
                $obj->dia = '';
                $obj->maquina = '';
                $obj->descricao = 'TOTAL';
                $obj->valor = $total_paga;
                $this->datagrid2->addItem($obj);
            }
            if($mjogadas){
                $repository = new TRepository('leitura');
                $criteria = new TCriteria;
                $criteria->add(new TFilter('fechado', 'IS', NULL));
                $criteria->add(new TFilter('maquina', 'in', $mjogadas));
                $leituras = $repository->load($criteria);
                foreach ($leituras as $leitura){
                    $machine = new maquina($leitura->maquina);
                    $obj = new stdclass();
                    $obj->maquina = $leitura->maquina;
                    $obj->descricao = $machine->tipo;
                    $obj->jogou = ($leitura->fim_entra-$leitura->ini_entra)*$leitura->credito;
                    $obj->pagou = ($leitura->fim_sai-$leitura->ini_sai)*$leitura->credito;
                    $obj->saldo = $obj->jogou-$obj->pagou;
                    $this->datagrid3->addItem($obj);
                }
            }
            // reset the criteria for record count
            $criteria->resetProperties();
            $count = $repository->count($criteria);
            // close the transaction
            TTransaction::close();
            $this->loaded = true;

        }
        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)
    {
        $row->style = "background: #C1CDC1";
        $number = number_format($stock, 2, ',', '.');
        if ($stock < 0) {
            if ($object->descricao == 'TOTAL') {
                $row->style = "background: #90EE90";
            }
            return "<span style='color:red'>$number</span>";
        } else {
            if ($object->descricao == 'TOTAL') {
                $row->style = "background: #90EE90";
            } else {
                $row->style = "background: #FFF9A7";
            }
            return "<span style='color:blue'>$number</span>";
        }
    }
    public function ago($entrada,$saida){//return a DateTime object or a date in the chosen format
        if(!$saida){$saida=time();}else{$saida=strtotime($saida);}
        $timeago=$saida-strtotime($entrada);
        if($timeago>=0){
            $y=(int)($timeago/31536000);
            $y=($y<0)?(-$y):$y;
            $d=(int)(($timeago%31536000)/86400);
            $d=($d<0)?(-$d):$d;
            $h=(int)((($timeago%31536000)%86400)/3600);
            $h=($h<0)?(-$h):$h;
            $min=(int)(((($timeago%31536000)%86400)%3600)/60);
            $min=($min<0)?(-$min):$min;
            $sec=((((($timeago%31536000)%86400)%3600)%60));
            $sec=($sec<0)?(-$sec):$sec;
            $result = new DateInterval("P".$y."Y".$d."DT".$h."H".$min."M".$sec."S");
        }else{
            $result = new DateInterval("PT0H0M0S");
        }
        $retorno = '%i Min';
        If($h > 0){$retorno = '%h Hora %i Min';};

        return  $result->format($retorno);
    }

    public function onVoltar($param)
    {
        // reload the listing
        TApplication::loadPage('VisitaForm', 'onReload');
        return NULL;
    }

    /**
     * method onSaida()
     * Executed whenever the user clicks at the save button
     */
    public function onSaida($param)
    {
        try
        {
            $key = TSession::getValue('visitor');

            // open a transaction with database
            TTransaction::open('unit_database');

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

            if(!$visita->saida) {
                $visita->saida = date('Y-m-d H:i:s');

                // stores the object
                $visita->store();

                // shows the success message
                new TMessage('info', 'Fim da Visita confirmada');

            }
            // close the transaction
            TTransaction::close();

            // reload the listing
            TApplication::loadPage('VisitaForm', 'onReload');
            return NULL;
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', $e->getMessage());

            // undo all pending operations
            TTransaction::rollback();
        }
    }
}
