<?php

use Adianti\Database\TTransaction;
use Adianti\Widget\Base\TElement;
use Adianti\Widget\Form\TForm;
use Adianti\Widget\Form\TEntry;
use Adianti\Widget\Form\THidden;
use Adianti\Widget\Form\TLabel;
use Adianti\Widget\Form\TButton;
use Adianti\Widget\Container\TTable;
use Adianti\Widget\Container\TVBox;
use Adianti\Widget\Dialog\TMessage;
use Adianti\Validator\TRequiredValidator;
use Adianti\Control\TAction;

class LeiConfFoto extends TPage
{
    private $casa;
    private $diaFecha;

    public function __construct($param)
    {
        parent::__construct();
        TTransaction::open('unit_database');
        $this->equips = config::getConfig('equips');
        $this->casa=config::getConfig('titulo');
        if($param['tipo'] == 'Dia'){
            $result = movimento::where('fechado', 'IS', NULL)
                ->where('usuario', '<>', 0)
                ->orderby('id')
                ->take(1)
                ->load();
        } elseif($param['tipo'] == 'Fechado') {
            $result = movimento::where('fechado', '=', $param['primeirodia'])
                ->orderby('maquina')
                ->where('usuario', '<>', 0)
                ->orderby('id')
                ->take(1)
                ->load();
        }
        if($result){
            $this->diaFecha = $result[0]->dia;
//            $this->diaFecha = str_replace(':','_',$this->diaFecha);
        }
        TTransaction::close();

        $hafoto = 0;
        $this->imgFoto = new TElement('img');
        if(file_exists('app/images/leituras/'.$this->casa.'_'.$this->diaFecha.'_1.jpg')){
            $this->imgFoto->src = 'app/images/leituras/'.$this->casa.'_'.$this->diaFecha.'_1.jpg';
            $hafoto = 1;
        }
//        $this->imgFoto->style = "width:200px;height:200px;";

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

        $maquina_id = new TEntry('maquina_id');
        $maquina_id->setValue('1');
        $maquina_id->setEditable(False);
//        $maquina_id = new TDBCombo('maquina_id','unit_database','maquina','id','id','id');
//        $maquina_id->setChangeAction(new TAction(array($this, 'onExitMaquina')));

        $entant  = new TEntry('entant');
        $saiant  = new TEntry('saiant');
        $registro = new TEntry('registro');

//        var_dump($imgFoto);die;

        $entant->setEditable(FALSE);
        $saiant->setEditable(FALSE);

        $entant->setSize(200);
        $saiant->setSize(200);

        // add validators
        $maquina_id->addValidation('Máquina', new TRequiredValidator);

        // define some attributes
        $maquina_id->setSize(200);
        $maquina_id->style = 'font-size: 28pt; height: 45px;text-align: center;';
        $entant->style = 'font-size: 28pt; height: 45px; text-align: center; background-color: #00ffff; ';
        $saiant->style = 'font-size: 28pt; height: 45px; text-align: center; background-color: #00ffff; ';

        // add a row for the form title
        $row  = $table_item->addRow();
        $row->class = 'tformtitle'; // CSS class
        if($param['tipo'] == 'Dia') {
            $title = $row->addCell(new TLabel('LEITURA DO DIA'));
        }else{
            $texto  = substr($param['primeirodia'], 8, 2) . '/' . substr($param['primeirodia'], 5, 2) . '/' . substr($param['primeirodia'], 0, 4) . ' - ' . substr($param['primeirodia'], 11, 2) . ':' . substr($param['primeirodia'], 14, 2) . ':' . substr($param['primeirodia'], 17, 2);
            $title = $row->addCell(new TLabel('LEITURA - '.$texto));
        }
//        $title->colspan = 2;

        // create the field labels
        $lab_maq = new TLabel('MÁQUINA');
        $lab_maq->setFontSize(17);
        $lab_maq->setFontFace('Trebuchet MS');
        $lab_maq->setFontColor('blue');

        $lab_enta = new TLabel('ENTRADA ATUAL');
        $lab_enta->setFontSize(17);
        $lab_enta->setFontFace('Trebuchet MS');
        $lab_enta->setFontColor('blue');

        $lab_saia = new TLabel('SAIDA ATUAL');
        $lab_saia->setFontSize(17);
        $lab_saia->setFontFace('Trebuchet MS');
        $lab_saia->setFontColor('blue');

        // creates the action button
        $button1 = new TButton('tras');
        $button1->setAction(new TAction(array($this, 'onTras'),$param), '<< ANTERIOR');
        $button1->class = 'btn btn-success btn-lg btn-block';

        $button2 = new TButton('frente');
        $button2->setAction(new TAction(array($this, 'onFrente'),$param), ' PRÓXIMA>>');
        $button2->class = 'btn btn-success btn-lg btn-block';

        // add the form fields
        $table_item->addRowSet($lab_maq);
        $table_item->addRowSet($maquina_id)->style = 'text-align: center;';
        $table_item->addRowSet($lab_enta)->style = 'text-align: center;';
        $table_item->addRowSet($entant)->style = 'text-align: center;';
        $table_item->addRowSet($lab_saia)->style = 'text-align: center;';
        $table_item->addRowSet($saiant)->style = 'text-align: center;';
        $table_item->addRowSet('');
        if($hafoto){
            $table_item->addRowSet($this->imgFoto)->style = 'text-align: center;';
            $table_item->addRowSet('');
        }
        $table_item->addRowSet(array($button1, $button2))->style = 'text-align: center;';

        // define the form fields
        $this->form_item->setFields(array($maquina_id, $registro, $entant, $saiant, $button1, $button2));

        $passa = Array(0 => $maquina_id->getValue(),1 => $param);
        $this->onReload($passa);

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

    public function onReload($param)
    {
        $codigo = $param[0];
        try
        {
            TTransaction::open('unit_database');

            if($param[1]['tipo'] == 'Dia'){
                $machine = leitura::where('fechado', 'IS', NULL)
                    ->where('maquina', '=', $codigo)
                    ->load();
            } elseif($param[1]['tipo'] == 'Fechado') {
                $machine = leitura::where('fechado', '=', $param[1]['primeirodia'])
                    ->where('maquina', '=', $codigo)
                    ->load();
            }
            $item = $machine[0];
            $leitura = new leitura($item->id);
            $registro = $item->id;
            $obj = new StdClass;
            $obj->entant   = $leitura->fim_entra;
            $obj->saiant   = $leitura->fim_sai;
            $obj->registro = $registro;
            $obj->moeda = $item->credito;
            if(file_exists('app/images/leituras/'.$this->casa.'_'.$this->diaFecha.'_'.$leitura->maquina.'.jpg')){
                $this->imgFoto->src = 'app/images/leituras/'.$this->casa.'_'.$this->diaFecha.'_'.$leitura->maquina.'.jpg';
            }
            TTransaction::close();
            TForm::sendData('form_atendente', $obj);
        }
        catch (Exception $e)
        {
            // does nothing
        }

    }

    public function onTras($param)
    {
        try
        {
            $this->form_item->validate(); // validate form data
            $data = $this->form_item->getData();
            if($data->maquina_id == 1){
                $obj = new StdClass;
                $obj->maquina_id = $this->equips;
            } else {
                $obj = new StdClass;
                $obj->maquina_id = $data->maquina_id - 1;
            }
            TForm::sendData('form_atendente', $obj);
            $passa = Array(0 => $obj->maquina_id,1 => $param);
            $this->onReload($passa);
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

    public function onFrente($param)
    {
        try
        {
            $this->form_item->validate(); // validate form data
            $data = $this->form_item->getData();
            if($data->maquina_id == $this->equips){
                $obj = new StdClass;
                $obj->maquina_id = 1;
            } else {
                $obj = new StdClass;
                $obj->maquina_id = $data->maquina_id + 1;
            }
            TForm::sendData('form_atendente', $obj);
            $passa = Array(0 => $obj->maquina_id,1 => $param);
            $this->onReload($passa);
        }
        catch (Exception $e)
        {
            new TMessage('error', $e->getMessage());
        }
    }

}