<?php

class ContaReceberList extends TPage
{
    private $form; // form
    private $datagrid; // listing
    private $pageNavigation;
    private $loaded;
    private $filter_criteria;
    private static $database = 'clinica';
    private static $activeRecord = 'Conta';
    private static $primaryKey = 'id';
    private static $formName = 'formList_Conta';
    private $showMethods = ['onReload', 'onSearch', 'onRefresh', 'onClearFilters'];
    private $limit = 20;

    /**
     * Class constructor
     * Creates the page, the form and the listing
     */
    public function __construct($param = null)
    {
        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("Contas a receber");
        $this->limit = 20;

        $criteria_pessoa_id = new TCriteria();
        $criteria_categoria_conta_id = new TCriteria();
        $criteria_clinica_id = new TCriteria();

        $filterVar = Grupo::PACIENTE;
        $criteria_pessoa_id->add(new TFilter('id', 'in', "(SELECT pessoa_id FROM pessoa_grupo WHERE grupo_id = '{$filterVar}')")); 
        $filterVar = TipoConta::RECEBER;
        $criteria_categoria_conta_id->add(new TFilter('tipo_conta_id', '=', $filterVar)); 
        $filterVar = TSession::getValue("userunitids");
            $filterVar = is_array($filterVar) ? "'".implode("','", $filterVar)."'" : $filterVar;
        $criteria_clinica_id->add(new TFilter('system_unit_id', 'in', "(SELECT id FROM clinica WHERE system_unit_id in ($filterVar))")); 

        $this->showMethods = array_merge($this->showMethods, ['onVencidas', 'onVencer', 'onEmAberto']);

        $pessoa_id = new TDBUniqueSearch('pessoa_id', 'clinica', 'Pessoa', 'id', 'nome','nome asc' , $criteria_pessoa_id );
        $descricao = new TEntry('descricao');
        $filtro_rapido = new TCombo('filtro_rapido');
        $categoria_conta_id = new TDBCombo('categoria_conta_id', 'clinica', 'CategoriaConta', 'id', '{nome}','nome asc' , $criteria_categoria_conta_id );
        $clinica_id = new TDBCombo('clinica_id', 'clinica', 'Clinica', 'id', '{nome}','nome asc' , $criteria_clinica_id );
        $quitada = new TRadioGroup('quitada');
        $data_emissao_ini = new TDate('data_emissao_ini');
        $data_emissao_fim = new TDate('data_emissao_fim');
        $dt_vencimento_ini = new TDate('dt_vencimento_ini');
        $data_vencimento_fim = new TDate('data_vencimento_fim');


        $pessoa_id->setMinLength(1);
        $filtro_rapido->enableSearch();
        $quitada->setLayout('horizontal');
        $quitada->setUseButton();
        $quitada->addItems(["S"=>"Sim","N"=>"Não",""=>"Ambos"]);
        $filtro_rapido->addItems(["1"=>"Vencidas","2"=>"À vencer"]);

        $data_emissao_ini->setDatabaseMask('yyyy-mm-dd');
        $data_emissao_fim->setDatabaseMask('yyyy-mm-dd');
        $dt_vencimento_ini->setDatabaseMask('yyyy-mm-dd');
        $data_vencimento_fim->setDatabaseMask('yyyy-mm-dd');

        $pessoa_id->setMask('{nome_formatado}');
        $data_emissao_ini->setMask('dd/mm/yyyy');
        $data_emissao_fim->setMask('dd/mm/yyyy');
        $dt_vencimento_ini->setMask('dd/mm/yyyy');
        $data_vencimento_fim->setMask('dd/mm/yyyy');

        $quitada->setSize(100);
        $pessoa_id->setSize('100%');
        $descricao->setSize('100%');
        $clinica_id->setSize('100%');
        $filtro_rapido->setSize('100%');
        $data_emissao_ini->setSize(150);
        $data_emissao_fim->setSize(150);
        $dt_vencimento_ini->setSize(150);
        $data_vencimento_fim->setSize(150);
        $categoria_conta_id->setSize('100%');



        $row1 = $this->form->addFields([new TLabel("Paciente:", null, '14px', null, '100%'),$pessoa_id],[new TLabel("Descrição:", null, '14px', null, '100%'),$descricao],[new TLabel("Filtro rápido:", null, '14px', null),$filtro_rapido]);
        $row1->layout = [' col-sm-4',' col-sm-4',' col-sm-4'];

        $row2 = $this->form->addFields([new TLabel("Categoria:", null, '14px', null, '100%'),$categoria_conta_id],[new TLabel("Clínica:", null, '14px', null),$clinica_id],[new TLabel("Quitada:", null, '14px', null, '100%'),$quitada]);
        $row2->layout = ['col-sm-4','col-sm-4','col-sm-4'];

        $row3 = $this->form->addFields([new TLabel("Data de emissão:", null, '14px', null, '100%'),$data_emissao_ini,new TLabel("até", null, '14px', null),$data_emissao_fim],[new TLabel("Data de vencimento", null, '14px', null, '100%'),$dt_vencimento_ini,new TLabel("até", null, '14px', null),$data_vencimento_fim]);
        $row3->layout = ['col-sm-4','col-sm-4'];

        // keep the form filled during navigation with session data
        $this->form->setData( TSession::getValue(__CLASS__.'_filter_data') );

        $btn_onsearch = $this->form->addAction("Buscar", new TAction([$this, 'onSearch']), 'fas:search #ffffff');
        $this->btn_onsearch = $btn_onsearch;
        $btn_onsearch->addStyleClass('btn-primary'); 

        // creates a Datagrid
        $this->datagrid = new TDataGrid;
        $this->datagrid->disableHtmlConversion();

        $this->datagrid_form = new TForm('datagrid_'.self::$formName);
        $this->datagrid_form->onsubmit = 'return false';

        $this->datagrid = new BootstrapDatagridWrapper($this->datagrid);
        $this->filter_criteria = new TCriteria;

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

        $this->datagrid->style = 'width: 100%';
        $this->datagrid->setHeight(250);

        $column_id = new TDataGridColumn('id', "Código", 'center' , '70px');
        $column_pessoa_nome_formatado_transformed = new TDataGridColumn('{pessoa->nome_formatado}', "Pessoa", 'left');
        $column_total_conta_transformed = new TDataGridColumn('total_conta', "Total", 'center' , '100px');
        $column_data_emissao_transformed = new TDataGridColumn('data_emissao', "Emissão", 'center' , '100px');
        $column_quitada_transformed = new TDataGridColumn('quitada', "Quitada", 'center' , '100px');

        $column_pessoa_nome_formatado_transformed->setTransformer(function($value, $object, $row, $cell = null, $last_row = null)
        {
            $table = new TElement('div');
            $table->style = 'display: flex; flex-direction: row; flex-wrap: wrap; gap: 4px;';

            foreach(Lancamento::where('conta_id', '=', $object->id)->orderBy('dt_vencimento', 'asc')->load() as $lancamento)
            {
                $tableDetail = new TElement('div');
                $tableDetail->style = 'display: flex; flex-direction: column';
                $tableDetail->add(TElement::tag('small',TDate::date2br($lancamento->dt_vencimento)));
                $tableDetail->add(TElement::tag('span', 'R$ ' . number_format($lancamento->valor, 2, ',', '.')));

                $clazz = $lancamento->dt_pagamento ? 'label-success' : ($lancamento->dt_vencimento <= date('Y-m-d') ? 'label-danger' : 'label-default');

                $tableDetail->class = 'card card-lancamento ' . $clazz;

                $tableDetail->title =  $lancamento->dt_pagamento ? 'Quitada' : ($lancamento->dt_vencimento <= date('Y-m-d') ? 'Atrasada' : 'Em aberto');

                $table->add($tableDetail);
            }

            $div = new TElement('div');
            $div->add(TElement::tag('span', $value, ['style' => 'color: var(--text-color-strong); text-transform: uppercase; font-size: 110%;']));
            $div->add(TElement::tag('div', 'Lançamentos', ['class' => 'title-lancamentos']));
            $div->add($table);
            return $div;

        });

        $column_total_conta_transformed->setTransformer(function($value, $object, $row, $cell = null, $last_row = null)
        {
            if(!$value)
            {
                $value = 0;
            }

            if(is_numeric($value))
            {
                return "R$ " . number_format($value, 2, ",", ".");
            }
            else
            {
                return $value;
            }
        });

        $column_data_emissao_transformed->setTransformer(function($value, $object, $row, $cell = null, $last_row = null)
        {
            if(!empty(trim($value)))
            {
                try
                {
                    $date = new DateTime($value);
                    return $date->format('d/m/Y');
                }
                catch (Exception $e)
                {
                    return $value;
                }
            }
        });

        $column_quitada_transformed->setTransformer(function($value, $object, $row, $cell = null, $last_row = null)
        {

            $label = new TElement('span');
            $label->{'class'} = 'label label-';

            if ($value == 'S' || $value == 'T') {
                $label->{'class'} .= 'success';
                $label->add('Sim');    

                return $label;
            }

            $label->{'class'} .= 'danger';
            $label->add('Não');

            return $label;
        });        

        $order_id = new TAction(array($this, 'onReload'));
        $order_id->setParameter('order', 'id');
        $column_id->setAction($order_id);

        $this->datagrid->addColumn($column_id);
        $this->datagrid->addColumn($column_pessoa_nome_formatado_transformed);
        $this->datagrid->addColumn($column_total_conta_transformed);
        $this->datagrid->addColumn($column_data_emissao_transformed);
        $this->datagrid->addColumn($column_quitada_transformed);

        $action_onShow = new TDataGridAction(array('ContaFormView', 'onShow'));
        $action_onShow->setUseButton(false);
        $action_onShow->setButtonClass('btn btn-default btn-sm');
        $action_onShow->setLabel("Visualizar parcelas");
        $action_onShow->setImage('fas:search #00BCD4');
        $action_onShow->setField(self::$primaryKey);

        $this->datagrid->addAction($action_onShow);

        $action_onEdit = new TDataGridAction(array('ContaForm', 'onEdit'));
        $action_onEdit->setUseButton(false);
        $action_onEdit->setButtonClass('btn btn-default btn-sm');
        $action_onEdit->setLabel("Editar");
        $action_onEdit->setImage('far:edit #478fca');
        $action_onEdit->setField(self::$primaryKey);

        $this->datagrid->addAction($action_onEdit);

        $action_onDelete = new TDataGridAction(array('ContaReceberList', 'onDelete'));
        $action_onDelete->setUseButton(false);
        $action_onDelete->setButtonClass('btn btn-default btn-sm');
        $action_onDelete->setLabel("Excluir");
        $action_onDelete->setImage('fas:trash-alt #dd5a43');
        $action_onDelete->setField(self::$primaryKey);

        $this->datagrid->addAction($action_onDelete);

        // create the datagrid model
        $this->datagrid->createModel();

        // creates the page navigation
        $this->pageNavigation = new TPageNavigation;
        $this->pageNavigation->enableCounters();
        $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
        $this->pageNavigation->setWidth($this->datagrid->getWidth());

        $panel = new TPanelGroup("Contas a receber");
        $panel->datagrid = 'datagrid-container';
        $this->datagridPanel = $panel;
        $this->datagrid_form->add($this->datagrid);
        $panel->add($this->datagrid_form);

        $panel->addFooter($this->pageNavigation);

        $headerActions = new TElement('div');
        $headerActions->class = ' datagrid-header-actions ';
        $headerActions->style = 'justify-content: space-between;';

        $head_left_actions = new TElement('div');
        $head_left_actions->class = ' datagrid-header-actions-left-actions ';

        $head_right_actions = new TElement('div');
        $head_right_actions->class = ' datagrid-header-actions-left-actions ';

        $headerActions->add($head_left_actions);
        $headerActions->add($head_right_actions);

        $panel->getBody()->insert(0, $headerActions);

        $button_cadastrar = new TButton('button_button_cadastrar');
        $button_cadastrar->setAction(new TAction(['ContaForm', 'onShow']), "Cadastrar");
        $button_cadastrar->addStyleClass('');
        $button_cadastrar->setImage('fas:plus #69aa46');

        $this->datagrid_form->addField($button_cadastrar);

        $btnShowCurtainFilters = new TButton('button_btnShowCurtainFilters');
        $btnShowCurtainFilters->setAction(new TAction(['ContaReceberList', 'onShowCurtainFilters']), "Filtros");
        $btnShowCurtainFilters->addStyleClass('');
        $btnShowCurtainFilters->setImage('fas:filter #000000');

        $this->datagrid_form->addField($btnShowCurtainFilters);

        $button_limpar_filtros = new TButton('button_button_limpar_filtros');
        $button_limpar_filtros->setAction(new TAction(['ContaReceberList', 'onClearFilters']), "Limpar filtros");
        $button_limpar_filtros->addStyleClass('');
        $button_limpar_filtros->setImage('fas:eraser #f44336');

        $this->datagrid_form->addField($button_limpar_filtros);

        $button_atualizar = new TButton('button_button_atualizar');
        $button_atualizar->setAction(new TAction(['ContaReceberList', 'onRefresh']), "Atualizar");
        $button_atualizar->addStyleClass('');
        $button_atualizar->setImage('fas:sync-alt #03a9f4');

        $this->datagrid_form->addField($button_atualizar);

        $mostrar_vencidas = new TButton('button_mostrar_vencidas');
        $mostrar_vencidas->setAction(new TAction(['ContaReceberList', 'onVencidas']), "Vencidas");
        $mostrar_vencidas->addStyleClass('');
        $mostrar_vencidas->setImage('fas:calendar-times #FFC107');

        $this->datagrid_form->addField($mostrar_vencidas);

        $vencer = new TButton('button_vencer');
        $vencer->setAction(new TAction(['ContaReceberList', 'onVencer']), "À vencer");
        $vencer->addStyleClass('');
        $vencer->setImage('fas:calendar-day #4CAF50');

        $this->datagrid_form->addField($vencer);

        $em_aberto = new TButton('button_em_aberto');
        $em_aberto->setAction(new TAction(['ContaReceberList', 'onEmAberto']), "Em aberto");
        $em_aberto->addStyleClass('');
        $em_aberto->setImage('fas:calendar-check #3F51B5');

        $this->datagrid_form->addField($em_aberto);

        $dropdown_button_exportar = new TDropDown("Exportar", 'fas:file-export #2d3436');
        $dropdown_button_exportar->setPullSide('right');
        $dropdown_button_exportar->setButtonClass('btn btn-default waves-effect dropdown-toggle');
        $dropdown_button_exportar->addPostAction( "CSV", new TAction(['ContaReceberList', 'onExportCsv'],['static' => 1]), 'datagrid_'.self::$formName, 'fas:table #00b894' );
        $dropdown_button_exportar->addPostAction( "PDF", new TAction(['ContaReceberList', 'onExportPdf'],['static' => 1]), 'datagrid_'.self::$formName, 'far:file-pdf #e74c3c' );

        $head_left_actions->add($button_cadastrar);
        $head_left_actions->add($btnShowCurtainFilters);
        $head_left_actions->add($button_limpar_filtros);
        $head_left_actions->add($button_atualizar);
        $head_left_actions->add($mostrar_vencidas);
        $head_left_actions->add($vencer);
        $head_left_actions->add($em_aberto);

        $head_right_actions->add($dropdown_button_exportar);

        $this->btnShowCurtainFilters = $btnShowCurtainFilters;

        // vertical box container
        $container = new TVBox;
        $container->style = 'width: 100%';
        if(empty($param['target_container']))
        {
            $container->add(TBreadCrumb::create(["Financeiro","Contas a receber"]));
        }

        $container->add($panel);

        parent::add($container);

    }

    public function onDelete($param = null) 
    { 
        if(isset($param['delete']) && $param['delete'] == 1)
        {
            try
            {
                // get the paramseter $key
                $key = $param['key'];
                // open a transaction with database
                TTransaction::open(self::$database);

                // instantiates object
                $object = new Conta($key, FALSE); 

                // deletes the object from the database
                $object->delete();

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

                // reload the listing
                $this->onReload( $param );
                // shows the success message
                new TMessage('info', AdiantiCoreTranslator::translate('Record deleted'));
            }
            catch (Exception $e) // in case of exception
            {
                // shows the exception error message
                new TMessage('error', $e->getMessage());
                // undo all pending operations
                TTransaction::rollback();
            }
        }
        else
        {
            // define the delete action
            $action = new TAction(array($this, 'onDelete'));
            $action->setParameters($param); // pass the key paramseter ahead
            $action->setParameter('delete', 1);
            // shows a dialog to the user
            new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);   
        }
    }
    public function onExportCsv($param = null) 
    {
        try
        {
            $output = 'app/output/'.uniqid().'.csv';

            if ( (!file_exists($output) && is_writable(dirname($output))) OR is_writable($output))
            {
                $this->limit = 0;
                $objects = $this->onReload();

                if ($objects)
                {
                    $handler = fopen($output, 'w');
                    TTransaction::open(self::$database);

                    foreach ($objects as $object)
                    {
                        $row = [];
                        foreach ($this->datagrid->getColumns() as $column)
                        {
                            $column_name = $column->getName();

                            if (isset($object->$column_name))
                            {
                                $row[] = is_scalar($object->$column_name) ? $object->$column_name : '';
                            }
                            else if (method_exists($object, 'render'))
                            {
                                $column_name = (strpos($column_name, '{') === FALSE) ? ( '{' . $column_name . '}') : $column_name;
                                $row[] = $object->render($column_name);
                            }
                        }

                        fputcsv($handler, $row);
                    }

                    fclose($handler);
                    TTransaction::close();
                }
                else
                {
                    throw new Exception(_t('No records found'));
                }

                TPage::openFile($output);
            }
            else
            {
                throw new Exception(_t('Permission denied') . ': ' . $output);
            }
        }
        catch (Exception $e) // in case of exception
        {
            new TMessage('error', $e->getMessage()); // shows the exception error message
        }
    }
    public function onExportPdf($param = null) 
    {
        try
        {
            $output = 'app/output/'.uniqid().'.pdf';

            if ( (!file_exists($output) && is_writable(dirname($output))) OR is_writable($output))
            {
                $this->limit = 0;
                $this->datagrid->prepareForPrinting();
                $this->onReload();

                $html = clone $this->datagrid;
                $contents = file_get_contents('app/resources/styles-print.html') . $html->getContents();

                $dompdf = new \Dompdf\Dompdf;
                $dompdf->loadHtml($contents);
                $dompdf->setPaper('A4', 'portrait');
                $dompdf->render();

                file_put_contents($output, $dompdf->output());

                $window = TWindow::create('PDF', 0.8, 0.8);
                $object = new TElement('object');
                $object->data  = $output;
                $object->type  = 'application/pdf';
                $object->style = "width: 100%; height:calc(100% - 10px)";

                $window->add($object);
                $window->show();
            }
            else
            {
                throw new Exception(_t('Permission denied') . ': ' . $output);
            }
        }
        catch (Exception $e) // in case of exception
        {
            new TMessage('error', $e->getMessage()); // shows the exception error message
        }
    }
    public static function onShowCurtainFilters($param = null) 
    {
        try 
        {
            //code here

                        $filter = new self([]);

            $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');

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

            $page = new TPage();
            $page->setTargetContainer('adianti_right_panel');
            $page->setProperty('page-name', 'ContaReceberListSearch');
            $page->setProperty('page_name', 'ContaReceberListSearch');
            $page->adianti_target_container = 'adianti_right_panel';
            $page->target_container = 'adianti_right_panel';
            $page->add($filter->form);
            $page->setIsWrapped(true);
            $page->show();

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

            //</autoCode>
        }
        catch (Exception $e) 
        {
            new TMessage('error', $e->getMessage());    
        }
    }
    public function onClearFilters($param = null) 
    {
        TSession::setValue(__CLASS__.'_filter_data', NULL);
        TSession::setValue(__CLASS__.'_filters', NULL);

        $this->onReload(['offset' => 0, 'first_page' => 1]);
    }
    public function onRefresh($param = null) 
    {
        $this->onReload([]);
    }
    public function onVencidas($param = null) 
    {
        try 
        {
            $filters = [new TFilter('id', 'in', "(SELECT conta_id FROM lancamento WHERE dt_vencimento < '". date('Y-m-d 00:00') ."' and quitada = 'N')")];

            $data = new stdClass;
            $data->filtro_rapido = '1';

            TSession::setValue(__CLASS__.'_filter_data', $data);
            TSession::setValue(__CLASS__.'_filters', $filters);

            $this->onReload([]);
            //</autoCode>
        }
        catch (Exception $e) 
        {
            new TMessage('error', $e->getMessage());    
        }
    }
    public function onVencer($param = null) 
    {
        try 
        {
            $filters = [new TFilter('id', 'in', "(SELECT conta_id FROM lancamento WHERE dt_vencimento >= '". date('Y-m-d 00:00') ."' and quitada = 'N')")];

            $data = new stdClass;
            $data->filtro_rapido = '2';

            TSession::setValue(__CLASS__.'_filter_data', $data);
            TSession::setValue(__CLASS__.'_filters', $filters);

            $this->onReload([]);
            //</autoCode>
        }
        catch (Exception $e) 
        {
            new TMessage('error', $e->getMessage());    
        }
    }
    public function onEmAberto($param = null) 
    {
        try 
        {
            $filters = [new TFilter('quitada', '=', 'N')];

            $data = new stdClass;
            $data->quitada = 'N';

            TSession::setValue(__CLASS__.'_filter_data', $data);
            TSession::setValue(__CLASS__.'_filters', $filters);

            $this->onReload([]);
            //</autoCode>
        }
        catch (Exception $e) 
        {
            new TMessage('error', $e->getMessage());    
        }
    }

    /**
     * Register the filter in the session
     */
    public function onSearch($param = null)
    {
        $data = $this->form->getData();
        $filters = [];

        TSession::setValue(__CLASS__.'_filter_data', NULL);
        TSession::setValue(__CLASS__.'_filters', NULL);

        if (isset($data->pessoa_id) AND ( (is_scalar($data->pessoa_id) AND $data->pessoa_id !== '') OR (is_array($data->pessoa_id) AND (!empty($data->pessoa_id)) )) )
        {

            $filters[] = new TFilter('pessoa_id', '=', $data->pessoa_id);// create the filter 
        }

        if (isset($data->descricao) AND ( (is_scalar($data->descricao) AND $data->descricao !== '') OR (is_array($data->descricao) AND (!empty($data->descricao)) )) )
        {

            $filters[] = new TFilter('descricao', 'like', "%{$data->descricao}%");// create the filter 
        }

        if (isset($data->categoria_conta_id) AND ( (is_scalar($data->categoria_conta_id) AND $data->categoria_conta_id !== '') OR (is_array($data->categoria_conta_id) AND (!empty($data->categoria_conta_id)) )) )
        {

            $filters[] = new TFilter('categoria_conta_id', '=', $data->categoria_conta_id);// create the filter 
        }

        if (isset($data->clinica_id) AND ( (is_scalar($data->clinica_id) AND $data->clinica_id !== '') OR (is_array($data->clinica_id) AND (!empty($data->clinica_id)) )) )
        {

            $filters[] = new TFilter('clinica_id', 'in', "(SELECT id FROM conta WHERE clinica_id = '{$data->clinica_id}')");// create the filter 
        }

        if (isset($data->quitada) AND ( (is_scalar($data->quitada) AND $data->quitada !== '') OR (is_array($data->quitada) AND (!empty($data->quitada)) )) )
        {

            $filters[] = new TFilter('quitada', 'like', "%{$data->quitada}%");// create the filter 
        }

        if (isset($data->data_emissao_ini) AND ( (is_scalar($data->data_emissao_ini) AND $data->data_emissao_ini !== '') OR (is_array($data->data_emissao_ini) AND (!empty($data->data_emissao_ini)) )) )
        {

            $filters[] = new TFilter('data_emissao', '>=', $data->data_emissao_ini);// create the filter 
        }

        if (isset($data->data_emissao_fim) AND ( (is_scalar($data->data_emissao_fim) AND $data->data_emissao_fim !== '') OR (is_array($data->data_emissao_fim) AND (!empty($data->data_emissao_fim)) )) )
        {

            $filters[] = new TFilter('data_emissao', '<=', $data->data_emissao_fim);// create the filter 
        }

        if (isset($data->dt_vencimento_ini) AND ( (is_scalar($data->dt_vencimento_ini) AND $data->dt_vencimento_ini !== '') OR (is_array($data->dt_vencimento_ini) AND (!empty($data->dt_vencimento_ini)) )) )
        {

            $filters[] = new TFilter('id', 'in', "(SELECT conta_id FROM lancamento WHERE dt_vencimento >= '{$data->dt_vencimento_ini}')");// create the filter 
        }

        if (isset($data->data_vencimento_fim) AND ( (is_scalar($data->data_vencimento_fim) AND $data->data_vencimento_fim !== '') OR (is_array($data->data_vencimento_fim) AND (!empty($data->data_vencimento_fim)) )) )
        {

            $filters[] = new TFilter('id', 'in', "(SELECT conta_id FROM lancamento WHERE dt_vencimento <= '{$data->data_vencimento_fim}')");// create the filter 
        }

        if (!empty($data->filtro_rapido) && $data->filtro_rapido == 1)
        {
            $filters[] = new TFilter('id', 'in', "(SELECT conta_id FROM lancamento WHERE dt_vencimento < '". date('Y-m-d 00:00') ."' and quitada = 'N')");// vencidas
        }

        if (!empty($data->filtro_rapido) && $data->filtro_rapido == 2)
        {
            $filters[] = new TFilter('id', 'in', "(SELECT conta_id FROM lancamento WHERE dt_vencimento >= '". date('Y-m-d 00:00') ."' and quitada = 'N')");
        }

        // fill the form with data again
        $this->form->setData($data);

        // keep the search data in the session
        TSession::setValue(__CLASS__.'_filter_data', $data);
        TSession::setValue(__CLASS__.'_filters', $filters);

        $this->onReload(['offset' => 0, 'first_page' => 1]);
    }

    /**
     * Load the datagrid with data
     */
    public function onReload($param = NULL)
    {
        try
        {
            // open a transaction with database 'clinica'
            TTransaction::open(self::$database);

            // creates a repository for Conta
            $repository = new TRepository(self::$activeRecord);

            $criteria = clone $this->filter_criteria;

            if (empty($param['order']))
            {
                $param['order'] = 'id';    
            }

            if (empty($param['direction']))
            {
                $param['direction'] = 'desc';
            }

            $criteria->setProperties($param); // order, offset
            $criteria->setProperty('limit', $this->limit);

            if($filters = TSession::getValue(__CLASS__.'_filters'))
            {
                foreach ($filters as $filter) 
                {
                    $criteria->add($filter);       
                }
            }

            //</blockLine><btnShowCurtainFiltersAutoCode>
            if(!empty($this->btnShowCurtainFilters))
            {
                $this->btnShowCurtainFilters->style = 'position: relative';
                $countFilters = count($filters ?? []);
                $this->btnShowCurtainFilters->setLabel($this->btnShowCurtainFilters->getLabel(). "<span class='badge badge-success' style='position: absolute'>{$countFilters}<span>");
            }
            //</blockLine></btnShowCurtainFiltersAutoCode>

            // load the objects according to criteria
            $objects = $repository->load($criteria, FALSE);

            $this->datagrid->clear();
            if ($objects)
            {
                // iterate the collection of active records
                foreach ($objects as $object)
                {

                    $row = $this->datagrid->addItem($object);
                    $row->id = "row_{$object->id}";

                }
            }

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

            $this->pageNavigation->setCount($count); // count of records
            $this->pageNavigation->setProperties($param); // order, page
            $this->pageNavigation->setLimit($this->limit); // limit

            // close the transaction
            TTransaction::close();
            $this->loaded = true;

            return $objects;
        }
        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 onShow($param = null)
    {

    }

    /**
     * method show()
     * Shows the page
     */
    public function show()
    {
        // check if the datagrid is already loaded
        if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'],  $this->showMethods))) )
        {
            if (func_num_args() > 0)
            {
                $this->onReload( func_get_arg(0) );
            }
            else
            {
                $this->onReload();
            }
        }
        parent::show();
    }

}

