<?php

class ExameAtendimentoForm extends TPage
{
    protected $form;
    private $formFields = [];
    private static $database = 'clinica';
    private static $activeRecord = 'ExameAtendimento';
    private static $primaryKey = 'id';
    private static $formName = 'form_ExameAtendimentoForm';

    /**
     * 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("Exame");

        $criteria_exame_id = new TCriteria();

        $filterVar = "S";
        $criteria_exame_id->add(new TFilter('ativo', '=', $filterVar)); 

        $id = new TEntry('id');
        $atendimento_id = new THidden('atendimento_id');
        $indicacao_clinica = new TEntry('indicacao_clinica');
        $dt_exames = new TDate('dt_exames');
        $exame_id = new TDBCombo('exame_id', 'clinica', 'Exame', 'id', '{nome}','nome asc' , $criteria_exame_id );
        $quantidade = new TEntry('quantidade');

        $indicacao_clinica->addValidation("Indicação clínica", new TRequiredValidator()); 
        $dt_exames->addValidation("Data", new TRequiredValidator()); 
        $exame_id->addValidation("Exame id", new TRequiredValidator()); 
        $quantidade->addValidation("Quantidade", new TRequiredValidator()); 

        $id->setEditable(false);
        $dt_exames->setDatabaseMask('yyyy-mm-dd');
        $exame_id->enableSearch();
        $quantidade->setMask('9999');
        $dt_exames->setMask('dd/mm/yyyy');

        $quantidade->setValue('1');
        $dt_exames->setValue(date('d/m/Y'));
        $atendimento_id->setValue($param['atendimento_id']??'');

        $id->setSize(100);
        $exame_id->setSize('100%');
        $dt_exames->setSize('100%');
        $quantidade->setSize('100%');
        $atendimento_id->setSize(200);
        $indicacao_clinica->setSize('100%');



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

        $row2 = $this->form->addFields([new TLabel("Indicação clínica:", '#ff0000', '14px', null, '100%'),$indicacao_clinica],[new TLabel("Data:", '#ff0000', '14px', null, '100%'),$dt_exames]);
        $row2->layout = [' col-sm-9',' col-sm-3'];

        $row3 = $this->form->addFields([new TLabel("Exame:", '#ff0000', '14px', null, '100%'),$exame_id],[new TLabel("Quantidade:", '#ff0000', '14px', null, '100%'),$quantidade]);
        $row3->layout = [' col-sm-9',' col-sm-3'];

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

        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=ExameAtendimentoForm]');
        $style->width = '50% !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 ExameAtendimento(); // 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(['AtendimentoFormView', 'onShow']);   

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

            if(!empty($object->atendimento_id))
            {
                $messageAction->setParameter("key", $object->atendimento_id);
            }

            if(!empty($object->atendimento_id))
            {
                $messageAction->setParameter("id", $object->atendimento_id);
            }

            $messageAction->setParameter("current_tab_abas", "1"); 

            // 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 function onEdit( $param )
    {
        try
        {
            if (isset($param['key']))
            {
                $key = $param['key'];  // get the parameter $key
                TTransaction::open(self::$database); // open a transaction

                $object = new ExameAtendimento($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)
    {

    } 

}

