<?php

/**
 * Smart Report Maker
 * Version 9.0.0
 * Author : Webuccino
 * All copyrights are preserved to Webuccino
 * URL : http://mysqlreports.com/
 *
 */
/*
 * #################################################################################################
 * DB managment and other helper functions
 * ################################################################################################
 */

if (!defined("DIRECTACESS")) {
    exit("No direct script access allowed");
}

function set_direction()
{
    global $language;

    if ($language == "he" || $language == "ar") {
        return " dir = 'rtl' ";
    } else {
        return "";
    }

}

function get_cur_url()
{
    global $_SERVER;
    $pageURL = 'http';

    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
        $pageURL .= "s";
    } elseif (strstr(strtolower($_SERVER["SERVER_PROTOCOL"]), "https")) {
        $pageURL .= "s";
    }

    $pageURL .= "://";

    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }

    return strtok($pageURL, '?');
}

function h_aggregation_arr($arr)
{

// this function correct detect and fix statestical columns in arrays
    // for example changes $arr["some column"] to $arr[sum(the same column)] if the column is an affectd one
    global $affected_column, $function;
    $editedArray = array();

    foreach ($arr as $key => $val) {

        if ($key == $affected_column) {
            $editedArray["$function(`$key`)"] = $val;
        } else {
            $editedArray[$key] = $val;
        }

    }

    return $editedArray;
}

function get_param_type($var)
{
    // this function should be used with numeric parameters to decide wether it is an integer or double
    $int_var = (int) $var;

    if ($var == $int_var) {
        return "i";
    } else {
        return "d";
    }

}

/*
 * Sending Queries
 * *****************************************************************************************
 */

function connect()
{
    global $db_extension, $srm_dashboard, $connection_name, $used_extension, $DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME;
    $extensions = array(
        "pdo",
        "mysqli",
        "mysql"
    );

    if (isset($db_extension) && in_array(strtolower($db_extension), $extensions)) {
        $extension = $db_extension;
    } else {
        $extension = "";
    }

    if (isset($connection_name) && !empty($connection_name)) {

        if ($connection_name != default_connection_name) {
            $parameters = $srm_dashboard->get_connection_details(trim($connection_name));
        } else {
            $parameters = $srm_dashboard->get_default_connection_details();
        }

        $DB_HOST      = isset($parameters["server"]) ? $parameters["server"] : "";
        $DB_USER      = isset($parameters["user"]) ? $parameters["user"] : "";
        $DB_PASSWORD  = isset($parameters["password"]) ? $parameters["password"] : "";
        $DB_NAME      = isset($parameters["db"]) ? $parameters["db"] : "";
        $DB_CHARSET   = isset($parameters["charset"]) ? $parameters["charset"] : "";
        $DB_COLLATION = isset($parameters["collation"]) ? $parameters["collation"] : "";
        $DB_PORT      = isset($parameters["port"]) ? $parameters["port"] : "";
    }

    if (check_debug_mode() == 1) {
        $dbHandler = new DatabaseHandler($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME, true, $extension);
    } else {
        $dbHandler = new DatabaseHandler($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME, false, $extension);
    }

    if (!$dbHandler || $dbHandler->is_connection_failed()) {
        srm_dashboard::log("DB Connection error.", __FILE__ . "Line." . __LINE__, "connect", "", log_error, "report_builder_generated_report", "", "");
        die("Internal System Error");
        return false;
    }

    $used_extension = $dbHandler->get_used_extension();

    return $dbHandler;
}

function query($query, $stacktrace = "query", $params = array(), $paramsType = "")
{
    global $possible_attack, $flush, $maintainance_email, $report_key, $srm_dashboard;

// important to protect database from attacks
    if ($possible_attack == true) {
        return array();
    }

    $dbHandler = connect();
    if (!empty($params)) {
        $unique_params = array_unique($params);
    }

    if (empty($params)) {
        $params     = array();
        $paramsType = '';

    } elseif (count($unique_params) === 1 && count($params) > 1) {
        // case ordinary search params where all the params are duplicates of the same param
        $cleaned_param = clean_input($unique_params[0], false, false, false);

        $sanitized_param = $dbHandler->sanitize_values($cleaned_param);

        $elements = count($params);
        $params   = array();

        for ($i = 0; $i < $elements; $i++) {
            $params[] = $sanitized_param;
        }

    } else {

        // Cleaning
        $params = clean_array($params);

        // sql outpurt escaping against SQL injection
        $params = $dbHandler->sanitize_array($params);

    }

    if (!$dbHandler || $dbHandler->is_connection_failed()) {

        if ($flush && check_debug_mode() == 1) {
            send_log_info($maintainance_email);
        }

        srm_dashboard::log("DB Connection error.", __FILE__ . "Line." . __LINE__, "query", "", log_error, "report_builder_generated_report", "", "");
        return false;
    }

    debug("\n ## Sql query : $query  \n   ");
    $result = $dbHandler->query($query, "ASSOC", $params, $paramsType, $srm_dashboard);

    if (!is_array($result)) {

        srm_dashboard::log("Invalid query.", __FILE__ . "Line." . __LINE__, "query", "", log_error, "report_builder_generated_report", $query, json_encode($params));

        if ($flush && check_debug_mode() === 1) {
            send_log_info($maintainance_email);
        }

        return false;
    } elseif (empty($result)) {
        srm_dashboard::log("valid query yet empty report because no records matches the query.", __FILE__ . "Line." . __LINE__, "query", "", log_warning, "report_builder_generated_report", $query, json_encode($params));
    }

    $dbHandler->close_connection();
    debug("*** End of the request at: " . date('Y-m-d H:i:s'));

    if ($flush && check_debug_mode() == 1) {
        send_log_info($maintainance_email);
    }

    debug("array returned " . count($result) . "rows");

    return $result;
}

function language_exist($lang)
{
    $path = "../shared/languages/" . $lang . ".php";

    if (file_exists($path)) {
        return true;
    } else {
        return false;
    }

}

function grouping_diff_index($arr1, $arr2)
{
    $i = 0;

    foreach ($arr1 as $key => $val) {
        // Extract the 'href' attribute from the <a> element using regex
        preg_match('/href\s*=\s*[\'"]([^\'"]+)[\'"]/', $val, $matches1);
        preg_match('/href\s*=\s*[\'"]([^\'"]+)[\'"]/', $arr2[$key], $matches2);

// If both href attributes exist, compare them
        if (isset($matches1[1]) && isset($matches2[1])) {
            if ($matches1[1] !== $matches2[1]) {
                return $i; // Return the index if the image URLs differ
            }

        } else {

// If href attribute does not exist, compare the full elements
            if ($val != $arr2[$key]) {
                return $i; // Return the index if the full elements differ
            }

        }

        $i++;
    }

    return -1; // Return -1 if no differences are found
}

function array_row_count($arr)
{

    if (function_exists(array_column)) {
        return array_column($arr);
    } else {
        return count($arr[0]);
    }

}

function array_appending($arr1, $arr2)
{

    foreach ($arr2 as $key => $val) {
        $arr1[$key] = $val;
    }

    return $arr1;
}

function array_change_key_case_recursive($arr)
{
    return array_map(function ($item) {

        if (is_array($item)) {
            $item = array_change_key_case_recursive($item);
        }

        return $item;
    }, array_change_key_case($arr));
}

function map_datatype($datatype)
{
    $dataStr = array(
        'varchar',
        'char',
        'text'
    );
    $dataInt = array(
        'int',
        'decimal',
        'double',
        'smallint',
        'float',
        'year'
    );
    $dataDate = array(
        'date'
    );
    $dataDateTime = array('datetime', 'timestamp');
    $dataTime     = array('time');
    $dataBool     = array(
        'bit',
        'bool',
        'tinyint'
    );

    if (in_array($datatype, $dataInt)) {
        return "number";
    } elseif (in_array($datatype, $dataDate)) {
        return "date";
    } elseif (in_array($datatype, $dataBool)) {
        return "YesNo";
    } elseif (in_array($datatype, $dataTime)) {
        return "time";
    } elseif (in_array($datatype, $dataDateTime)) {
        return 'datetime';
    } else {
        return "text";
    }

}

function get_numeric_index($key, $arr)
{
    $index = 1;

    foreach ($arr as $f) {

        if ($f === $key) {
            return $index;
        }

        $index++;
    }

    return 0;
}

/*
 * get_field_part
 *
 * Return the appropriate fields index in a result set
 * either col or table.col depending on how the results is formated
 *
 * @param (name) the index to adjust
 * @param (row) a row in the result set
 *
 *
 * @return the adjusted index .
 */

function get_field_part($name, $row)
{
    global $table, $datasource;

    if ($datasource == "sql") {

        return $name;
    }

    if (count($table) > 1 && strstr($name, ".") && is_short_fields_result($row)) {
        $arr = explode(".", $name);

        if ($arr[1]) {
            $field = str_replace("`", "", $arr[1]);
            $field = str_replace(")", "", $field);
            return $field;
        } else {

            return $name;
        }

    } else {

        return $name;
    }

}

/*
 * is_short_fields_result
 *
 * check if the array consists of result set in the form of tab.col or just col
 *
 * @param (arr) the array to check
 *
 *
 *
 * @return true if the array consists of col and false if it consists of table.col .
 */

function is_short_fields_result($arr)
{

    foreach ($arr as $key => $val) {

        if (strstr($key, ".")) {
            //long field index tab.col in the result set
            return false;
        } else {
            //short field index col in the result set
            return true;
        }

    }

}

function print_array($array)
{
    $arr = array();

    foreach ($array as $k => $v) {

        if (is_array($array[$k])) {
            echo "$k is an array <br/>";
            print_array($array[$k]);
        } else {
            echo "****$k : $v <br/>";
        }

    }

}

function get_primary_key_column()
{
    global $primary_key;

    if (isset($primary_key) && is_array($primary_key) && count($primary_key) === 1) {
        return $primary_key[0];
    } else {
        return false;
    }

}

function get_record_primary_key_value($row)
{
    $column = get_primary_key_column();

    if ($column) {
        return $row[$column];
    } else {
        return false;
    }

}

function echo_width($_print_option)
{

    if ($_print_option == 1 || $_print_option == 2) {
        echo "width='700'";
    } else {
        echo "width ='100%' ";
    }

}
