<?php

/**
 * Indices do array de quebras $tab_quebra:
 * - 0 : nome da quebra em minusculo
 * - 13: direcao de ordenacao da quebra
 * - 19: nome da quebra na forma original
 */
define("SC_GROUPBY_NAME_LOWER", 0);
define("SC_GROUPBY_DEFINITION", 3);
define("SC_GROUPBY_LABEL", 4);
define("SC_GROUPBY_DISPLAY_CHART", 5);
define("SC_GROUPBY_ORDER_DIRECTION", 13);
define("SC_GROUPBY_DATATYPE", 17);
define("SC_GROUPBY_SEQ", 18);
define("SC_GROUPBY_NAME_ORIGINAL", 19);

/**
 * Indices do array de sumarizacoes $arr_ordem_res:
 * - 0: nome da sumarizacao
 * - 1: funcao da sumarizacao
 */
define("SC_SUMM_ORDER_NAME", 0);
define("SC_SUMM_ORDER_FUNC", 1);

function prepareSummaryInfo()
{
    global $summaryInfo;

    $summaryInfo = [];

    fnSum_infoGet_general();
    fnSum_infoGet_options();
    fnSum_infoGet_order();

    fnSum_infoGet_fields_setFields();

    fnSum_infoGet_dimension_setFields();
    fnSum_infoGet_metric_setFields();

    fnSum_infoGet_groupBy_initialize();
    fnSum_infoGet_groupBy_options();
    fnSum_infoGet_groupBy_setAxysFieldList();
    fnSum_infoGet_groupBy_setMetricFieldList();

    fnSum_infoGet_chart_options();
    fnSum_infoGet_chart_setFields();

    fnSum_infoGet_restrictVersionFeatures();
} // prepareSummaryInfo

function fnSum_infoGet_general()
{
    global $summaryInfo, $nome_aplicacao, $dir_apl, $tbapl_idioma, $apl_modules, $tbapl_tp_apl, $arquivo3;

    $summaryInfo['general'] = [
        'app_name_var' => $nome_aplicacao,
        'app_name_function' => $nome_aplicacao,
        'app_name_link_var' => $nome_aplicacao,
        'app_name_file' => $nome_aplicacao,
        'app_name_session_var' => $nome_aplicacao,
        'app_dir' => $dir_apl,
        'app_language' => $tbapl_idioma,
        'app_type' => $tbapl_tp_apl,
        'app_link_base_file' => $arquivo3,
        'modules' => $apl_modules,
    ];
} // fnSum_infoGet_general

function fnSum_infoGet_options()
{
    global $summaryInfo, $apl_cab_res_mostra, $apl_rod_res_mostra, $parms_tbapl_attr1, $res_barr_embbed,
           $tbapl_attr4_parms, $tbapl_hist_tot_hor, $tbapl_hist_tot_vert, $apl_tem_fixed_column_summary,
           $tbapl_use_grid_order_icons, $apl_graf_outra_pag, $flagVersao, $prj_fav_icon, $tbapl_grid_pos_resumo,
           $tab_cmp, $parms_tbapl_attr2, $tbapl_grid_mostra_resumo;

    $comparisonFieldLabel = "''";
    foreach ($tab_cmp as $fieldSeq => $fieldInfo) {
        if ($fieldInfo['nmgp_date_comparison']) {
            $comparisonFieldLabel = label_dynamic_search($fieldSeq);
        }
    }

    if (3 == $tbapl_attr4_parms['summary_gridpostotal']) {
        $displaySummaryTotalOption = 'no';
    } elseif (2 == $tbapl_attr4_parms['summary_gridpostotal']) {
        $displaySummaryTotalOption = 'last_page';
    } else {
        $displaySummaryTotalOption = 'all_pages';
    }

    $summaryLabel = isset($parms_tbapl_attr1['summary_format_summary']) && '' != $parms_tbapl_attr1['summary_format_summary'] ? $parms_tbapl_attr1['summary_format_summary'] : '{lang_othr_smry_info}';
    fnSum_infoGet_pregString($summaryLabel);

    $hasSummaryButton = false;
    $searchButtonPos = ['top_left', 'top_right', 'top_center', 'bottom_left', 'bottom_right', 'bottom_center'];
    foreach ($searchButtonPos as $buttonPos) {
        foreach ($parms_tbapl_attr2['botoes_resume'] [$buttonPos] as $buttonName) {
            if ('sys_format_rows' == substr($buttonName, -15)) {
                $hasSummaryButton = true;
                break;
            }
        }
    }

    // flags gerais
    $summaryInfo['options'] = [
        'chart_icon_position_data' => 'R' == $parms_tbapl_attr1['icon_data_align'] ? 'right' : 'left',
        'chart_icon_position_total' => 'R' == $parms_tbapl_attr1['icon_total_align'] ? 'right' : 'left',
        'chart_new_page' => 'N' == $apl_graf_outra_pag,
        'comparison_field_label' => $comparisonFieldLabel,
        'display_abbreviated_value' => 'S' == $parms_tbapl_attr1['summary_valor_abrev'],
        'display_footer' => 'S' == $apl_rod_res_mostra,
        'display_groupby_onhover' => isset($tbapl_attr4_parms['graf_habilitar_hover']) && 'S' == $tbapl_attr4_parms['graf_habilitar_hover'],
        'display_header' => 'S' == $apl_cab_res_mostra,
        'display_header_pdf' => 'S' == $apl_cab_res_mostra && 2 != $tbapl_grid_mostra_resumo,
        'display_label_on_total' => isset($tbapl_attr4_parms['graf_label_total']) && '2' == $tbapl_attr4_parms['graf_label_total'],
        'display_inline_chart' => isset($tbapl_attr4_parms['chart_inline_summary']) && 'S' == $tbapl_attr4_parms['chart_inline_summary'],
        'display_seq' => isset($tbapl_attr4_parms['graf_num_linha']) && 'S' == $tbapl_attr4_parms['graf_num_linha'],
        'display_summary_every_page' => isset($tbapl_attr4_parms['summary_exibir_sumario']) && 'S' == $tbapl_attr4_parms['summary_exibir_sumario'],
        'display_summary_label' => $summaryLabel,
        'display_summary_total' => $displaySummaryTotalOption,
        'display_total_column' => 'S' == $tbapl_hist_tot_vert,
        'display_total_row' => 'S' == $tbapl_hist_tot_hor,
        'display_total_top' => 'top' == $parms_tbapl_attr1['summary_total_position'],
        'embbed_config_windows' => $res_barr_embbed,
        'favicon' => $prj_fav_icon,
        'has_fixed_columns' => $apl_tem_fixed_column_summary,
        'has_summary_button' => $hasSummaryButton,
        'show_percentuals' => false,
        'use_fontawesome' => $flagVersao['opcao_fontawesome'],
        'use_fontawesome_order_icons' => $tbapl_use_grid_order_icons,
        'use_pagination' => isset($tbapl_attr4_parms['summary_gridlinhaspagina']) && '2' == $tbapl_attr4_parms['summary_gridlinhaspagina'] && 3 == $tbapl_grid_pos_resumo,
        'page_length' => isset($tbapl_attr4_parms['summary_gridlinhaspaginanumero']) && '' != $tbapl_attr4_parms['summary_gridlinhaspaginanumero'] ? $tbapl_attr4_parms['summary_gridlinhaspaginanumero'] : 10,
        'page_link_count' => isset($parms_tbapl_attr1['summary_qtdpages']) && '' != $parms_tbapl_attr1['summary_qtdpages'] ? $parms_tbapl_attr1['summary_qtdpages'] : 5,
        'page_goto_mode' => isset($parms_tbapl_attr1['summary_page_or_seq']) && '' != $parms_tbapl_attr1['summary_page_or_seq'] ? $parms_tbapl_attr1['summary_page_or_seq'] : 'page',
    ];
} // fnSum_infoGet_options

function fnSum_infoGet_order()
{
    global $summaryInfo, $tbapl_attr4_parms;

    // dados de ordenacao
    $summaryInfo['order'] = [
        'fontawesome_icons_alpha' => $tbapl_attr4_parms['grid_order_icons_alpha'],
        'fontawesome_icons_numeric' => $tbapl_attr4_parms['grid_order_icons_numeric'],
    ];
} // fnSum_infoGet_options

function fnSum_infoGet_fields_setFields()
{
    global $summaryInfo, $tab_cmp;

    $summaryInfo['fields_by_lower'] = [];

    foreach ($tab_cmp as $fieldSeq => $fieldInfo) {
        $summaryInfo['fields_by_lower'] [ $fieldInfo['nmgp_campo'] ] = $fieldInfo['nmgp_campo_or'];
    }
} // fnSum_infoGet_options

function fnSum_infoGet_dimension_setFields()
{
    global $summaryInfo, $tbapl_arr_quebras, $tab_cmp, $nm_tipo_dado_banco_def, $arr_campos_orig,
           $tab_cmp_seq, $compat_ind_quebras;

    foreach ($tbapl_arr_quebras as $groupByIndex => $groupByInfo) {
        $summaryInfo['group_by'] [$groupByIndex] ['dimension'] = [];
        $summaryInfo['group_by'] [$groupByIndex] ['metric'] = [];
        $summaryInfo['group_by'] [$groupByIndex] ['metric_by_index'] = [];
        $summaryInfo['group_by'] [$groupByIndex] ['dimension_by_lowercase'] = [];
        $summaryInfo['group_by'] [$groupByIndex] ['dimension_by_old'] = [];

        foreach ($groupByInfo['tab_quebra'] as $groupByData) {
            // recuperacao da entrada no array de dados da tabela tbcmp relativa a esta quebra
            if (isset($arr_campos_orig[ $groupByData[SC_GROUPBY_SEQ] ])) {
                $groupByName = $arr_campos_orig[ $groupByData[SC_GROUPBY_SEQ] ];
                $fieldData = $tab_cmp[ $groupByData[SC_GROUPBY_SEQ] ];
            }
            else {
                $groupByName = $groupByData[SC_GROUPBY_NAME_ORIGINAL];
                if (isset($tab_cmp_seq[$groupByName])) {
                    $fieldData = $tab_cmp[ $tab_cmp_seq[$groupByName] ];
                } elseif (isset($tab_cmp_seq[strtolower($groupByName)])) {
                    $fieldData = $tab_cmp[ $tab_cmp_seq[strtolower($groupByName)] ];
                }
            }

            $variableName = fnSum_infoGet_fieldVarName($groupByData[SC_GROUPBY_NAME_ORIGINAL]);

            // recuperacao de dados adicionais
            $groupByInfo_quebras = fnSum_infoGet_dimension_groupByInfoQuebras($groupByInfo, $groupByData);
            $groupByInfo_layout = fnSum_infoGet_dimension_groupByInfoLayout($groupByIndex, $groupByData);
            $groupByNameOld = fnSum_infoGet_dimension_groupByNameOld($groupByIndex, $groupByData);

            // definicao do label
            $groupByLabel = "\"" . $groupByInfo_quebras['fld_group_label_field'] . "\"";
            if (!isset($groupByInfo_quebras['fld_group_usar_label_data']) || $groupByInfo_quebras['fld_group_usar_label_data'] == "S") {
                if (isset($groupByInfo_quebras['nmgp_quebra_label_title']) && !empty($groupByInfo_quebras['nmgp_quebra_label_title'])) {
                    $groupByLabel = "sprintf(\"" . $groupByInfo_quebras['nmgp_quebra_label_title'] . "\", $groupByLabel)";
                }
            }

            // definicao dos dados para montagem do link para a consulta
            $linkProtectString  = '@aspass@';
            $linkFieldVarName = $groupByData[SC_GROUPBY_NAME_ORIGINAL];
            $fieldNameLower = $groupByData[SC_GROUPBY_NAME_LOWER];
            $fieldDefinition = $groupByData[SC_GROUPBY_DEFINITION];
            $fieldProtected = $groupByData[SC_GROUPBY_NAME_ORIGINAL];
            protect_campo($fieldProtected);
            $fieldProtected = str_replace(".", "_", $fieldProtected);
            if ($fieldProtected == $fieldNameLower || strtolower($fieldProtected) == $fieldNameLower) {
                foreach ($nm_tipo_dado_banco_def as $fieldDbTypeDefinition => $dbTypeDefinitionData) {
                    if ($fieldDbTypeDefinition == $fieldDefinition) {
                        $linkProtectString = '';
                    }
                }
                $linkFieldVarName = $fieldNameLower;
            }

            // definicao da ordenacao
            $hasOrder = false;
            if (isset($groupByInfo['ord_fld_tot_res_reg'])) {
                foreach ($groupByInfo['ord_fld_tot_res_reg'] as $fieldOrderData) {
                    $fieldOrderDataParts = explode('_#NM#_', $fieldOrderData);
                    if ('dimension' == $fieldOrderDataParts[0] && isset($fieldOrderDataParts[1]) && $fieldOrderDataParts[1] && isset($compat_ind_quebras[$groupByIndex]) && isset($compat_ind_quebras[$groupByIndex] [ $fieldOrderDataParts[1] ]) && $compat_ind_quebras[$groupByIndex] [ $fieldOrderDataParts[1] ]) {
                        $fieldOrderSeq = $compat_ind_quebras[$groupByIndex] [ $fieldOrderDataParts[1] ];
                        if ($tab_cmp[$fieldOrderSeq] ['nmgp_campo_or'] == $groupByData[SC_GROUPBY_NAME_ORIGINAL]) {
                            $hasOrder = true;
                        }
                    }
                }
            }

            $isRating = $fieldData['rating_use_in_summary'] && in_array($fieldData['nmgp_tipo_dado'], array('RATING', 'RATINGSTAR', 'RATINGSMILE', 'RATINGTHUMBS'));

            $summaryInfo['group_by'] [$groupByIndex] ['dimension'] [ $groupByData[SC_GROUPBY_NAME_ORIGINAL] ] = [
                'label' => $groupByLabel,
                'label_json_off' => $fieldData['nmgp_campo_or'],
                'datatype' => $groupByData[SC_GROUPBY_DATATYPE],
                'lowercase' => $groupByData[SC_GROUPBY_NAME_LOWER],
                'php_var_name' => $variableName,
                'summary_values_array' => 'array_total_' . $variableName,
                'summary_line_values_array' => 'array_line_' . $variableName,
                'order_by_index' => isset($groupByInfo_layout['order']) && 'B' == $groupByInfo_layout['order'] ? 'self::TOTAL_ARRAY_VALUE_INDEX' : 'self::TOTAL_ARRAY_LABEL_INDEX',
                'order_by_direction' => 'desc' == $groupByInfo_quebras['nmgp_ord_quebra'] ? 'desc' : 'asc',
                'rating_function' => $isRating ? 'getFieldHtml_' . $groupByName : '',
                'fill_empty_axys' => isset($groupByInfo_layout['show_empty']) && 'S' != $groupByInfo_layout['show_empty'] ? 'false' : 'true',
                'align_css_class' => isset($groupByInfo_layout['align']) && '' != $groupByInfo_layout['align'] ? 'sc-align-' . $groupByInfo_layout['align'] : '',
                'show_link' => isset($groupByInfo_layout['link_grid']) && 'S' != $groupByInfo_layout['link_grid'] ? 'false' : 'true',
                'link_field_var_name' => $linkFieldVarName,
                'link_protect_string' => $linkProtectString,
                'has_order' => $hasOrder,
                'limit_chart_items' => isset($groupByInfo_quebras['fld_group_chart_limit_items']) && '' != $groupByInfo_quebras['fld_group_chart_limit_items'] ? $groupByInfo_quebras['fld_group_chart_limit_items'] : '0',
            ];

            $summaryInfo['group_by'] [$groupByIndex] ['dimension_by_lowercase'] [ $groupByData[SC_GROUPBY_NAME_LOWER] ] = $groupByData[SC_GROUPBY_NAME_ORIGINAL];
            $summaryInfo['group_by'] [$groupByIndex] ['dimension_by_old'] [ $groupByNameOld ] = $groupByData[SC_GROUPBY_NAME_ORIGINAL];
        }
    }
} // fnSum_infoGet_dimension_setFields

function fnSum_infoGet_metric_setFields()
{
    global $summaryInfo, $arr_tot_res, $arr_ordem_res, $tbapl_arr_quebras;

    foreach ($arr_tot_res as $groupByIndex => $groupByInfo) {
        foreach ($groupByInfo as $fieldName => $summarizationList) {
            foreach ($summarizationList as $summarizationFunction => $summarizationInfo) {
                $metricIndex = $fieldName . '-' . $summarizationFunction;
                $variableName = fnSum_infoGet_fieldVarName($metricIndex);

                $valueIndex = '';
                $metricInfo = [];
                if (isset($arr_ordem_res[$groupByIndex])) {
                    foreach ($arr_ordem_res[$groupByIndex] as $orderIndex => $orderInfo) {
                        if ($orderInfo[SC_SUMM_ORDER_NAME] . '-' . $orderInfo[SC_SUMM_ORDER_FUNC] == $metricIndex) {
                            $valueIndex = $orderIndex;
                            $metricInfo = $orderInfo;
                            break;
                        }
                    }
                }

                if ('' === $valueIndex || empty($metricInfo)) {
                    continue;
                }

                $metricFullName = fnSum_infoGet_metricName($metricInfo[SC_SUMM_ORDER_NAME], $metricInfo[SC_SUMM_ORDER_FUNC]);
                $totFieldRes = fnSum_infoGet_metric_totFieldRes($groupByIndex, $metricFullName);

                $hasOrder = false;
                if (isset($tbapl_arr_quebras[$groupByIndex] ['ord_fld_tot_res_reg'])) {
                    foreach ($tbapl_arr_quebras[$groupByIndex] ['ord_fld_tot_res_reg'] as $fieldOrderData) {
                        $fieldOrderDataParts = explode('_#NM#_', $fieldOrderData);
                        if (1 == count($fieldOrderDataParts)) {
                            if ($metricFullName == strtolower($fieldOrderData)) {
                                $hasOrder = true;
                            } elseif ($metricFullName == str_replace('.', '_', strtolower($fieldOrderData))) {
                                $hasOrder = true;
                            }
                        }
                    }
                }

                $originalFieldName = 'NM_Count' == $metricInfo[SC_SUMM_ORDER_NAME] ? '' : $summaryInfo['fields_by_lower'] [$fieldName];

                if (!isset($totFieldRes['tot_res_linha_visu_campo_align'])) {
                    $labelJustifyContent = 'flex-end';
                } elseif (1 == $totFieldRes['tot_res_linha_visu_campo_align']) {
                    $labelJustifyContent = 'flex-start';
                } elseif (3 == $totFieldRes['tot_res_linha_visu_campo_align']) {
                    $labelJustifyContent = 'center';
                } else {
                    $labelJustifyContent = 'flex-end';
                }

                $summaryInfo['group_by'] [$groupByIndex] ['metric'] [ $metricIndex ] = [
                    'label' => $summarizationInfo['label'],
                    'label_justify_content' => $labelJustifyContent,
                    'css_var_name' => $variableName,
                    'chart_var_name' => fnSum_infoGet_chartVarName($metricInfo[SC_SUMM_ORDER_NAME], $metricInfo[SC_SUMM_ORDER_FUNC], $originalFieldName),
                    'value_index' => $valueIndex + 1,
                    'is_rating' => '' != $groupByInfo[$fieldName] [$summarizationFunction] ['rating'],
                    'rating_function' => $groupByInfo[$fieldName] [$summarizationFunction] ['rating'],
                    'format_function' => 'aux_format_' . str_replace('-', '_', $metricIndex),
                    'sc_format_function' => str_replace('valor_campo', 'value', $groupByInfo[$fieldName] [$summarizationFunction] ['format']),
                    'negative_color' => isset($groupByInfo[$fieldName] [$summarizationFunction] ['cor_negat']) && '' != $groupByInfo[$fieldName] [$summarizationFunction] ['cor_negat'] ? $groupByInfo[$fieldName] [$summarizationFunction] ['cor_negat'] : '',
                    'css_class' => 'css_' . $metricFullName . '_field',
                    'has_order' => $hasOrder,
                    'show_percentuals' => isset($totFieldRes['show_perc_total']) && 'S' == $totFieldRes['show_perc_total'],
                    'show_percentuals_below' => isset($totFieldRes['show_perc_total_pos']) && 'bottom' == $totFieldRes['show_perc_total_pos'],
                ];

                $summaryInfo['group_by'] [$groupByIndex] ['metric_by_index'] [ ($valueIndex + 2) ] = $metricIndex;

                if ($summaryInfo['group_by'] [$groupByIndex] ['metric'] [ $metricIndex ] ['show_percentuals']) {
                    $summaryInfo['options'] ['show_percentuals'] = true;
                }
            }
        }
    }
} // fnSum_infoGet_metric_setFields

function fnSum_infoGet_groupBy_initialize()
{
    global $summaryInfo, $tbapl_arr_quebras;

    foreach ($tbapl_arr_quebras as $groupByIndex => $groupByInfo) {
        $summaryInfo['group_by'] [$groupByIndex] ['group_by'] = [
            'dimension' => [
                'x' => [],
                'y' => [],
                'order' => [],
                'unselected' => [],
            ],
            'metric' => [],
            'options' => [],
            'is_dynamic' => false,
        ];
    }
} // fnSum_infoGet_groupBy_initialize

function fnSum_infoGet_groupBy_options()
{
    global $summaryInfo, $tbapl_arr_quebras, $nm_totaliza_php;

    foreach ($tbapl_arr_quebras as $groupByIndex => $groupByInfo) {
        $orderInitialMetric = '';
        if (isset($groupByInfo['ord_fld_tot_res_def'])) {
            foreach ($summaryInfo['group_by'] [$groupByIndex] ['metric'] as $metricName => $metricInfo) {
                if ($groupByInfo['ord_fld_tot_res_def'] == $metricInfo['chart_var_name']) {
                    $orderInitialMetric = $metricName;
                } elseif ('__NM_COUNT_NM___cnt' == $groupByInfo['ord_fld_tot_res_def'] && '__NM_COUNT_NM__' == $metricInfo['chart_var_name']) {
                    $orderInitialMetric = $metricName;
                }
            }
        }

        $summaryInfo['group_by'] [$groupByIndex] ['group_by'] ['options'] ['tabular'] = isset($groupByInfo['res_layout'] ['format_tab']) && 'S' == $groupByInfo['res_layout'] ['format_tab'];
        $summaryInfo['group_by'] [$groupByIndex] ['group_by'] ['is_dynamic'] = 'sc_free_group_by' == $groupByIndex;
        $summaryInfo['group_by'] [$groupByIndex] ['group_by'] ['has_total_php'] = $nm_totaliza_php[$groupByIndex];
        $summaryInfo['group_by'] [$groupByIndex] ['group_by'] ['order_initial_metric'] = $orderInitialMetric;
        $summaryInfo['group_by'] [$groupByIndex] ['group_by'] ['order_initial_rule'] = isset($groupByInfo['ord_fld_tot_res_type']) ? $groupByInfo['ord_fld_tot_res_type'] : '';
        $summaryInfo['group_by'] [$groupByIndex] ['group_by'] ['order_initial_dimension'] = isset($groupByInfo['ord_fld_tot_res_start']) && '' != $groupByInfo['ord_fld_tot_res_start'] ? (int)$groupByInfo['ord_fld_tot_res_start'] : 1;
    }
} // fnSum_infoGet_groupBy_options

function fnSum_infoGet_groupBy_setAxysFieldList()
{
    global $tbapl_arr_quebras;

    foreach ($tbapl_arr_quebras as $groupByName => $groupByInfo) {
        if ('sc_free_group_by' == $groupByName) {
            fnSum_infoGet_groupBy_setAxysFieldList_dynamic($groupByInfo['quebras'], $groupByName);
        } else {
            fnSum_infoGet_groupBy_setAxysFieldList_static($groupByInfo['res_layout'] ['fields'], $groupByName);
        }
    }
} // fnSum_infoGet_groupBy_setAxysFieldList

function fnSum_infoGet_groupBy_setAxysFieldList_dynamic($groupByInfo, $groupByName)
{
    global $summaryInfo;

    foreach ($groupByInfo as $groupByFieldNameOriginal => $groupByFieldInfo) {
        if (isset($summaryInfo['group_by'] [$groupByName] ['dimension'] [$groupByFieldNameOriginal])) {
            $groupByNameToUse = $groupByFieldNameOriginal;
        } elseif (isset($summaryInfo['group_by'] [$groupByName] ['dimension_by_old'] [$groupByFieldNameOriginal])) {
            $groupByNameToUse = $summaryInfo['group_by'] [$groupByName] ['dimension_by_old'] [$groupByFieldNameOriginal];
        } else {
            $groupByNameToUse = $groupByNameToUse;
        }

        if ('Y' == $groupByFieldInfo['start']) {
            $summaryInfo['group_by'] ['sc_free_group_by'] ['group_by'] ['dimension'] ['y'] [] = $groupByNameToUse;
            $summaryInfo['group_by'] ['sc_free_group_by'] ['group_by'] ['dimension'] ['order'] [] = $groupByNameToUse;
        } else {
            $summaryInfo['group_by'] ['sc_free_group_by'] ['group_by'] ['dimension'] ['unselected'] [] = $groupByNameToUse;
        }
    }
} // fnSum_infoGet_groupBy_setAxysFieldList_dynamic

function fnSum_infoGet_groupBy_setAxysFieldList_static($groupByInfo, $groupByName)
{
    global $summaryInfo;

    foreach ($groupByInfo as $groupByFieldNameOriginal => $groupByFieldInfo) {
        if (isset($summaryInfo['group_by'] [$groupByName] ['dimension'] [$groupByFieldNameOriginal])) {
            $groupByNameToUse = $groupByFieldNameOriginal;
        } elseif (isset($summaryInfo['group_by'] [$groupByName] ['dimension_by_old'] [$groupByFieldNameOriginal])) {
            $groupByNameToUse = $summaryInfo['group_by'] [$groupByName] ['dimension_by_old'] [$groupByFieldNameOriginal];
        } else {
            $groupByNameToUse = $groupByFieldNameOriginal;
        }

        if ('X' == $groupByFieldInfo['position']) {
            $summaryInfo['group_by'] [$groupByName] ['group_by'] ['dimension'] ['x'] [] = $groupByNameToUse;
            $summaryInfo['group_by'] [$groupByName] ['group_by'] ['dimension'] ['order'] [] = $groupByNameToUse;
        } else {
            $summaryInfo['group_by'] [$groupByName] ['group_by'] ['dimension'] ['y'] [] = $groupByNameToUse;
            $summaryInfo['group_by'] [$groupByName] ['group_by'] ['dimension'] ['order'] [] = $groupByNameToUse;
        }
    }
} // fnSum_infoGet_groupBy_setAxysFieldList_static

function fnSum_infoGet_groupBy_setMetricFieldList()
{
    global $summaryInfo, $arr_ordem_res, $arr_display_res;

    foreach ($arr_ordem_res as $groupByName => $groupByInfo) {
        foreach ($groupByInfo as $metricInfo) {
            if (isset($arr_display_res[$groupByName] [ $metricInfo[SC_SUMM_ORDER_NAME] ]) && in_array($metricInfo[SC_SUMM_ORDER_FUNC], $arr_display_res[$groupByName] [ $metricInfo[SC_SUMM_ORDER_NAME] ])) {
                $summaryInfo['group_by'] [$groupByName] ['group_by'] ['metric'] [] = $metricInfo[SC_SUMM_ORDER_NAME] . '-' . $metricInfo[SC_SUMM_ORDER_FUNC];
            }
        }
    }
} // fnSum_infoGet_groupBy_setMetricFieldList

function fnSum_infoGet_chart_options()
{
    global $summaryInfo, $parms_tbapl_attr1, $tbapl_graf_largura, $tbapl_graf_altura, $tbapl_attr4_parms, $nm_config;

    $summaryInfo['chart'] = [];

    $availableTypes = [];
    $availableComparisonTypes = [];
    if ('' === $parms_tbapl_attr1['graf_tp_flash'] || '0' === $parms_tbapl_attr1['graf_tp_flash']) {
        $aFlashGrafs = array('100');
    } else {
        $aFlashGrafs = explode('_@NM@_', $parms_tbapl_attr1['graf_tp_flash']);
    }
    foreach ($aFlashGrafs as $sFlashGraf) {
        switch ($sFlashGraf) {
            case '100':
                $availableTypes[] = 'Bar';
                $availableComparisonTypes[] = 'Bar';
                fnSum_infoGet_chart_options_bar();
                break;
            case '101':
                $availableTypes[] = 'Pie';
                fnSum_infoGet_chart_options_pie();
                break;
            case '102':
                $availableTypes[] = 'Line';
                $availableComparisonTypes[] = 'Line';
                fnSum_infoGet_chart_options_line();
                break;
            case '103':
                $availableTypes[] = 'Area';
                $availableComparisonTypes[] = 'Area';
                fnSum_infoGet_chart_options_area();
                break;
            case '105':
                $availableTypes[] = 'Gauge';
                fnSum_infoGet_chart_options_gauge();
                break;
            case '106':
                $availableTypes[] = 'Radar';
                $availableComparisonTypes[] = 'Radar';
                fnSum_infoGet_chart_options_radar();
                break;
            case '108':
                $availableTypes[] = 'Funnel';
                fnSum_infoGet_chart_options_funnel();
                break;
            case '109':
                $availableTypes[] = 'Pyramid';
                fnSum_infoGet_chart_options_pyramid();
                break;
        }
    }

    if (0 == count($availableTypes)) {
        $availableTypes = ['Bar'];
        fnSum_infoGet_chart_options_bar();
    }
    if (0 == count($availableComparisonTypes)) {
        $availableComparisonTypes = ['Bar'];

        if (!in_array('Bar', $availableTypes)) {
            fnSum_infoGet_chart_options_bar();
        }
    }

    switch ($parms_tbapl_attr1['graf_option']) {
        default:
        case 1:
            $summaryInfo['chart'] ['available_modes'] = ['synthetic'];
            $summaryInfo['chart'] ['default_mode'] = 'synthetic';
            break;
        case 2:
            $summaryInfo['chart'] ['available_modes'] = ['analytic'];
            $summaryInfo['chart'] ['default_mode'] = 'analytic';
            break;
        case 3:
            $summaryInfo['chart'] ['available_modes'] = ['synthetic', 'analytic'];
            $summaryInfo['chart'] ['default_mode'] = 'analytic';
            break;
        case 4:
            $summaryInfo['chart'] ['available_modes'] = ['synthetic', 'analytic'];
            $summaryInfo['chart'] ['default_mode'] = 'synthetic';
            break;
    }

    $summaryInfo['chart'] ['available_types'] = $availableTypes;
    $summaryInfo['chart'] ['available_comparison_types'] = $availableComparisonTypes;
    $summaryInfo['chart'] ['default_type'] = $availableTypes[0];
    $summaryInfo['chart'] ['width'] = $tbapl_graf_largura;
    $summaryInfo['chart'] ['height'] = $tbapl_graf_altura;
    $summaryInfo['chart'] ['inline_width'] = $tbapl_attr4_parms['chart_inline_width'];
    $summaryInfo['chart'] ['inline_height'] = $tbapl_attr4_parms['chart_inline_height'];
    $summaryInfo['chart'] ['has_limit_chart_items'] = $nm_config['flag_versao']['summary_new']['has'];
    $summaryInfo['chart'] ['chart_create_time'] = isset($parms_tbapl_attr1['chart_create_time']) && '' != $parms_tbapl_attr1['chart_create_time'] ? $parms_tbapl_attr1['chart_create_time'] : '150';
    $summaryInfo['chart'] ['tooltip_expanded'] = 'S' == $tbapl_attr4_parms['tooltip_expanded'];
    $summaryInfo['chart'] ['formatNumberScale'] = 'S' == $parms_tbapl_attr1['flsh_chrt_valor_abrev'];
    $summaryInfo['chart'] ['legendPosition'] = $parms_tbapl_attr1['graf_subtitle_val'];
    $summaryInfo['chart'] ['setAdaptiveYMin'] = 'S' == $tbapl_attr4_parms['adaptive_y_axis'];
}

function fnSum_infoGet_chart_options_area()
{
    global $summaryInfo, $parms_tbapl_attr1;

    $summaryInfo['chart'] ['types'] ['area'] = [
        'format' => isset($parms_tbapl_attr1['flsh_chrt_area_forma']) && '' != $parms_tbapl_attr1['flsh_chrt_area_forma'] ? $parms_tbapl_attr1['flsh_chrt_area_forma'] : 'Area',
    ];
}

function fnSum_infoGet_chart_options_bar()
{
    global $summaryInfo, $parms_tbapl_attr1;

    $summaryInfo['chart'] ['types'] ['bar'] = [
        'orientation' => isset($parms_tbapl_attr1['flsh_chrt_barra_orien']) && '' != $parms_tbapl_attr1['flsh_chrt_barra_orien'] ? $parms_tbapl_attr1['flsh_chrt_barra_orien'] : 'Vertical',
        'dimension' => isset($parms_tbapl_attr1['flsh_chrt_barra_dimen']) && '' != $parms_tbapl_attr1['flsh_chrt_barra_dimen'] ? $parms_tbapl_attr1['flsh_chrt_barra_dimen'] : '2d',
        'plotSpacePercent' => isset($parms_tbapl_attr1['flsh_chrt_barra_larg_barra']) && '' != $parms_tbapl_attr1['flsh_chrt_barra_larg_barra'] ? $parms_tbapl_attr1['flsh_chrt_barra_larg_barra'] : '',
        'rotateValues' => isset($parms_tbapl_attr1['flsh_chrt_barra_orien_value']) && 'Vertical' == $parms_tbapl_attr1['flsh_chrt_barra_orien_value'] ? '1' : '0',
        'placeValuesInside' => isset($parms_tbapl_attr1['flsh_chrt_barra_position_value']) && 'dentro' == $parms_tbapl_attr1['flsh_chrt_barra_position_value'] ? '1' : '0',
        'stacking' => isset($parms_tbapl_attr1['flsh_chrt_barra_empil']) && '' != $parms_tbapl_attr1['flsh_chrt_barra_empil'] && 'Off' != $parms_tbapl_attr1['flsh_chrt_barra_empil'],
        'stack100Percent' => isset($parms_tbapl_attr1['flsh_chrt_barra_empil']) && 'Percent' == $parms_tbapl_attr1['flsh_chrt_barra_empil'] ? '1' : '0',
        'seriesMode' => isset($parms_tbapl_attr1['flsh_chrt_barra_agrup']) && '' != $parms_tbapl_attr1['flsh_chrt_barra_agrup'] ? $parms_tbapl_attr1['flsh_chrt_barra_agrup'] : 'Normal',
    ];
}

function fnSum_infoGet_chart_options_funnel()
{
    global $summaryInfo, $parms_tbapl_attr1;

    $summaryInfo['chart'] ['types'] ['funnel'] = [
        'dimension' => isset($parms_tbapl_attr1['flsh_chrt_funil_dimen']) && '' != $parms_tbapl_attr1['flsh_chrt_funil_dimen'] ? $parms_tbapl_attr1['flsh_chrt_funil_dimen'] : '3d',
        'streamlinedData' => isset($parms_tbapl_attr1['flsh_chrt_funil_ignore_flow']) && 'S' == $parms_tbapl_attr1['flsh_chrt_funil_ignore_flow'] ? '0' : '1',
    ];
}

function fnSum_infoGet_chart_options_gauge()
{
    global $summaryInfo, $parms_tbapl_attr1;

    $summaryInfo['chart'] ['types'] ['gauge'] = [
        'format' => isset($parms_tbapl_attr1['flsh_chrt_gauge_forma']) && '' != $parms_tbapl_attr1['flsh_chrt_gauge_forma'] ? $parms_tbapl_attr1['flsh_chrt_gauge_forma'] : 'Circular',
    ];
}

function fnSum_infoGet_chart_options_line()
{
    global $summaryInfo, $parms_tbapl_attr1;

    $summaryInfo['chart'] ['types'] ['line'] = [
        'format' => isset($parms_tbapl_attr1['flsh_chrt_linha_forma']) && '' != $parms_tbapl_attr1['flsh_chrt_linha_forma'] ? $parms_tbapl_attr1['flsh_chrt_linha_forma'] : 'Line',
        'seriesMode' => isset($parms_tbapl_attr1['flsh_chrt_linha_agrup']) && '' != $parms_tbapl_attr1['flsh_chrt_linha_agrup'] ? $parms_tbapl_attr1['flsh_chrt_linha_agrup'] : 'Normal',
    ];
}

function fnSum_infoGet_chart_options_pie()
{
    global $summaryInfo, $parms_tbapl_attr1;

    $summaryInfo['chart'] ['types'] ['pie'] = [
        'format' => isset($parms_tbapl_attr1['flsh_chrt_pizza_forma']) && '' != $parms_tbapl_attr1['flsh_chrt_pizza_forma'] ? $parms_tbapl_attr1['flsh_chrt_pizza_forma'] : 'Pie',
        'dimension' => isset($parms_tbapl_attr1['flsh_chrt_pizza_dimen']) && '' != $parms_tbapl_attr1['flsh_chrt_pizza_dimen'] ? $parms_tbapl_attr1['flsh_chrt_pizza_dimen'] : '2d',
        'order' => isset($parms_tbapl_attr1['flsh_chrt_pizza_orden']) && '' != $parms_tbapl_attr1['flsh_chrt_pizza_orden'] ? $parms_tbapl_attr1['flsh_chrt_pizza_orden'] : 'Off',
        'showPercentValues' => isset($parms_tbapl_attr1['flsh_chrt_pizza_valor']) && 'Percent' == $parms_tbapl_attr1['flsh_chrt_pizza_valor'],
    ];
}

function fnSum_infoGet_chart_options_pyramid()
{
    global $summaryInfo, $parms_tbapl_attr1;

    $summaryInfo['chart'] ['types'] ['pyramid'] = [
        'dimension' => isset($parms_tbapl_attr1['flsh_chrt_pyramid_dimen']) && '' != $parms_tbapl_attr1['flsh_chrt_pyramid_dimen'] ? $parms_tbapl_attr1['flsh_chrt_pyramid_dimen'] : '3d',
        'showPercentValues' => isset($parms_tbapl_attr1['flsh_chrt_pyramid_valor']) && 'Percent' == $parms_tbapl_attr1['flsh_chrt_pyramid_valor'],
        'isSliced' => isset($parms_tbapl_attr1['flsh_chrt_pyramid_forma']) && 'S' == $parms_tbapl_attr1['flsh_chrt_pyramid_forma'],
    ];
}

function fnSum_infoGet_chart_options_radar()
{
}

function fnSum_infoGet_chart_setFields()
{
    global $summaryInfo, $tbapl_arr_quebras;

    foreach ($summaryInfo['group_by'] as $groupByName => $groupByInfo) {
        $summaryInfo['group_by'] [$groupByName] ['chart'] = [];

        foreach ($groupByInfo['dimension'] as $dimensionName => $dimensionInfo) {
            $summaryInfo['group_by'] [$groupByName] ['chart'] [$dimensionName] = [];

            foreach ($groupByInfo['metric'] as $metricName => $metricInfo) {
                $chartConfig =  [
                    'has_chart' => false,
                ];

                if (isset($tbapl_arr_quebras[$groupByName]) && isset($tbapl_arr_quebras[$groupByName] ['cfg_chart'] [$dimensionName]) && isset($tbapl_arr_quebras[$groupByName] ['cfg_chart'] [$dimensionName] [ $metricInfo['chart_var_name'] ])) {
                    $chartConfig['has_chart'] = 'S' == $tbapl_arr_quebras[$groupByName] ['cfg_chart'] [$dimensionName] [ $metricInfo['chart_var_name'] ] ['graf_show'];
                }

                $summaryInfo['group_by'] [$groupByName] ['chart'] [$dimensionName] [$metricName] = $chartConfig;
            }
        }
    }
}

function fnSum_infoGet_metricName($metricName, $metricFunction)
{
    $metricNamePart = 'NM_Count' == $metricName ? '__nm_count_nm__' : $metricName;

    $metricFullName = $metricNamePart . '_';

    switch ($metricFunction) {
        case 'S': // soma
            $metricFullName .= 'sum';
            break;
        case 'A': // media
            $metricFullName .= 'avg';
            break;
        case 'M': // minimo
            $metricFullName .= 'min';
            break;
        case 'X': // maximo
            $metricFullName .= 'max';
            break;
        case 'W': // media ponderada
            $metricFullName .= 'wei';
            break;
        case 'C': // contagem
            $metricFullName .= 'cnt';
            break;
        case 'D': // contagem distinta
            $metricFullName .= 'dct';
            break;
        case 'V': // variancia
            $metricFullName .= 'var';
            break;
        case 'P': // desvio padrao
            $metricFullName .= 'pad';
            break;
    }

    return $metricFullName;
} // fnSum_infoGet_metricName

function fnSum_infoGet_fieldVarName($fieldName)
{
    return strtolower(str_replace(array('.', '-'), array('_', '_'), $fieldName));
} // fnSum_infoGet_fieldVarName

function fnSum_infoGet_chartVarName($metricName, $metricFunction, $fieldName)
{
    if ('NM_Count' == $metricName) {
        return '__NM_COUNT_NM__';
    }

    $metricFullName = $fieldName . '_';

    switch ($metricFunction) {
        case 'S': // soma
            $metricFullName .= 'sum';
            break;
        case 'A': // media
            $metricFullName .= 'avg';
            break;
        case 'M': // minimo
            $metricFullName .= 'min';
            break;
        case 'X': // maximo
            $metricFullName .= 'max';
            break;
        case 'W': // media ponderada
            $metricFullName .= 'wei';
            break;
        case 'C': // contagem
            $metricFullName .= 'cnt';
            break;
        case 'D': // contagem distinta
            $metricFullName .= 'dct';
            break;
        case 'V': // variancia
            $metricFullName .= 'var';
            break;
        case 'P': // desvio padrao
            $metricFullName .= 'pad';
            break;
    }

    return str_replace(array('.', '-'), array('_', '_'), $metricFullName);
} // fnSum_infoGet_chartVarName

function fnSum_infoGet_dimension_groupByInfoQuebras($groupByInfo, $groupByData)
{
    if (isset($groupByInfo['quebras'] [ $groupByData[SC_GROUPBY_NAME_ORIGINAL] ])) {
        return $groupByInfo['quebras'] [ $groupByData[SC_GROUPBY_NAME_ORIGINAL] ];
    } else {
        return $groupByInfo['quebras'] [ $groupByData[SC_GROUPBY_NAME_LOWER] ];
    }
}

function fnSum_infoGet_dimension_groupByInfoLayout($groupByIndex, $groupByData)
{
    global $resLayoutFull;

    $groupByInfo_layout = [];
    if (isset($resLayoutFull[$groupByIndex] ['fields'] [ $groupByData[SC_GROUPBY_NAME_ORIGINAL] ])) {
        $groupByInfo_layout = $resLayoutFull[$groupByIndex] ['fields'] [ $groupByData[SC_GROUPBY_NAME_ORIGINAL] ];
    } else {
        foreach ($resLayoutFull[$groupByIndex] ['fields'] as $layoutIndex => $layoutInfo) {
            $layoutIndexLower = strtolower($layoutIndex);
            if ($layoutIndexLower == $groupByData[SC_GROUPBY_NAME_ORIGINAL] || $layoutIndexLower == $groupByData[SC_GROUPBY_NAME_LOWER]) {
                $groupByInfo_layout = $resLayoutFull[$groupByIndex] ['fields'] [$layoutIndex];
                break;
            }
        }
    }

    return $groupByInfo_layout;
}

function fnSum_infoGet_dimension_groupByNameOld($groupByIndex, $groupByData)
{
    global $resLayoutFull;

    $groupByNameOld = '';

    if (isset($resLayoutFull[$groupByIndex] ['fields'] [ $groupByData[SC_GROUPBY_NAME_ORIGINAL] ])) {
        $groupByNameOld = $groupByData[SC_GROUPBY_NAME_ORIGINAL];
    } else {
        foreach ($resLayoutFull[$groupByIndex] ['fields'] as $layoutIndex => $layoutInfo) {
            $layoutIndexLower = strtolower($layoutIndex);
            if ($layoutIndexLower == $groupByData[SC_GROUPBY_NAME_ORIGINAL] || $layoutIndexLower == $groupByData[SC_GROUPBY_NAME_LOWER]) {
                $groupByNameOld = $layoutIndex;
                break;
            }
        }
    }

    return $groupByNameOld;
}

function fnSum_infoGet_metric_totFieldRes($groupByIndex, $metricFullName)
{
    global $tbapl_cmp_tot_res;

    if (isset($tbapl_cmp_tot_res[$groupByIndex])) {
        foreach ($tbapl_cmp_tot_res[$groupByIndex] as $metricName => $metricInfo) {
            if (strtolower($metricName) == $metricFullName) {
                return $metricInfo;
            }
        }

        foreach ($tbapl_cmp_tot_res[$groupByIndex] as $metricName => $metricInfo) {
            if (strtolower(str_replace('.', '_', $metricName)) == $metricFullName) {
                return $metricInfo;
            }
        }
    }

    return [];
}

function fnSum_infoGet_restrictVersionFeatures()
{
    global $nm_config, $summaryInfo;

    if (!$nm_config['flag_versao'] ['summary_new'] ['has']) {
        $summaryInfo['options'] ['display_inline_chart'] = false;
        $summaryInfo['options'] ['display_summary_every_page'] = false;
        $summaryInfo['options'] ['display_summary_total'] = 'all_pages';
        $summaryInfo['options'] ['display_total_top'] = false;
        $summaryInfo['options'] ['use_pagination'] = false;
        $summaryInfo['options'] ['show_percentuals'] = false;

        foreach ($summaryInfo['group_by'] as $groupByName => $groupByInfo) {
            foreach ($groupByInfo['metric'] as $metricName => $metricInfo) {
                $summaryInfo['group_by'] [$groupByName] ['metric'] [$metricName] ['show_percentuals'] = false;
            }
            foreach ($groupByInfo['dimension'] as $dimensionName => $dimensionInfo) {
                $summaryInfo['group_by'] [$groupByName] ['dimension'] [$dimensionName] ['limit_chart_items'] = '0';
            }
        }
    }
}

function fnSum_infoGet_pregString(&$string)
{
    global $tbapl_idioma, $apl_charset;

    sc_preg_match_local($string, $matches, $tbapl_idioma, $apl_charset);
    if (!empty($matches[0])) {
        $matches = $matches[0];
        foreach ($matches as $eachMatch) {
            $varName = substr($eachMatch, 1, strlen($eachMatch) - 2);
            if (substr($varName, 0, 5) == "lang_") {
                $replaceString = "{\$this->Ini->Nm_lang['{$varName}']}";
                $string = str_replace($eachMatch, $replaceString, $string);
            }
        }
    }

    sc_preg_match_global($string, $matches, $tbapl_idioma, $apl_charset);
    if (!empty($matches[0])) {
        $matches = $matches[0];
        foreach ($matches as $eachMatch) {
            $replaceString = "{\$_SESSION['" . substr($eachMatch, 1, strlen($eachMatch) - 2) . "']}";
            $string = str_replace($eachMatch, $replaceString, $string);
        }
    }
}