}
                }
            }
        }
    }
}
if (!empty($_REQUEST['to_pdf'])) {
    if (isset($args['reporter'])) {
        template_handle_pdf($args['reporter']);
    }
    return;
}
// if
if (!empty($_REQUEST['to_csv'])) {
    //check to see if exporting is allowed
    if (!hasExportAccess($args)) {
        //die if one of the above conditions has been met
        sugar_die($mod_strings['LBL_NO_EXPORT_ACCESS']);
    }
    template_handle_export($args['reporter']);
    return;
}
// if
// create report obj with the seed
$args['list_nav'] = '';
$args['upper_left'] = '';
// do saves, deletes, and publish
control($args);
$params = array();
if (!empty($_REQUEST['favorite'])) {
    $params[] = "<a href='index.php?module=Reports&action=index&favorite=1'>{$mod_strings['LBL_FAVORITES_TITLE']}</a>";
function reportCriteriaWithResult(&$reporter, &$args)
{
    global $current_user, $theme;
    global $current_language;
    global $mod_strings, $app_strings, $timedate;
    global $sugar_config, $sugar_version;
    global $app_list_strings;
    $sort_by = '';
    $sort_dir = '';
    $summary_sort_by = '';
    $summary_sort_dir = '';
    $report_type = '';
    $smarty = new Sugar_Smarty();
    if (isset($reporter->report_def['order_by'][0]['name']) && isset($reporter->report_def['order_by'][0]['table_key'])) {
        $sort_by = $reporter->report_def['order_by'][0]['table_key'] . ":" . $reporter->report_def['order_by'][0]['name'];
    }
    // if
    if (isset($reporter->report_def['order_by'][0]['sort_dir'])) {
        $sort_dir = $reporter->report_def['order_by'][0]['sort_dir'];
    }
    // if
    if (!empty($reporter->report_def['summary_order_by'][0]['group_function']) && $reporter->report_def['summary_order_by'][0]['group_function'] == 'count') {
        $summary_sort_by = $reporter->report_def['summary_order_by'][0]['table_key'] . ":" . 'count';
    } else {
        if (isset($reporter->report_def['summary_order_by'][0]['name'])) {
            $summary_sort_by = $reporter->report_def['summary_order_by'][0]['table_key'] . ":" . $reporter->report_def['summary_order_by'][0]['name'];
            if (!empty($reporter->report_def['summary_order_by'][0]['group_function'])) {
                $summary_sort_by .= ":" . $reporter->report_def['summary_order_by'][0]['group_function'];
            } else {
                if (!empty($reporter->report_def['summary_order_by'][0]['column__function'])) {
                    $summary_sort_by .= ":" . $reporter->report_def['summary_order_by'][0]['column_function'];
                }
            }
            // else if
        }
    }
    // else if
    if (isset($reporter->report_def['summary_order_by'][0]['sort_dir'])) {
        $summary_sort_dir = $reporter->report_def['summary_order_by'][0]['sort_dir'];
    }
    // if
    if (isset($reporter->report_def['report_type'])) {
        $report_type = $reporter->report_def['report_type'];
    }
    // if
    $issetSaveResults = false;
    $isSaveResults = false;
    if (isset($args['save_result'])) {
        $issetSaveResults = true;
        $smarty->assign('save_report_as_str', $_REQUEST['save_report_as']);
        if ($args['save_result']) {
            $isSaveResults = true;
        }
        // if
    }
    // if
    $buttonDuplicateAsOrigin = '<a onclick=\'document.EditView.to_pdf.value="";document.EditView.to_csv.value="";document.EditView.action.value="ReportsWizard";document.EditView.save_as.value="true";' . 'document.EditView.submit();\' href=\'#\'>' . $mod_strings['LBL_DUPLICATE_AS_ORIGINAL'] . '</a>';
    $buttonDuplicateAsSummation = '<a onclick=\'document.EditView.to_pdf.value="";document.EditView.to_csv.value="";document.EditView.action.value="ReportsWizard";document.EditView.save_as.value="true";' . 'document.EditView.save_as_report_type.value="summation";document.EditView.submit();\' href=\'#\'>' . $mod_strings['LBL_DUPLICATE_AS_SUMMATON'] . '</a>';
    $buttonDuplicateAsDetail = '<a onclick=\'document.EditView.to_pdf.value="";document.EditView.to_csv.value="";document.EditView.action.value="ReportsWizard";document.EditView.save_as.value="true";' . 'document.EditView.save_as_report_type.value="summation_with_details";document.EditView.submit();\' href=\'#\'>' . $mod_strings['LBL_DUPLICATE_AS_SUMMATION_DETAILS'] . '</a>';
    $buttonDuplicateAsMatrix = '<a onclick=\'document.EditView.to_pdf.value="";document.EditView.to_csv.value="";document.EditView.action.value="ReportsWizard";document.EditView.save_as.value="true";' . 'document.EditView.save_as_report_type.value="matrix";document.EditView.submit();\' href=\'#\'>' . $mod_strings['LBL_DUPLICATE_AS_MATRIX'] . '</a>';
    $buttonDuplicateAsTabular = '<a onclick=\'document.EditView.to_pdf.value="";document.EditView.to_csv.value="";document.EditView.action.value="ReportsWizard";document.EditView.save_as.value="true";' . 'document.EditView.save_as_report_type.value="tabular";document.EditView.submit();\' href=\'#\'>' . $mod_strings['LBL_DUPLICATE_AS_ROWS_AND_COLS'] . '</a>';
    if ($report_type == 'tabular') {
        $duplicateButtons = array('<input class="button" onclick="showDuplicateOverlib(this,\'tabular\');" type="button" ' . ' value="' . $app_strings['LBL_DUPLICATE_BUTTON_LABEL'] . '">', $buttonDuplicateAsOrigin, $buttonDuplicateAsSummation, $buttonDuplicateAsDetail, $buttonDuplicateAsMatrix);
    } else {
        if ($report_type == 'summary' && (!empty($reporter->report_def['display_columns']) && count($reporter->report_def['display_columns']) > 0)) {
            $canCovertToMatrix = 0;
            if (!empty($reporter->report_def['group_defs']) && count($reporter->report_def['group_defs']) <= 3) {
                $canCovertToMatrix = 1;
            }
            $duplicateButtons = array('<input type=button class="button" onclick="showDuplicateOverlib(this,\'summation_with_details\',' . $canCovertToMatrix . ');" type="button" ' . 'value="' . $app_strings['LBL_DUPLICATE_BUTTON_LABEL'] . '"/>', $buttonDuplicateAsOrigin, $buttonDuplicateAsSummation, $buttonDuplicateAsTabular);
            if ($canCovertToMatrix) {
                $duplicateButtons[] = $buttonDuplicateAsMatrix;
            }
        } else {
            if ($report_type == 'summary' && !empty($reporter->report_def['layout_options'])) {
                $duplicateButtons = array('<input class="button" onclick="showDuplicateOverlib(this,\'matrix\');" type="button" ' . ' value="' . $app_strings['LBL_DUPLICATE_BUTTON_LABEL'] . '">', $buttonDuplicateAsOrigin, $buttonDuplicateAsSummation, $buttonDuplicateAsDetail, $buttonDuplicateAsTabular);
            } else {
                if ($report_type == 'summary') {
                    $canCovertToMatrix = 0;
                    if (!empty($reporter->report_def['group_defs']) && count($reporter->report_def['group_defs']) <= 3) {
                        $canCovertToMatrix = 1;
                    }
                    $duplicateButtons = array('<input class="button" onclick="showDuplicateOverlib(this,\'summation\',' . $canCovertToMatrix . ');" type="button" ' . 'value="' . $app_strings['LBL_DUPLICATE_BUTTON_LABEL'] . '" >', $buttonDuplicateAsOrigin, $buttonDuplicateAsDetail, $buttonDuplicateAsTabular);
                    if ($canCovertToMatrix) {
                        $duplicateButtons[] = $buttonDuplicateAsMatrix;
                    }
                }
            }
        }
    }
    $smarty->assign('duplicateButtons', $duplicateButtons);
    $smarty->assign('mod_strings', $mod_strings);
    $smarty->assign('app_strings', $app_strings);
    $smarty->assign('current_language', $current_language);
    $smarty->assign('sugar_config', $sugar_config);
    $smarty->assign('sugar_version', $sugar_version);
    $smarty->assign('issetSaveResults', $issetSaveResults);
    $smarty->assign('isSaveResults', $isSaveResults);
    $smarty->assign('report_type', $report_type);
    $smarty->assign('reportDetailView', getReportDetailViewString($reporter, $args));
    $smarty->assign('reporter', $reporter);
    $smarty->assign('reporterArgs', $args);
    $form_header = get_form_header($mod_strings['LBL_TITLE'] . ": " . $args['reporter']->saved_report->name, "", false);
    $smarty->assign('form_header', $form_header);
    $smarty->assign('report_offset', $reporter->report_offset);
    $smarty->assign('sort_by', $sort_by);
    $smarty->assign('sort_dir', $sort_dir);
    $smarty->assign('summary_sort_by', $summary_sort_by);
    $smarty->assign('summary_sort_dir', $summary_sort_dir);
    if (isset($_REQUEST['save_as']) && $_REQUEST['save_as'] == 'true') {
        $report_id = '';
    } else {
        if (isset($reporter->saved_report->id)) {
            $report_id = $reporter->saved_report->id;
        } elseif (!empty($_REQUEST['record'])) {
            $report_id = $_REQUEST['record'];
        } else {
            $report_id = '';
        }
    }
    // else
    $smarty->assign('report_id', $report_id);
    $smarty->assign('to_pdf', isset($_REQUEST['to_pdf']) ? $_REQUEST['to_pdf'] : "");
    $smarty->assign('to_csv', isset($_REQUEST['to_csv']) ? $_REQUEST['to_csv'] : "");
    $isAdmin = false;
    if ($current_user->is_admin) {
        $isAdmin = true;
    }
    // if
    $smarty->assign('isAdmin', $isAdmin);
    if ($isAdmin) {
        $smarty->assign('show_query', true);
        if (!empty($_REQUEST['show_query'])) {
            $smarty->assign('show_query_checked', true);
        }
        // if
    }
    // if
    $schedule_value = $app_strings['LBL_LINK_NONE'];
    if (isset($args['reporter']->saved_report->schedule_id) && $args['reporter']->saved_report->active == 1) {
        $schedule_value = $timedate->to_display_date_time($args['reporter']->saved_report->next_run);
    }
    // if
    $smarty->assign('schedule_value', $schedule_value);
    $current_favorites = $current_user->getPreference('favorites', 'Reports');
    if (!is_array($current_favorites)) {
        $current_favorites = array();
    }
    $report_ids_array = array_keys($current_favorites, $current_user->id);
    if (!is_array($report_ids_array)) {
        $report_ids_array = array();
    }
    // if
    if (isset($args['warnningMessage'])) {
        $smarty->assign('warnningMessage', $args['warnningMessage']);
    }
    // if
    if (!empty($args['reporter']->saved_report)) {
        $context = array("bean" => $args['reporter']->saved_report);
    } else {
        $context = array();
    }
    $report_edit_access = SugarACL::checkAccess('Reports', 'edit', $context);
    $smarty->assign('report_edit_access', $report_edit_access);
    $report_delete_access = SugarACL::checkAccess('Reports', 'delete', $context);
    $smarty->assign('report_delete_access', $report_delete_access);
    $report_export_access = SugarACL::checkAccess('Reports', 'export', $context);
    $smarty->assign('report_export_access', $report_export_access);
    //check to see if exporting is allowed
    $isExportAccess = hasExportAccess($args);
    $smarty->assign('report_export_as_csv_access', $isExportAccess);
    $smarty->assign('form_submit', empty($_REQUEST['form_submit']) ? false : $_REQUEST['form_submit']);
    $global_json = getJSONobj();
    global $ACLAllowedModules;
    $ACLAllowedModules = getACLAllowedModules();
    $smarty->assign('ACLAllowedModules', $global_json->encode(array_keys($ACLAllowedModules)));
    template_reports_filters($smarty, $args);
    $smarty->assign('reporter_report_type', $args['reporter']->report_type);
    $smarty->assign('current_user_id', $current_user->id);
    $smarty->assign('md5_current_user_id', md5($current_user->id));
    if (!hasRuntimeFilter($reporter)) {
        //$showRunReportButton = false;
        $smarty->assign('filterTabStyle', "display:none");
    } else {
        $smarty->assign('filterTabStyle', "display:''");
    }
    $smarty->assign('reportResultHeader', $mod_strings['LBL_REPORT_RESULTS']);
    $reportDetailsButtonTitle = $mod_strings['LBL_REPORT_HIDE_DETAILS'];
    $reportDetailsTableStyle = '';
    if (isset($args['reportCache'])) {
        $reportCache = $args['reportCache'];
        if (!empty($reportCache->report_options_array)) {
            if (array_key_exists("showDetails", $reportCache->report_options_array) && !$reportCache->report_options_array['showDetails']) {
                $reportDetailsButtonTitle = $mod_strings['LBL_REPORT_SHOW_DETAILS'];
                $reportDetailsTableStyle = 'display:none';
            }
        }
        // if
    }
    // if
    $smarty->assign('reportDetailsButtonTitle', $reportDetailsButtonTitle);
    $smarty->assign('reportDetailsTableStyle', $reportDetailsTableStyle);
    $smarty->assign('cache_path', sugar_cached(''));
    template_reports_request_vars_js($smarty, $reporter, $args);
    //custom chart code
    require_once 'include/SugarCharts/SugarChartFactory.php';
    $sugarChart = SugarChartFactory::getInstance();
    $resources = $sugarChart->getChartResources();
    $smarty->assign('chartResources', $resources);
    $smarty->assign('id', empty($_REQUEST['id']) ? false : $_REQUEST['id']);
    //Bug#51609: Create action buttons for report view. Previously existed in _reportCriteriaWithResult.tpl
    $buttons = array();
    $buttons[] = <<<EOD
        <input name="runReportButton" id="runReportButton" type="submit" class="button" accessKey="{$mod_strings['LBL_RUN_REPORT_BUTTON_KEY']}" title="{$mod_strings['LBL_RUN_BUTTON_TITLE']}"
               onclick="this.form.to_pdf.value='';this.form.to_csv.value='';this.form.save_report.value='';" value="{$mod_strings['LBL_RUN_REPORT_BUTTON_LABEL']}">
EOD;
    $reportName = $args['reporter']->saved_report->name;
    $shareButtonCode = "parent.SUGAR.App.bwc.shareRecord('Reports', '{$report_id}', '{$reportName}');";
    $buttons[] = <<<EOD
        <input type="button" class="button" name="shareReportButton" id="shareReportButton" accessKey="{$app_strings['LBL_SHARE_BUTTON_KEY']}" value="{$app_strings['LBL_SHARE_BUTTON_LABEL']}" title="{$app_strings['LBL_SHARE_BUTTON_TITLE']}"
               onclick="{$shareButtonCode}">
EOD;
    if ($report_edit_access) {
        $buttons[] = <<<EOD
            <input type="submit" class="button" name="editReportButton" id="editReportButton" accessKey="{$app_strings['LBL_EDIT_BUTTON_KEY']}" value="{$app_strings['LBL_EDIT_BUTTON_LABEL']}" title="{$app_strings['LBL_EDIT_BUTTON_TITLE']}"
               onclick="this.form.to_pdf.value='';this.form.to_csv.value='';this.form.action.value='ReportsWizard';">
EOD;
    }
    array_push($buttons, $duplicateButtons);
    if ($report_edit_access) {
        $buttons[] = <<<EOD
        <input type="button" class="button"  name="scheduleReportButton" id="scheduleReportButton" value="{$mod_strings['LBL_REPORT_SCHEDULE_TITLE']}"
               onclick="schedulePOPUP()">
EOD;
    }
    if ($report_export_access) {
        //workaround for SP-1685, Need to clear bwcModel so change confirmation doesn't fire after making a PDF.
        $buttons[] = <<<EOD
        <input type="submit" class="button" name="printPDFButton" id="printPDFButton" accessKey="{$app_strings['LBL_VIEW_PDF_BUTTON_KEY']}" value="{$app_strings['LBL_VIEW_PDF_BUTTON_LABEL']}" title="{$app_strings['LBL_VIEW_PDF_BUTTON_TITLE']}"
               onclick="if (window&&window.parent&&window.parent.App&&window.parent.App.controller
               &&window.parent.App.controller.layout
               &&window.parent.App.controller.layout._components[0]
               &&window.parent.App.controller.layout._components[0].bwcModel
               &&window.parent.App.controller.layout._components[0].bwcModel.clear)
               {window.parent.App.controller.layout._components[0].bwcModel.clear({silent:true});this.form.save_report.value='';this.form.to_csv.value='';this.form.to_pdf.value='on'}">
EOD;
    }
    if ($isExportAccess) {
        $buttons[] = <<<EOD
        <input type="button" class="button"  name="exportReportButton" id="exportReportButton" value="{$mod_strings['LBL_EXPORT']}" onclick="do_export();">
EOD;
    }
    if ($report_delete_access) {
        $buttons[] = <<<EOD
        <input type="button" class="button"  name="deleteReportButton" id="deleteReportButton" accessKey="{$app_strings['LBL_DELETE_BUTTON_KEY']}" value="{$app_strings['LBL_DELETE_BUTTON_LABEL']}" title="{$app_strings['LBL_DELETE_BUTTON_TITLE']}"
               onclick="if (confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))){this.form.to_pdf.value='';this.form.to_csv.value='';this.form.is_delete.value='1';this.form.action.value='ReportsWizard';this.form.submit();}">
EOD;
    }
    $smarty->assign('action_button', $buttons);
    $reportType = $reporter->report_def['report_type'] == 'tabular' ? $mod_strings['LBL_ROWS_AND_COLUMNS_REPORT'] : $mod_strings['LBL_SUMMATION_REPORT'];
    if (!empty($reporter->report_def['display_columns']) && !empty($reporter->report_def['group_defs'])) {
        $reportType = $mod_strings['LBL_SUMMATION_WITH_DETAILS'];
    }
    // if
    if (isset($reporter->report_def['layout_options'])) {
        $reportType = $mod_strings['LBL_MATRIX_REPORT'];
    }
    // if
    $fullTableList = $reporter->report_def['full_table_list'];
    $fullTableListArray = array();
    foreach ($fullTableList as $key => $value) {
        if (!isset($value['name'])) {
            if (!isset($fullTableListArray[$value['module']])) {
                $module_str = $value['module'];
                if (isset($app_list_strings['moduleList'][$module_str])) {
                    $module_str = $app_list_strings['moduleList'][$module_str];
                }
                $fullTableListArray[$value['module']] = $module_str;
            }
            // if
        } else {
            if (!isset($fullTableListArray[$value['name']])) {
                $fullTableListArray[$value['name']] = $value['name'];
            }
            // if
        }
        // else
    }
    // foreach
    $displayColumnsList = $reporter->report_def['display_columns'];
    $displayColumnsArray = array();
    foreach ($displayColumnsList as $key => $value) {
        $displayColumnsArray[] = $value['label'];
    }
    // foreach
    $group_defs = $reporter->report_def['group_defs'];
    $group_defsArray = array();
    if (!empty($group_defs)) {
        foreach ($group_defs as $key => $value) {
            $group_defsArray[] = $value['label'];
        }
        // foreach
    }
    // if
    $summary_columnsList = $reporter->report_def['summary_columns'];
    $summaryColumnsArray = array();
    if (!empty($summary_columnsList)) {
        foreach ($summary_columnsList as $key => $value) {
            $summaryColumnsArray[] = $value['label'];
        }
        // foreach
    }
    // if
    $summaryAndGroupDefData = "";
    if (!empty($group_defs) && !empty($summary_columnsList)) {
        $summaryAndGroupDefData = '<tr><td wrap="true">';
        $summaryAndGroupDefData = $summaryAndGroupDefData . "<b>" . $mod_strings['LBL_GROUP_BY'] . ": </b>" . implode(", ", $group_defsArray) . "</td><td wrap=\"true\">";
        $summaryAndGroupDefData = $summaryAndGroupDefData . "<b>" . $mod_strings['LBL_SUMMARY_COLUMNS'] . ": </b>" . implode(", ", $summaryColumnsArray) . "</td></tr>";
    } else {
        if (!empty($group_defs) || !empty($summary_columnsList)) {
            $summaryAndGroupDefData = '<tr><td wrap="true">';
            if (!empty($group_defs)) {
                $summaryAndGroupDefData = $summaryAndGroupDefData . "<b>" . $mod_strings['LBL_GROUP_BY'] . ": </b>" . implode(", ", $group_defsArray) . "</td><td wrap=\"true\">&nbsp;</td>";
            }
            // if
            if (!empty($summary_columnsList)) {
                $summaryAndGroupDefData = $summaryAndGroupDefData . "<b>" . $mod_strings['LBL_SUMMARY_COLUMNS'] . ": </b>" . implode(", ", $summaryColumnsArray) . "</td><td wrap=\"true\">&nbsp;</td>";
            }
            // if
        }
    }
    // else
    $reportFilters = "";
    if (isset($reporter->report_def['filters_def']) && !isset($reporter->report_def['filters_def']['Filter_1'][0])) {
        $reportFilters = " " . $mod_strings['LBL_NONE_STRING'];
    } else {
        $reportFilters = "<span id=\"filter_results\" valign=\"bottom\">&nbsp;<img id=\"filter_results_image\" src=\"" . SugarThemeRegistry::current()->getImageURL('basic_search.gif') . "\" width=\"8px\" height=\"10px\" onclick=\"showFilterString();\"></span><span id=\"filter_results_text\" style=\"visibility:hidden;\"></span>";
    }
    // else
    $smarty->assign('reportFilters', $reportFilters);
    $smarty->assign('reportName', $reportName);
    $smarty->assign('reportType', $reportType);
    $smarty->assign('reportModuleList', implode(", ", $fullTableListArray));
    $smarty->assign('reportDisplayColumnsList', implode(", ", $displayColumnsArray));
    require_once 'modules/Teams/TeamSetManager.php';
    $smarty->assign('reportTeam', TeamSetManager::getCommaDelimitedTeams($args['reporter']->saved_report->team_set_id, $args['reporter']->saved_report->team_id, true));
    $smarty->assign('reportAssignedToName', $args['reporter']->saved_report->assigned_user_name);
    $smarty->assign('summaryAndGroupDefData', $summaryAndGroupDefData);
    // Set fiscal start date
    $admin = BeanFactory::getBean('Administration');
    $config = $admin->getConfigForModule('Forecasts', 'base');
    if (!empty($config['is_setup']) && !empty($config['timeperiod_start_date'])) {
        $smarty->assign("fiscalStartDate", $config['timeperiod_start_date']);
    }
    $smarty->assign('ENTROPY', mt_rand());
    echo $smarty->fetch("modules/Reports/templates/_reportCriteriaWithResult.tpl");
    reportResults($reporter, $args);
}