<?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");
putenv("erpToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IndlYkFwaTgiLCJwYXNzd29yZCI6ImV5OHlydzRyIn0.UyShdlXVpL0u7zV-QJKYqg67JRO0IrJSgaO67rvi0hY");
$hosturl = get_base_url() . '/erp';
$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"]);
################################################################################
$oldVersionFlag = checkForOldVersion();
$smarty->assign("oldVersionFlag", $oldVersionFlag);

$httpStatusCodes = [
    // 1xx: Informational
    100 => 'Continue',
    101 => 'Switching Protocols',
    102 => 'Processing',
    103 => 'Early Hints',
    // 2xx: Success
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',
    207 => 'Multi-Status',
    208 => 'Already Reported',
    226 => 'IM Used',
    // 3xx: Redirection
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    307 => 'Temporary Redirect',
    308 => 'Permanent Redirect',
    // 4xx: Client Error
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Timeout',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Payload Too Large',
    414 => 'URI Too Long',
    415 => 'Unsupported Media Type',
    416 => 'Range Not Satisfiable',
    417 => 'Expectation Failed',
    418 => "I'm a teapot",
    421 => 'Misdirected Request',
    422 => 'Unprocessable Entity',
    423 => 'Locked',
    424 => 'Failed Dependency',
    425 => 'Too Early',
    426 => 'Upgrade Required',
    428 => 'Precondition Required',
    429 => 'Too Many Requests',
    431 => 'Request Header Fields Too Large',
    451 => 'Unavailable For Legal Reasons',
    // 5xx: Server Error
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Timeout',
    505 => 'HTTP Version Not Supported',
    506 => 'Variant Also Negotiates',
    507 => 'Insufficient Storage',
    508 => 'Loop Detected',
    510 => 'Not Extended',
    511 => 'Network Authentication Required'
];

//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 != '') {
        if ($post['useERPIDs'] == 1) {
            $authorization = "Open-Key: $token";
            curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization)); // Inject the token into the
        } else {
            $authorization = "Authorization: Bearer $token";
            $tokenHeader = "token: Bearer $token";
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', $authorization, $tokenHeader)); // 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 checkForOldVersion() {
    $dbBackups = glob('../../_tempArchives/' . $_SESSION['dbname'] . '*');
    $filesBackups = glob('../../_tempArchives/' . basename(dirname(getcwd())) . '*');
    return count($dbBackups) + count($filesBackups);
}

?>