<?php

class BloqueioForm extends TPage
{
    protected $form;
    private $formFields = [];
    private static $database = 'clinica';
    private static $activeRecord = 'Bloqueio';
    private static $primaryKey = 'id';
    private static $formName = 'form_Bloqueio';

    /**
     * Form constructor
     * @param $param Request
     */
    public function __construct( $param )
    {
        parent::__construct();

        if(!empty($param['target_container']))
        {
            $this->adianti_target_container = $param['target_container'];
        }

        // creates the form
        $this->form = new BootstrapFormBuilder(self::$formName);
        // define the form title
        $this->form->setFormTitle("Bloqueio");

        $criteria_agenda_id = new TCriteria();

        $filterVar = TSession::getValue("userunitid");
        $criteria_agenda_id->add(new TFilter('clinica_id', 'in', "(SELECT id FROM clinica WHERE system_unit_id = '{$filterVar}')")); 

        $filterVar = TSession::getValue('userid');

        $criteriaAcesso = new TCriteria;
        // está como um profissional relacionado com a agenda
        $criteriaAcesso->add(new TFilter('id', 'in', "(SELECT agenda.id FROM agenda, agenda_profissional, pessoa WHERE pessoa.id = agenda_profissional.profissional_id AND agenda.id = agenda_profissional.agenda_id AND system_users_id = '{$filterVar}')"));
        // oyu é o profissional responsável da agenda
        $criteriaAcesso->add(new TFilter('id', 'in', "(SELECT agenda.id FROM agenda, pessoa WHERE pessoa.id = agenda.profissional_id AND system_users_id = '{$filterVar}')"), TExpression::OR_OPERATOR); 

        $criteria_agenda_id->add($criteriaAcesso);

        $id = new TEntry('id');
        $agenda_id = new TDBCombo('agenda_id', 'clinica', 'Agenda', 'id', '{nome}','nome asc' , $criteria_agenda_id );
        $dt_inicio = new TDateTime('dt_inicio');
        $dt_final = new TDateTime('dt_final');
        $observacao = new TText('observacao');

        $agenda_id->addValidation("Agenda", new TRequiredValidator()); 
        $dt_inicio->addValidation("Início", new TRequiredValidator()); 
        $dt_final->addValidation("Fim", new TRequiredValidator()); 
        $observacao->addValidation("Observação", new TRequiredValidator()); 

        $id->setEditable(false);
        $dt_final->setMask('dd/mm/yyyy hh:ii');
        $dt_inicio->setMask('dd/mm/yyyy hh:ii');

        $dt_final->setDatabaseMask('yyyy-mm-dd hh:ii');
        $dt_inicio->setDatabaseMask('yyyy-mm-dd hh:ii');

        $id->setSize(100);
        $dt_final->setSize(150);
        $dt_inicio->setSize(150);
        $agenda_id->setSize('100%');
        $observacao->setSize('100%', 70);

        $row1 = $this->form->addFields([new TLabel("Código:", null, '14px', null, '100%'),$id]);
        $row1->layout = ['col-sm-6'];

        $row2 = $this->form->addFields([new TLabel("Agenda:", '#ff0000', '14px', null, '100%'),$agenda_id],[new TLabel("Início:", '#ff0000', '14px', null, '100%'),$dt_inicio],[new TLabel("Fim:", '#ff0000', '14px', null, '100%'),$dt_final]);
        $row2->layout = [' col-sm-6',' col-sm-3',' col-sm-3'];

        $row3 = $this->form->addFields([new TLabel("Observação:", '#FF0000', '14px', null, '100%'),$observacao]);
        $row3->layout = [' col-sm-12'];

        // create the form actions
        $btnSalvar = $this->form->addAction("Salvar", new TAction([$this, 'onSave']), 'fas:save #ffffff');
        $this->btnSalvar = $btnSalvar;
        $btnSalvar->addStyleClass('btn-primary'); 

        $btn_onclear = $this->form->addAction("Limpar formulário", new TAction([$this, 'onClear']), 'fas:eraser #dd5a43');
        $this->btn_onclear = $btn_onclear;

        $btn_ondeletebloqueio = $this->form->addAction("Remover Bloqueio", new TAction([$this, 'onDeleteBloqueio']), 'fas:trash-alt #FF5722');
        $this->btn_ondeletebloqueio = $btn_ondeletebloqueio;

        parent::setTargetContainer('adianti_right_panel');

        $btnClose = new TButton('closeCurtain');
        $btnClose->class = 'btn btn-sm btn-default';
        $btnClose->style = 'margin-right:10px;';
        $btnClose->onClick = "Template.closeRightPanel();";
        $btnClose->setLabel("Fechar");
        $btnClose->setImage('fas:times');

        $this->form->addHeaderWidget($btnClose);

        parent::add($this->form);

        $style = new TStyle('right-panel > .container-part[page-name=BloqueioForm]');
        $style->width = '70% !important';   
        $style->show(true);

    }

    public function onSave($param = null) 
    {
        try
        {
            TTransaction::open(self::$database); // open a transaction

            $messageAction = null;

            $this->form->validate(); // validate form data

            $object = new Bloqueio(); // create an empty object 

            $data = $this->form->getData(); // get form data as array
            $object->fromArray( (array) $data); // load the object with data

            $object->store(); // save the object 

            $messageAction = new TAction(['AgendamentosFilterForm', 'onShow']);   

            if(!empty($param['target_container']))
            {
                $messageAction->setParameter('target_container', $param['target_container']);
            }

            // get the generated {PRIMARY_KEY}
            $data->id = $object->id; 

            $this->form->setData($data); // fill form data
            TTransaction::close(); // close the transaction

            new TMessage('info', "Registro salvo", $messageAction); 

                        TScript::create("Template.closeRightPanel();"); 

        }
        catch (Exception $e) // in case of exception
        {
            //</catchAutoCode> 

            new TMessage('error', $e->getMessage()); // shows the exception error message
            $this->form->setData( $this->form->getData() ); // keep form data
            TTransaction::rollback(); // undo all pending operations
        }
    }
    public static function onDeleteBloqueio($param = null) 
    {
        try 
        {
            // Código gerado pelo snippet: "Questionamento"
            new TQuestion("Você tem certeza que deseja remover esse bloqueio?", new TAction([__CLASS__, 'onYesRemoverBloqueio'], $param), new TAction([__CLASS__, 'onNoRemoverBloqueio'], $param));
            // -----

        }
        catch (Exception $e) 
        {
            new TMessage('error', $e->getMessage());    
        }
    }

    public function onEdit( $param )
    {
        try
        {
            if (isset($param['key']))
            {
                $key = $param['key'];  // get the parameter $key
                TTransaction::open(self::$database); // open a transaction

                $object = new Bloqueio($key); // instantiates the Active Record 

                $this->form->setData($object); // fill the form 

                TTransaction::close(); // close the transaction 
            }
            else
            {
                $this->form->clear();
            }
        }
        catch (Exception $e) // in case of exception
        {
            new TMessage('error', $e->getMessage()); // shows the exception error message
            TTransaction::rollback(); // undo all pending operations
        }
    }

    /**
     * Clear form data
     * @param $param Request
     */
    public function onClear( $param )
    {
        $this->form->clear(true);

    }

    public function onShow($param = null)
    {

    } 

    public static function onYesRemoverBloqueio($param = null) 
    {
        try 
        {
            TTransaction::open(self::$database);

            $bloqueio = new Bloqueio($param['id']);
            $bloqueio->delete();

            TTransaction::close();

            new TMessage('info', 'Bloqueio removido', new TAction(['AgendamentosFilterForm', 'onShow']));

            TScript::create("Template.closeRightPanel();");
        }
        catch (Exception $e) 
        {
            new TMessage('error', $e->getMessage());    
        }
    }

    public static function onNoRemoverBloqueio($param = null) 
    {
        try 
        {
            //code here
        }
        catch (Exception $e) 
        {
            new TMessage('error', $e->getMessage());    
        }
    }

}

