<?php
/**
 * @package			No Boss Extensions
 * @subpackage  	No Boss Calendar
 * @author			No Boss Technology <contact@nobosstechnology.com>
 * @copyright		Copyright (C) 2020 No Boss Technology. All rights reserved.
 * @license			GNU Lesser General Public License version 3 or later; see <https://www.gnu.org/licenses/lgpl-3.0.en.html>
 */

defined("JPATH_PLATFORM") or die;

// verificacao necessaria, caso contrario um erro acontece na geracao de tema
if(!class_exists('JFormFieldNobosssubform')){
    require JPATH_LIBRARIES . '/noboss/forms/fields/nobosssubform.php'; 
}

class JFormFieldNobosssubformcalendar extends JFormFieldNobosssubform
{

    protected $type = "nobosssubformcalendar";

    protected $htmlButtonsExtra;

    protected function getInput(){
        // montagem do html dos filtros de ano e mes
        $html = "<div class='calendar-items-filter' data-id='items-filter'>
            <p class='filters-title'>" . JText::_('MOD_NOBOSSCALENDAR_ITEMS_FILTERS_TITLE') . "</p>";
        
        $yearNow = (int)(new JDate())->year;
        $monthNow = (int)(new JDate())->year;
        
        // O value guardou os filtros selecionados no ultimo acesso ao site: aplica ao filtro o ultimo ano e mes selecionados
        if(!empty($_COOKIE['cache-filter'])){
            $tempDate = explode('|', $_COOKIE['cache-filter']);
            $yearSelect = $tempDate[0];
            $monthSelect = $tempDate[1];
            $limitSelect = $tempDate[2];
        }
        if(empty($yearSelect)){
            $yearSelect = $yearNow;
        }
        if(empty($monthSelect)){
            $monthSelect = $monthNow;
        }
        if(empty($limitSelect)){
            $limitSelect = 10;
        }
        
        // campo select de ano
        $html .= "<div class='form-group'>
                    <span>" . JText::_('MOD_NOBOSSCALENDAR_ITEMS_FILTER_YEAR') . "</span>
                    <select class='form-control custom-select' data-id='year-filter'>";

        // Adiciona opcao de selecionar todos os anos
        $html .= "<option value='all' " . ('all' == $yearSelect ? 'selected' : '') . ">" . JText::_('MOD_NOBOSSCALENDAR_ITEMS_FILTER_YEAR_ALL') . "</option>";
        
        // monta as options de anos (3 anos atras, ano atual e 3 anos a frente)
        for($i = $yearNow - 3; $i <= $yearNow + 3; $i++){
            $html .= "<option value='{$i}' " . ($i == $yearSelect ? 'selected' : '') . ">{$i}</option>";
        }
        // fecha o select de anos
        $html .= "</select>
                </div>";

        // Select de meses
        $html .= "<div class='form-group'>
                    <span>" . JText::_('MOD_NOBOSSCALENDAR_ITEMS_FILTER_MONTH') . "</span>
                    <select class='form-control custom-select' data-id='month-filter'>
                        <option value=''>" . JText::_('MOD_NOBOSSCALENDAR_ITEMS_FILTER_MONTH_DEFAULT_OPT') . "</option>
                        <option value='all' " . ('all' == $monthSelect ? 'selected' : '') . ">" . JText::_('MOD_NOBOSSCALENDAR_ITEMS_FILTER_MONTH_ALL') . "</option>
                        <option value='01' " . (1 == $monthSelect ? 'selected' : '') . ">" . JText::_('JANUARY') . "</option>
                        <option value='02' " . (2 == $monthSelect ? 'selected' : '') . ">" . JText::_('FEBRUARY') . "</option>
                        <option value='03' " . (3 == $monthSelect ? 'selected' : '') . ">" . JText::_('MARCH') . "</option>
                        <option value='04' " . (4 == $monthSelect ? 'selected' : '') . ">" . JText::_('APRIL') . "</option>
                        <option value='05' " . (5 == $monthSelect ? 'selected' : '') . ">" . JText::_('MAY') . "</option>
                        <option value='06' " . (6 == $monthSelect ? 'selected' : '') . ">" . JText::_('JUNE') . "</option>
                        <option value='07' " . (7 == $monthSelect ? 'selected' : '') . ">" . JText::_('JULY') . "</option>
                        <option value='08' " . (8 == $monthSelect ? 'selected' : '') . ">" . JText::_('AUGUST') . "</option>
                        <option value='09' " . (9 == $monthSelect ? 'selected' : '') . ">" . JText::_('SEPTEMBER') . "</option>
                        <option value='10' " . (10 == $monthSelect ? 'selected' : '') . ">" . JText::_('OCTOBER') . "</option>
                        <option value='11' " . (11 == $monthSelect ? 'selected' : '') . ">" . JText::_('NOVEMBER') . "</option>
                        <option value='12' " . (12 == $monthSelect ? 'selected' : '') . ">" . JText::_('DECEMBER') . "</option>
                    </select>
                </div>";

        // Select de paginacao dos resultados
        $html .= "<div class='form-group' style='float:right; margin-right:0px;'>
                    <span>" . JText::_('JSHOW') . "</span>
                    <select class='form-control input-mini custom-select' data-id='limit-filter'>
                        <option value='5' " . (5 == $limitSelect ? 'selected' : '') . ">5</option>
                        <option value='10' " . (10 == $limitSelect ? 'selected' : '') . ">10</option>
                        <option value='15' " . (15 == $limitSelect ? 'selected' : '') . ">15</option>
                        <option value='20' " . (20 == $limitSelect ? 'selected' : '') . ">20</option>
                        <option value='all' " . ('all' == $limitSelect ? 'selected' : '') . ">" . JText::_('JALL') . "</option>
                    </select>
                </div>";

        // avisos ao usuario
        $html .= "<div data-id='no-results-alert' class='nobosssubform-alert-result'>" . JText::_('MOD_NOBOSSCALENDAR_NO_ITEMS_ALERT') . "</div>";
        $html .= "<div data-id='no-month-alert' class='nobosssubform-alert-result'>" . JText::_('MOD_NOBOSSCALENDAR_NO_MONTH_SELECTED_ALERT') . "</div>";
        // fecha a div externa dos filtros
        $html .= "</div>";
               
        // Botao de limpeza de eventos antigos
        $this->htmlButtonsExtra = '<a class="btn btn-nb" data-id="cleanoldevents"><span>'.JText::_('MOD_NOBOSSCALENDAR_CLEAN_OLD_EVENTS_BUTTON').'</span></a>';

        // limpa os itens para que eles nao sejam exibidos ao carregar a pagina
        $this->value = array();
        // chama o resto do html do nobosssubform
        $html .= parent::getInput();
        
        $doc = JFactory::getDocument();
        
        // Carrega o js e css do field personalizado
        $doc->addStylesheet(JURI::base()."../modules/mod_nobosscalendar/fields/assets/stylesheets/css/nobosssubformcalendar.min.css");
        $doc->addScript(JURI::base()."../modules/mod_nobosscalendar/fields/assets/js/min/nobosssubformcalendar.min.js");
        
        // adiciona constante no JS
        JText::script('MOD_NOBOSSCALENDAR_SUBFORM_COLLAPSE_TITLE_RECURRENT_INFO');
        JText::script('MOD_NOBOSSCALENDAR_EVENT_RECURRENCE_TYPE_OPT_WEEK_DAYS');
        JText::script('MOD_NOBOSSCALENDAR_EVENT_RECURRENCE_TYPE_OPT_SPECIFIC_DATES');
        JText::script('MOD_NOBOSSCALENDAR_EVENT_RECURRENCE_TYPE_OPT_SPECIFIC_DATES_HOURS');
        JText::script('MOD_NOBOSSCALENDAR_CLEAN_OLD_EVENTS_MODAL_TITLE');
        JText::script('MOD_NOBOSSCALENDAR_CLEAN_OLD_EVENTS_MODAL_TEXT');
        JText::script('MOD_NOBOSSCALENDAR_CLEAN_OLD_EVENTS_MODAL_BUTTON_SUBMIT');
        JText::script('MOD_NOBOSSCALENDAR_CLEAN_OLD_EVENTS_MODAL_REQUIRED');
        JText::script('MOD_NOBOSSCALENDAR_CLEAN_OLD_EVENTS_MODAL_SUCCESS');
        JText::script('MOD_NOBOSSCALENDAR_ITEMS_FILTER_BT_ALL_DIPLAY');
        JText::script('MOD_NOBOSSCALENDAR_MANDATORY_FIELDS_EVENTS');
        
        // Obtem a tag do idioma que esta sendo navegado
        $currentLanguage = JFactory::getLanguage()->getTag();

        /* TODO: modificado para pegar sef do idioma direto no idioma corrente cortando estring (ex: extraimos 'pt' de 'pt-BR')
                - Anteriormente buscavamos o sef dos idiomas de conteúdo instalados, mas isso poderia dar problema pq eles podem estar desabilitados sem que o acesso pelo idioma esteja desabilitado
        */
        // $languages = JLanguageHelper::getLanguages('lang_code');
        // $langSef = $languages[$currentLanguage];
        // $langSef = $langSef->sef;
        $langSef = substr($currentLanguage, 0, 2);

        // Define sefLanguage caso ja nao definido
        if ((version_compare(JVERSION, '4', '>=')) || @!strpos($doc->_script["text/javascript"], "lang")) {
            $doc->addScriptDeclaration('var lang =  "'.$langSef.'";');
        }

        // exibe o field
        return $html;
    }
}
