<?php

/* ============================================
  HERE THE PUBLIC CONFIG THE RELATE THE SMARTY
  WITH CONTROLLER AND VIEWS.
  ============================================ */
set_time_limit(100); // set time limit for script in seconds & ignores maximum execution time in php.ini

error_reporting(E_ERROR); //E_ALL
ini_set('display_errors', 1);
ini_set('memory_limit', '-1');
//the path of the folder that contains all files
//for templates
//to check if it from the folder or from .htaccess
putenv("africanoToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJidXMiLCJhdWQiOiJidXMiLCJqdGkiOiJZeGNPZHBIdFQ5IiwiaWF0IjoxNzAyOTc1NDczLjA3MjE0Mn0.olDyb_cwaiJXNomnJjxD2Xvg25sps484cs5nPZmLDw8");
putenv("africanoUrl=https://africano.gt4it.com/api");
$hosturl = get_base_url() . '/edrp';
$hosturl_f = get_base_url() . explode('/controllers', $_SERVER['REQUEST_URI'])[0];
define("Host_URL", $hosturl);

function get_base_url() {
    if (isset($_SERVER['HTTPS'])) {
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    } else {
        $protocol = 'http';
    }
    return $protocol . "://" . $_SERVER['HTTP_HOST'];
}

$showoutside = 0;
if ($showoutside == 1) {
    $path = "views/default";
} else {
    $path = "../views/default";
}
//$_SERVER['DOCUMENT_ROOT']
/* * *** just used rd beans depend on connection ** */
require_once('../models/sql/ConnectionProperty.class.php');
require_once('../library/db_main/rb.php');
$dbhostrb = ConnectionProperty::getHost();
$dbuserrb = ConnectionProperty::getUser();
$dbpasswordrb = ConnectionProperty::getPassword();
$dbnamerb = ConnectionProperty::getDatabase();

R::setup('mysql:host=' . $dbhostrb . ';dbname=' . $dbnamerb . '', '' . $dbuserrb . '', '' . $dbpasswordrb . '');
R::exec('SET NAMES latin1');

/* * ***** end of red beans *** */
//use smarty template , it will found in public folder
require_once('libs/Smarty.class.php');

//use smarty paginate to paging the records from db
require_once('libs/SmartyPaginate.class.php');

//use trucate method to munipliate the restore data
require_once('libs/modifier.mb_truncate.php');

//use smarty as instance
$smarty = new Smarty();
//$smarty->template_dir = '../views/v1';
$smarty->template_dir = '../views/default';
$smarty->compile_dir = '../temp';

//send variable path to views
$smarty->assign("path", $path);
$smarty->assign("hosturl", $hosturl);

## theme setting,timezone,copyRightsStatment
$p = R::getRow("select colortype,timezone,copyRightsStatment FROM programsettings WHERE programsettingsid=1 limit 1");
//# load theme setting
$smarty->assign("colortype", (int) $p['colortype']);
//set time zone.It is important for ajax file because time zone is set in authintication which is not used in ajax files which makes it use time zone of php.ini
date_default_timezone_set($p["timezone"]);
$smarty->assign("copyRightsStatment", $p["copyRightsStatment"]);
################################################################################

//echo date_default_timezone_get();
//$urlType 0 internal "inside erp" , 1 external
//$encodeData is to encode $data_arr or to use it directly in $post
function CURL_Request($data_arr, $url, $urlType = 0, $jsonEncodeDataArr = 0, $token = '', $method = 'GET') {
    ##preparing session data
    $sessionlist = array();
    if ($urlType != 1) {
        //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
        $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

        ##appending necessary data
        $sessionVar = $_SESSION;
        $sessionVar['SmartyPaginate'] = '';
        $sessionlist = ($sessionVar);
    }

    //set post fields
    if ($jsonEncodeDataArr == 0) {
        $post = [
            'data_arr' => json_encode($data_arr), //encode it as it is array
            'curlpost' => 1,
            'sessionlist' => json_encode($sessionlist), //encode it as it is array
        ];
    } else {
        $post = $data_arr;
        $post['curlpost'] = 1;
        $post['sessionlist'] = json_encode($sessionlist); //encode it as it is array
    }



    //$post = $data_arr;
    $ch = curl_init($url);
    if ($token != '') {
        $authorization = "Authorization: Bearer $token";
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', $authorization)); // Inject the token into the
    }
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}

function searchForId($id, $array, $string = 'id') {
    foreach ($array as $key => $val) {
        if ($val[$string] === $id) {
            return $key;
        }
    }
    return null;
}

function searchForIds($id, $array, $string = 'id') {
    $keys = [];
    foreach ($array as $key => $val) {
        if ($val[$string] === $id) {
            $keys[] = $key;
        }
    }
    return $keys;
}

function customArrayIndexOne($array, $colName = 'id') {
    $newArr = array();
    foreach ($array as $val) {
        $newArr[$val[$colName]] = $val;
    }
    return $newArr;
}

function customArrayIndexMany($array, $colName = 'id') {
    $newArr = array();
    foreach ($array as $val) {
        if (!isset($newArr[$val[$colName]])) {
            $newArr[$val[$colName]] = array();
        }
        $newArr[$val[$colName]][] = $val;
    }
    return $newArr;
}

function customArrayManyIndexOne($array, $colName = array()) {
    $newArr = array();
    if (count($colName) > 0) {
        foreach ($array as $val) {
            $builtUpIndex = '';
            foreach ($colName as $col) {
                $builtUpIndex .= ',' . $val[$col];
            }
            $builtUpIndex = trim($builtUpIndex, ',');
            $newArr[$builtUpIndex] = $val;
        }
    }
    return $newArr;
}

function customArrayManyIndexMany($array, $colName = array()) {
    $newArr = array();
    if (count($colName) > 0) {
        foreach ($array as $val) {
            $builtUpIndex = '';
            foreach ($colName as $col) {
                $builtUpIndex .= ',' . $val[$col];
            }
            $builtUpIndex = trim($builtUpIndex, ',');
            $newArr[$builtUpIndex][] = $val;
        }
    }
    return $newArr;
}

function isJson($string) {
    json_decode($string);
    return json_last_error() === JSON_ERROR_NONE;
}

function json_validate($string) {
    // decode the JSON data
    $result = json_decode($string);

    // switch and check possible JSON errors
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            $error = ''; // JSON is valid // No error has occurred
            break;
        case JSON_ERROR_DEPTH:
            $error = 'The maximum stack depth has been exceeded.';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            $error = 'Invalid or malformed JSON.';
            break;
        case JSON_ERROR_CTRL_CHAR:
            $error = 'Control character error, possibly incorrectly encoded.';
            break;
        case JSON_ERROR_SYNTAX:
            $error = 'Syntax error, malformed JSON.';
            break;
        // PHP >= 5.3.3
        case JSON_ERROR_UTF8:
            $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
            break;
        // PHP >= 5.5.0
        case JSON_ERROR_RECURSION:
            $error = 'One or more recursive references in the value to be encoded.';
            break;
        // PHP >= 5.5.0
        case JSON_ERROR_INF_OR_NAN:
            $error = 'One or more NAN or INF values in the value to be encoded.';
            break;
        case JSON_ERROR_UNSUPPORTED_TYPE:
            $error = 'A value of a type that cannot be encoded was given.';
            break;
        default:
            $error = 'Unknown JSON error occured.';
            break;
    }

    if ($error !== '') {
        // throw the Exception or exit // or whatever :)
    }
}

?>