<?php

class AnexoForm extends TPage
{
    protected $form;
    private $formFields = [];
    private static $database = 'clinica';
    private static $activeRecord = 'Anexo';
    private static $primaryKey = 'id';
    private static $formName = 'form_AnexoForm';

    use Adianti\Base\AdiantiFileSaveTrait;

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


        $id = new TEntry('id');
        $atendimento_id = new THidden('atendimento_id');
        $arquivo = new TFile('arquivo');
        $observacao = new TEntry('observacao');

        $arquivo->addValidation("Arquivo", new TRequiredValidator()); 

        $id->setEditable(false);
        $atendimento_id->setValue($param['atendimento_id']??'');
        $arquivo->enableFileHandling();
        $id->setSize(100);
        $arquivo->setSize('100%');
        $observacao->setSize('100%');
        $atendimento_id->setSize(200);


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

        $row2 = $this->form->addFields([new TLabel("Arquivo:", '#ff0000', '14px', null, '100%'),$arquivo]);
        $row2->layout = [' col-sm-12'];

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

        $row1->style = 'display: none';

        // 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=AnexoForm]');
        $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 Anexo(); // create an empty object 

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

            $arquivo_dir = 'atendimento/anexos';  

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

            $this->saveFile($object, $data, 'arquivo', $arquivo_dir);
            $messageAction = new TAction(['AtendimentoFormView', 'onShow']);   

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

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

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

            // 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 Anexo($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)
    {

    } 

}

