<?php

class AgendaAgendamentoList extends TPage
{
    private $form; // form
    private $datagrid; // listing
    private $pageNavigation;
    private $loaded;
    private $filter_criteria;
    private static $database = 'clinica';
    private static $activeRecord = 'Agendamento';
    private static $primaryKey = 'id';
    private static $formName = 'form_AgendaAgendamentoList';
    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("Listagem");
        $this->limit = 20;

        $criteria_cliente_id = new TCriteria();
        $criteria_profissional_id = new TCriteria();
        $criteria_agenda_id = new TCriteria();

        $filterVar = Grupo::PACIENTE;
        $criteria_cliente_id->add(new TFilter('id', 'in', "(SELECT pessoa_id FROM pessoa_grupo WHERE grupo_id = '{$filterVar}')")); 
        $filterVar = Grupo::PROFISSIONAL;
        $criteria_profissional_id->add(new TFilter('id', 'in', "(SELECT pessoa_id FROM pessoa_grupo WHERE grupo_id = '{$filterVar}')")); 
        $filterVar = TSession::getValue("userunitid");
        $criteria_agenda_id->add(new TFilter('clinica_id', 'in', "(SELECT id FROM clinica WHERE system_unit_id = '{$filterVar}')")); 

        $cliente_id = new TDBCombo('cliente_id', 'clinica', 'Pessoa', 'id', '{nome_formatado}','nome asc' , $criteria_cliente_id );
        $profissional_id = new TDBCombo('profissional_id', 'clinica', 'Pessoa', 'id', '{nome_formatado}','nome asc' , $criteria_profissional_id );
        $especialidade_id = new TDBCombo('especialidade_id', 'clinica', 'Especialidade', 'id', '{descricao}','descricao asc'  );
        $agenda_id = new TDBCombo('agenda_id', 'clinica', 'Agenda', 'id', '{nome}','nome asc' , $criteria_agenda_id );
        $estado_agenda_id = new TDBCombo('estado_agenda_id', 'clinica', 'EstadoAgenda', 'id', '{nome}','nome asc'  );
        $dt_inicial = new TDate('dt_inicial');
        $dt_final = new TDate('dt_final');


        $dt_final->setMask('dd/mm/yyyy');
        $dt_inicial->setMask('dd/mm/yyyy');

        $dt_final->setDatabaseMask('yyyy-mm-dd');
        $dt_inicial->setDatabaseMask('yyyy-mm-dd');

        $agenda_id->enableSearch();
        $cliente_id->enableSearch();
        $profissional_id->enableSearch();
        $especialidade_id->enableSearch();

        $dt_final->setSize(150);
        $dt_inicial->setSize(150);
        $agenda_id->setSize('100%');
        $cliente_id->setSize('100%');
        $profissional_id->setSize('100%');
        $especialidade_id->setSize('100%');
        $estado_agenda_id->setSize('100%');

        $row1 = $this->form->addFields([new TLabel("Paciente:", null, '14px', null),$cliente_id],[new TLabel("Profissional:", null, '14px', null),$profissional_id],[new TLabel("Especialidade:", null, '14px', null),$especialidade_id]);
        $row1->layout = [' col-sm-4','col-sm-4',' col-sm-4'];

        $row2 = $this->form->addFields([new TLabel("Agenda:", null, '14px', null, '100%'),$agenda_id],[new TLabel("Estado:", null, '14px', null),$estado_agenda_id],[new TLabel("Data:", null, '14px', null, '100%'),$dt_inicial,new TLabel("até", null, '14px', null),$dt_final]);
        $row2->layout = [' col-sm-4',' 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('agenda_id', 'in', "(SELECT id FROM agenda WHERE clinica_id in (SELECT id FROM clinica WHERE system_unit_id = '{$filterVar}'))"));

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

        $column_estado_agenda_cor_transformed = new TDataGridColumn('estado_agenda->cor', "", 'left' , '50px');
        $column_paciente_nome_formatado = new TDataGridColumn('paciente->nome_formatado', "Paciente", 'left');
        $column_agenda_nome = new TDataGridColumn('agenda->nome', "Agenda", 'left');
        $column_especialidade_descricao = new TDataGridColumn('especialidade->descricao', "Especialidade", 'left');
        $column_dt_inicial_transformed = new TDataGridColumn('dt_inicial', "Início ", 'center' , '175px');
        $column_dt_final_transformed = new TDataGridColumn('dt_final', "Fim", 'center' , '175px');
        $column_is_online_transformed = new TDataGridColumn('is_online', "Online", 'center');
        $column_estado_agenda_nome_transformed = new TDataGridColumn('estado_agenda->nome', "Estado", 'center' , '150px');

        $column_estado_agenda_cor_transformed->setTransformer(function($value, $object, $row, $cell = null, $last_row = null)
        {
            if ($value)
            {
                return "<div style='position: relative;text-align: center;'><span class='estado_agendamento' style='background-color: {$value}'></span></div>";
            }

            return '';
        });

        $column_dt_inicial_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 H:i');
                }
                catch (Exception $e)
                {
                    return $value;
                }
            }
        });

        $column_dt_final_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 H:i');
                }
                catch (Exception $e)
                {
                    return $value;
                }
            }
        });

        $column_is_online_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;
        });

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

            return "<span class='label' style='width:235px;background-color:{$object->estado_agenda->cor}'> {$value} <span> "; 

        });        

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

        $criteriaAcesso = new TCriteria;
        // está como um profissional relacionado com a agenda
        $criteriaAcesso->add(new TFilter('agenda_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('agenda_id', 'in', "(SELECT agenda.id FROM agenda, pessoa WHERE pessoa.id = agenda.profissional_id AND system_users_id = '{$filterVar}')"), TExpression::OR_OPERATOR); 

        $this->filter_criteria->add($criteriaAcesso);

        $this->datagrid->addColumn($column_estado_agenda_cor_transformed);
        $this->datagrid->addColumn($column_paciente_nome_formatado);
        $this->datagrid->addColumn($column_agenda_nome);
        $this->datagrid->addColumn($column_especialidade_descricao);
        $this->datagrid->addColumn($column_dt_inicial_transformed);
        $this->datagrid->addColumn($column_dt_final_transformed);
        $this->datagrid->addColumn($column_is_online_transformed);
        $this->datagrid->addColumn($column_estado_agenda_nome_transformed);

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

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

        // 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("Agendamentos");
        $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_agenda = new TButton('button_button_agenda');
        $button_agenda->setAction(new TAction(['AgendamentosFilterForm', 'onShow']), "Agenda");
        $button_agenda->addStyleClass('btn-default');
        $button_agenda->setImage('fas:calendar-alt #FF9800');

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

        $button_novo_agendamento = new TButton('button_button_novo_agendamento');
        $button_novo_agendamento->setAction(new TAction(['AgendamentoCalendarForm', 'onShow']), "Novo agendamento");
        $button_novo_agendamento->addStyleClass('btn-default');
        $button_novo_agendamento->setImage('fas:plus #4CAF50');

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

        $button_filtros = new TButton('button_button_filtros');
        $button_filtros->setAction(new TAction(['AgendaAgendamentoList', 'onShowCurtainFilters']), "Filtros");
        $button_filtros->addStyleClass('btn-default');
        $button_filtros->setImage('fas:filter #000000');

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

        $button_limpar_filtros = new TButton('button_button_limpar_filtros');
        $button_limpar_filtros->setAction(new TAction(['AgendaAgendamentoList', 'onClearFilters']), "Limpar filtros");
        $button_limpar_filtros->addStyleClass('btn-default');
        $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(['AgendaAgendamentoList', 'onRefresh']), "Atualizar");
        $button_atualizar->addStyleClass('btn-default');
        $button_atualizar->setImage('fas:sync-alt #03A9F4');

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

        $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(['AgendaAgendamentoList', 'onExportCsv'],['static' => 1]), 'datagrid_'.self::$formName, 'fas:table #00b894' );
        $dropdown_button_exportar->addPostAction( "PDF", new TAction(['AgendaAgendamentoList', 'onExportPdf'],['static' => 1]), 'datagrid_'.self::$formName, 'far:file-pdf #e74c3c' );

        $head_left_actions->add($button_novo_agendamento);
        $head_left_actions->add($button_filtros);
        $head_left_actions->add($button_limpar_filtros);
        $head_left_actions->add($button_atualizar);

        $head_right_actions->add($button_agenda);
        $head_right_actions->add($dropdown_button_exportar);

        $button_novo_agendamento->getAction()->setParameter('origin', 'list');

        $this->button_filtros = $button_filtros;

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

        $container->add($panel);

        parent::add($container);

    }

    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', 'AgendaAgendamentoListSearch');
            $page->setProperty('page_name', 'AgendaAgendamentoListSearch');
            $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=AgendaAgendamentoListSearch]');
            $style->width = '50% !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) 
    {
        try 
        {
            $this->onReload(['offset' => 0, 'first_page' => 1]);
            //</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->cliente_id) AND ( (is_scalar($data->cliente_id) AND $data->cliente_id !== '') OR (is_array($data->cliente_id) AND (!empty($data->cliente_id)) )) )
        {

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

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

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

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

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

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

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

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

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

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

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

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

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

        $this->button_filtros->style = 'position: relative';
        $countFiltros = count($filters);

        if ($countFiltros)
        {
            $this->button_filtros->setLabel('Filtros'. "<span class='badge badge-success' style='position: absolute'>{$countFiltros}<span>");
        }

        // 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 Agendamento
            $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);       
                }
            }

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

}

