<?php

use Adianti\Control\TAction;
use Adianti\Control\TPage;
use Adianti\Database\TCriteria;
use Adianti\Database\TRepository;
use Adianti\Database\TTransaction;
use Adianti\Widget\Container\TVBox;
use Adianti\Widget\Datagrid\TDataGridAction;
use Adianti\Widget\Dialog\TMessage;
use Adianti\Widget\Wrapper\TQuickGrid;

class VisitaForm extends TPage
{
    private $datagrid;  // listagem
    private $loaded;

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

        // create the datagrid
        $this->datagrid = new TQuickGrid;
        // add the columns
        $this->datagrid->addQuickColumn('Visita na Casa',       'name',    'left'   , 150, new TAction(array($this, 'onReload')), array('order', 'name'));
        $this->datagrid->addQuickColumn('Entrada',    'entrada', 'center'  , 150 , new TAction(array($this, 'onReload')), array('order', 'entrada'));
        $this->datagrid->addQuickColumn('Permanência','tempo',   'center'  , 150);
        // add the actions
        $this->datagrid->addQuickAction('Histórico', new TDataGridAction(array('VisitaFormView', 'onReload')),   'id', 'fa:history fa-fw');
        // create the datagrid model
        $this->datagrid->createModel();

        // create the datagrid
        $this->datagrid1 = new TQuickGrid;
        // add the columns
        $this->datagrid1->addQuickColumn('Visita Encerrada',   'name',    'left'  , 150, new TAction(array($this, 'onReload')), array('order', 'name'));
        $this->datagrid1->addQuickColumn('Entrada','entrada', 'center', 150, new TAction(array($this, 'onReload')), array('order', 'entrada'));
        $this->datagrid1->addQuickColumn('Saida  ','saida',   'center', 150, new TAction(array($this, 'onReload')), array('order', 'saida'));
        // add the actions
        $this->datagrid1->addQuickAction('Histórico', new TDataGridAction(array('VisitaFormView', 'onReload')),   'id', 'fa:history fa-fw');
        // create the datagrid model
        $this->datagrid1->createModel();

        // create the datagrid
        $this->datagrid2 = new TQuickGrid;
        // add the columns
        $this->datagrid2->addQuickColumn('Nome',   'nome',   'left'   , 300, new TAction(array($this, 'onReload')), array('order', 'nome'));
        $this->datagrid2->addQuickColumn('Última Visita',   'last_visita',   'center'   , 300, new TAction(array($this, 'onReload')), array('order', 'last_visita'));
        $this->datagrid2->addQuickAction('Entrada', new TDataGridAction(array($this, 'onCasa')),   'id', 'fa:home');
        // create the datagrid model
        $this->datagrid2->createModel();

        $this->onReload();

        // wrap objects inside a table
        $vbox = new TVBox;
        $vbox->style = 'width: 100%; text-align: center;';
//        $vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
        $vbox->add($this->datagrid);
        $vbox->add($this->datagrid1);
        $vbox->add($this->datagrid2);
        // pack the table inside the page
        parent::add($vbox);
    }

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

            TTransaction::open('bingo');
            $repository = new TRepository('visita');
            $criteria = new TCriteria;
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $visitors = $repository->load($criteria);

            if ($visitors)
            {
                foreach ($visitors as $visitor)
                {
                    $visitor->tempo = $this->ago($visitor->entrada);

                    $visitor->entrada = substr($visitor->entrada,8,2).'/'.substr($visitor->entrada,5,2).'/'.substr($visitor->entrada,0,4).' - '.substr($visitor->entrada,11,5);

                    if(!$visitor->saida){
                        $this->datagrid->addItem($visitor);

                    }else{
                        $visitor->saida = substr($visitor->saida,8,2).'/'.substr($visitor->saida,5,2).'/'.substr($visitor->saida,0,4).' - '.substr($visitor->saida,11,5);
                        $this->datagrid1->addItem($visitor);
                    }
                }
            }

            $repository = new TRepository('cliente');
            $criteria = new TCriteria;
            $criteria->setProperty('order', 'nome');
            $criteria->add(new TFilter('tipo', '=', 0));         // create the form fields
            $clientes = $repository->load($criteria);
            if ($clientes)
            {
                foreach ($clientes as $cliente)
                {
                    // add the object inside the datagrid
                    $cliente->last_visita = substr($cliente->last_visita,8,2).'/'.substr($cliente->last_visita,5,2).'/'.substr($cliente->last_visita,0,4).' - '.substr($cliente->last_visita,11,5);
                    $this->datagrid2->addItem($cliente);
                }
            }

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

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

    public function onCasa($param)
    {
        try
        {
            // get the parameter $key
            $key=$param['key'];

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

            // instantiates object
            $cliente = new cliente($key);
            $repository = new TRepository('visita');
            $criteria = new TCriteria;
            $criteria->add(new TFilter('id_cliente', '=', $key));
            $criteria->add(new TFilter('fechado', 'IS', NULL));
            $criteria->add(new TFilter('saida', 'IS', NULL));
            $itens = $repository->count($criteria);

            if($itens > 0){
                // shows the success message
                new TMessage('info', 'Visita Já Adicionada');
            } else {
                $visita = new visita();
                $visita->id_cliente = $key;
                $visita->name = $cliente->nome;
                $visita->tipo_cliente = $cliente->tipo;
                // stores the object
                $visita->store();

                $cliente->last_visita = date("Y-m-d H:i:s");
                $cliente->store();

                // shows the success message
                new TMessage('info', 'Visita Adicionada');
            }

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

            // reload the listing
            $this->onReload();

            return $cliente;
        }
        catch (Exception $e) // in case of exception
        {
            // get the form data
            $object = $this->form->getData($this->activeRecord);

            // fill the form with the active record data
            $this->form->setData($object);

            // 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)
        {
            $row->style = "background: #FFF9A7";
            return "<span style='color:red'>$number</span>";
        }
        else
        {
            return "<span style='color:blue'>$number</span>";
        }
    }

    public function ago($hora){//return a DateTime object or a date in the chosen format
        $time=time();
        $timeago=$time-strtotime($hora);
        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);
    }

}