<?php

/**
 * Smart Report Maker
 * Version 9.0.0
 * Author : Webuccino
 * All copyrights are preserved to Webuccino
 * URL : http://mysqlreports.com/
 *
 */
// handle super globals
define("DIRECTACESS", 1);
defined('BASEPATH') or define('BASEPATH', 1);
require_once "../request.php";
$_GET    = array();
$_POST   = clean_input_array($_POST);
$_ENV    = array();
$_FILES  = array();
$_COOKIE = array();
require_once 'functions.php';

if (!is_connected()) {
    echo (" Must be connected to run this script");
    exit();
}

$error = false;

// Not authorized access
if (!is_connected() || !isset($_POST["token"]) || empty($_POST["token"]) || $_POST["token"] != $_SESSION[Session_wizard_key]["request_token_wizard"]) {
    echo "Not allowed for security reasons!";
    $error = true;
    exit();
}

/*
 * #################################################################################################
 * 1) Handling style and layout
 * ################################################################################################
 */
$allStyles = array(
    "mobile",
    "blue",
    "default",
    "grey"
);
$allLayouts = array(
    "Mobile",
    "AlignLeft",
    "Horizontal",
    "Stepped",
    "Block",
    "Outline"
);

// set layout, style_name, titles, security options in session
if (isset($_POST["layout"]) && isset($_POST["style_name"])) {

    $layout = clean_input($_POST["layout"]);
    $style  = clean_input($_POST["style_name"]);

// validating submitted style and layout
    if (!in_array($layout, $allLayouts)) {
        echo "<1stT>- Layout not found";
        $error = true;
        exit();
    } else if (!in_array($style, $allStyles)) {
        echo "<1stT>- Style not found";
        $error = true;
        exit();
    } else if (($layout === "Mobile" && $style !== "mobile") || ($layout !== "Mobile" && $style === "mobile")) {
        echo "<1stT>- Style AND Layout Not Match";
        $error = true;
        exit();
    }

    if ($error === false) {
        $_SESSION[Session_report_Settings_key]["layout"]     = $layout;
        $_SESSION[Session_report_Settings_key]["style_name"] = $style;
    } else {

// loading defaults
        if (!isset($_SESSION[Session_report_Settings_key]["layout"]) || $_SESSION[Session_report_Settings_key]["layout"] === "") {
            $_SESSION[Session_report_Settings_key]["layout"] = "AlignLeft";
        }

        if (!isset($_SESSION[Session_report_Settings_key]["style_name"]) || $_SESSION[Session_report_Settings_key]["style_name"] === "") {
            $_SESSION[Session_report_Settings_key]["style_name"] = "grey";
        }

    }

} else {
    echo "<1stT>-Style or layout not set";
    $error = true;
    exit();
}

/*
 * #################################################################################################
 * 2) Security
 * ################################################################################################
 */
$access_rules = array(
    public_report,
    private_report
);

if (isset($_POST["access"]) && strtolower($_POST["access"]) === "adminonly") {

    $_SESSION[Session_report_Settings_key]["access_rule"]   = private_report;
    $_SESSION[Session_report_Settings_key]["access_groups"] = array();
} elseif (isset($_POST["access"]) && strtolower($_POST["access"]) === "adminandusers" && !isset($_POST["groups"])) {

    echo "<2stT> Please select at least one group.";
    $error = true;
    exit();
} elseif (isset($_POST["access"]) && strtolower($_POST["access"]) === "adminandusers" && isset($_POST['groups'])) {

    $_SESSION[Session_report_Settings_key]["access_rule"] = private_report;

    if ($_SESSION[Session_security_key][srm_access_role] == "admin") {
        $_SESSION[Session_report_Settings_key]["access_groups"] = explode(", ", $_POST["groups"]);

    } else {
        $_SESSION[Session_report_Settings_key]["access_groups"] = explode(", ", $_SESSION[Session_security_key][srm_access_group]);

    }

} elseif (isset($_POST["access"]) && strtolower($_POST["access"]) === "public") {

    $_SESSION[Session_report_Settings_key]["access_rule"]   = public_report;
    $_SESSION[Session_report_Settings_key]["access_groups"] = array();
} else {
    /*
     * #################################################################################################
     * 2-4) Case Other
     * ################################################################################################
     */
    echo "<2stT> The Access rule are not set correctly, please specify who can access the generated report.";
    $error = true;
    exit();
}

/*
 * #################################################################################################
 * General Settings
 * ################################################################################################
 */

// language

$lang = (isset($_POST["lang"]) && !empty($_POST["lang"])) ? $_POST["lang"] : "";

if ($lang == "" || !in_array($_POST["lang"], $languages_array)) {
    echo '<3stT>- Please select a valid language.';
    $error = true;
    exit();
} else {
    $_SESSION[Session_report_Settings_key]["language"] = $lang;
}

require_once "../../Reports9/shared/helpers/Model/safeValue.php";

if (!is_numeric($_POST['txt_records_per_page'])) {
    echo '<3stT>- Record per page must be numeric.';
    $error = true;
    exit();
}

$txt_report_title     = (isset($_POST['txt_report_title'])) ? clean_input($_POST['txt_report_title']) : "";
$txt_report_header    = (isset($_POST['txt_report_header'])) ? clean_input($_POST['txt_report_header']) : "";
$txt_report_footer    = (isset($_POST['txt_report_footer'])) ? clean_input($_POST['txt_report_footer']) : "";
$txt_records_per_page = (isset($_POST['txt_records_per_page'])) ? clean_input($_POST['txt_records_per_page']) : "";
$txt_report_name      = (isset($_POST['txt_report_name'])) ? clean_input($_POST['txt_report_name']) : "";

$selected_Category      = (isset($_POST["selected_category"]) && $_POST["selected_category"] != "") ? intval($_POST["selected_category"]) : 0;
$forbidden_report_names = array("config", "init", "request", "calculated_columns", "request", "auto_load", "shared", "email_report", "ChangeStyle", "ChangeLayout", "filter", "Mobile", "Tablet", "Mobile_Detect", ".", "..");

if (empty($txt_report_name) || $txt_report_name === "") {
    echo "<3stT>- Please enter report name";
    $error = true;
    exit();
} elseif (in_array(strtolower($txt_report_name), array_map("strtolower", $forbidden_report_names))) {
    echo "<3stT>- $txt_report_name can't be used as a report name, please use another name.";
    $error = true;
    exit();
} else

if (
    !$_SESSION[Session_wizard_key]["edit_mode"] &&
    ($srm_dashboard->is_report_existed_by_name(trim($txt_report_name)) ||
        file_exists("../../Reports9/" . str_replace(" ", "", trim($txt_report_name))))
) {
    echo "<3stT>- A report with this name already exists, please choose another name for your report";
    $error = true;
    exit();
} else

if (
    $_SESSION[Session_wizard_key]["edit_mode"] &&
    strtolower($srm_dashboard->get_existed_name($_SESSION[Session_wizard_key]["report_id"])) != strtolower($txt_report_name) &&
    (file_exists("../../Reports9/" . str_replace(" ", "", trim($txt_report_name))) ||
        $srm_dashboard->is_report_existed_by_name(trim($txt_report_name)))
) {
    echo "<3stT>- A report with this name already exists, please choose another name for your report";
    $error = true;
    exit();
} elseif (empty($selected_Category) || $selected_Category == 0) {
    echo "<3stT>-Please select a category for the report.";
    $error = true;
    exit();
} else {

    $_SESSION[Session_report_Settings_key]["date_created"]     = date("d-M-Y H:i:s");
    $_SESSION[Session_report_Settings_key]["title"]            = $txt_report_title;
    $_SESSION[Session_report_Settings_key]["header"]           = $txt_report_header;
    $_SESSION[Session_report_Settings_key]["footer"]           = $txt_report_footer;
    $_SESSION[Session_report_Settings_key]["file_name"]        = $txt_report_name;
    $_SESSION[Session_report_Settings_key]["records_per_page"] = $txt_records_per_page;
    $_SESSION[Session_report_Settings_key]["chkSearch"]        = ($_SESSION[Session_report_Settings_key]["datasource"] === 'table') ? "Yes" : "";
    $_SESSION[Session_report_Settings_key]["category_id"]      = intval($selected_Category);
}

if ($error == false) {
    ob_start();
    $_GET    = array();
    $_POST   = array();
    $_ENV    = array();
    $_FILES  = array();
    $_COOKIE = array();
    require_once "../engine/Model/Engine.abstract.php";
    require_once "../engine/Model/StandardEngine.class.php";

    $engine = new StandardEngine("../../Reports9");

    try {
        $engine->run($srm_dashboard);
        echo "success";
    } catch (Exception $ex) {
        $srm_dashboard->log($ex->getMessage() . "  Error Code:" . $ex->getCode(), __FILE__, __LINE__, $ex->getTrace(), log_error, "report_builder_engine", "", json_encode($_SESSION[Session_report_Settings_key]));
        echo "<3stT>-Error: " . $ex->getMessage();
    }

}

ob_end_flush();
exit();
