<?php
if(!isset($_SESSION)) 
{ 
	session_start(); 
} 

if(!empty($_SESSION['acn_sst_userlogz']) && !empty($_SESSION['acn_sst_typelogz']) && !empty($_SESSION['acn_sst_logz']) && !empty($_SESSION['acn_sst_vndlogz']))
{
	$_SESSION['acn_sst_userlogz'] = $_SESSION['acn_sst_userlogz'];
	$_SESSION['acn_sst_typelogz'] = $_SESSION['acn_sst_typelogz'];
	$_SESSION['acn_sst_logz'] = $_SESSION['acn_sst_logz'];
	$_SESSION['acn_sst_vndlogz'] = $_SESSION['acn_sst_vndlogz'];
	
	$agnc_logz = $_SESSION['acn_sst_vndlogz'];$type_session = $_SESSION['acn_sst_typelogz'];
	
	$def_logz = $_SESSION['acn_sst_logz']; //generated logs
	$log_session = $_SESSION['acn_sst_userlogz']; //user account record
}
else
{
	$log_session = $type_session = $agnc_logz = $def_logz = "";
}


if(!empty($_SESSION['account_session'])){ 	$_SESSION['unknown_cart'] = $_SESSION['account_session'];	$set_sess = $_SESSION['account_session']; }
elseif(empty($_SESSION['account_session'])){
	if(empty($_SESSION['unknown_cart'])) {
	$reg = gntRdmStgs().substr(md5(uniqid(rand())), 0, 10);	$_SESSION['unknown_cart'] = $reg; $set_sess = $_SESSION['unknown_cart'];
	} $set_sess = $_SESSION['unknown_cart'];
}

	
$dbserverName = "localhost";
$dbUserName = "root";
$dbPassword = "";
$dbName = "kmart";

try{
	
	$db_con = new PDO("mysql:host={$dbserverName};dbname={$dbName}",$dbUserName,$dbPassword);
	$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
	echo $e->getMessage();
}


$link = mysqli_connect($dbserverName, $dbUserName, $dbPassword, $dbName);

/*******************************************SET TIME ZONE&****************************/
date_default_timezone_set('UTC');
	
/*******************************************SET TIME ZONE&****************************/


function data_cleand($str)
{
	return str_replace(' ','_',$str);
}

function clean_data($str)
{
	return str_replace('_',' ',$str);
}

function php_url_slug($string) 
{
	$comz = htmlentities($string);
	$chg = preg_replace("/[^a-zA-Z0-9_]/", "_", $comz);
	$slug = str_replace("__", "_", $chg);
	
	return strtolower($slug); 
}

function php_slug_url($string) 
{
	$comz = htmlentities($string);
	$chg = preg_replace("/[^a-zA-Z0-9_]/", "_", $comz);
	$slug = str_replace("__", "_", $chg).'_'.rand();
	$p_url = strtolower($slug);
	
	return $p_url; 
}

function data_clean($str)
{
	return str_replace(',','',$str);
}

function data_under($str)
{
	return str_replace(' ','_',$str);
}

function generateRandomString($length = 10) {
	$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$charactersLength = strlen($characters);
	$randomString = '';
	for ($i = 0; $i < $length; $i++) {
		$randomString .= $characters[rand(0, $charactersLength - 1)];
	}
	return $randomString;
}


//strtoupper( substr( md5(uniqid(rand())), 0, 10 ) ) 

function gntRdmSdk($length = 5) {
	$alp =  substr(str_shuffle(str_repeat($x='ABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil(2/strlen($x)) )),1,2);
	
	return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length).$alp ;
}

function gntRdmorderNum($length = 9) {
	return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length) ;
}

function gntRdmStgs($length = 13) {
	return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

	//CHECK INPUTS
function test_input($data) 
{
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

//CHECK AMOUNT INPUTS
function only_num($nums){
	$chg = preg_replace("/[^0-9. ]/", "", $nums);
	return $chg;
}

function change_currency($main_text)
{
	$amt = preg_replace("/[^0-9.]/", "", $main_text);
	return floatval($amt);
}

//INPUT PAGE LOGS 
function pages($pgid,$pgremark)
{
	global $db_con;
	
	$ins = $db_con->prepare("INSERT INTO pages_log(user_id, remark) VALUES(:pgid, :pgremark) ");
	$ins->bindParam(':pgid',$pgid);
	$ins->bindParam(':pgremark',$pgremark);
	$ins->execute();
}

/*********************CHECK IF SESSION IS ACTIVE*************************/
//get USER TYPE NAME
function gt_typ_nm($typ)
{
	$gt_typs = getOne('user_type'," id = '$typ' ",'role');	
	return $gt_typs;
}



function only_login($sess)
{	
	global $type_session;
	if(!empty($sess))
	{
		$urlnk = "account/";
		echo "<script>window.location.href ='$urlnk'</script>";
	}
}

function not_login($sess)
{	
	global $db_con,$def_logz;

	if(empty($sess))
	{
		echo "<script>window.location.href ='../login'</script>";
	}

	
	/*$splg = $db_con->prepare("SELECT sess_token FROM puc_log_session_chk WHERE user_id = :email AND status = 1 ");
	$splg->execute(array(":email"=>$sess));
	$count_logz = $splg->rowCount();
	if($count_logz > 0)
	{
		$lz = $splg->fetch();
		
		
		if($lz['sess_token'] != $def_logz)
		{
			echo "<script>window.location.href ='logout'</script>";
		}
		
		
	}*/
}

//ONLY SPECIFIC USER TYPE
function only_sects($logsess)
{	
	global $type_session;

		if($logsess == "Client")
		{
			if($type_session != "Client_sstyp" && $type_session != "Speaker_sstyp")
			{
				$urlnk = "logout";
				echo "<script>window.location.href ='$urlnk'</script>";
			}
		}
		elseif(!($logsess."_sstyp" == $type_session))
		{
			$urlnk = ($type_session == "Admin_sstyp" || $type_session == "Vendor_sstyp") ? "../account/" : "../account/";
			echo "<script>window.location.href ='$urlnk'</script>";
		}
}

//FETCH ALL DATA
function getALL($selectdb,$selectwhere,$selectorder)
{
	global $db_con;
	
	$sp = "SELECT * FROM ".$selectdb;
	
	if(!empty($selectwhere))
	{
		$sp .= " WHERE ".$selectwhere;
	}
	
	if(!empty($selectorder))
	{
		$sp .= " ORDER BY ".$selectorder;
	}
	
	$statement = $db_con->prepare($sp);
	$statement->execute();
	$result = $statement->fetchAll();
	
	return $result;
}

function gtALL($selectdb,$selectwhere,$selectorder)
{
	global $db_con;
	
	$sp = "SELECT * FROM ".$selectdb." WHERE delete_status = 0 ";
	
	if(!empty($selectwhere))
	{
		$sp .= " AND ".$selectwhere;
	}
	
	if(!empty($selectorder))
	{
		$sp .= " ORDER BY ".$selectorder;
	}
	
	$statement = $db_con->prepare($sp);
	$statement->execute();
	$result = $statement->fetchAll();
	
	return $result;
}

//FETCH SINGLE DATA
function getOne($selectdb,$selectwhere,$selectinfo)
{
	global $db_con;
	
	$sp = "SELECT * FROM ".$selectdb;
	
	if(!empty($selectwhere))
	{
		$sp .= " WHERE ".$selectwhere;
	}
	
	
	$statement = $db_con->prepare($sp);
	$statement->execute();
	$result = $statement->fetch();
	
	if(!empty($result[$selectinfo]))
	{
		return $result[$selectinfo];
	}
	else{
		return ;
	}
}

function gtOne($selectdb,$selectwhere,$selectinfo)
{
	global $db_con;
	
	$sp = "SELECT * FROM ".$selectdb." WHERE delete_status = 0 ";
	
	if(!empty($selectwhere))
	{
		$sp .= " AND ".$selectwhere;
	}
	
	
	$statement = $db_con->prepare($sp);
	$statement->execute();
	$result = $statement->fetch();
	
	if(!empty($result[$selectinfo]))
	{
		return $result[$selectinfo];
	}
	else{
		return ;
	}
}

function phone_nums($in_num)
{
	$dc1 = substr($in_num,0,3);
	$dc2 = substr($in_num, -7,-4);
	$dc3 = substr($in_num, -4);
	
	return $dc1." ". $dc2." ".$dc3;
}


function gtfullname($userid,$typ)
{
	global $db_con;
	
	$chk = getOne('tks_users'," tus_id = '$userid' ","delete_status");
	if($chk != 1 && $chk == 0 && empty($chk) && !empty($userid))
	{
		if($typ == 1)
		{
			$f_name = ucwords(getOne('tks_users'," tus_id = '$userid' ","firstname"));
		}
		elseif($typ == 2)
		{
			$f_name = ucwords(getOne('tks_users'," tus_id = '$userid' ","lastname"));
		}
		else
		{
			$f_name = ucwords(getOne('tks_users'," tus_id = '$userid' ","lastname")." ".getOne('tks_users'," tus_id = '$userid' ","firstname"));
		}
		
	}
	else
	{
		$f_name = 'N/A';
	}
	
	return $f_name;
}
/**************************************************************************/
function gtCount($selectdb,$selectwhere)
{
	global $db_con;
	
	
	$sp = "SELECT count(id) FROM ".$selectdb."  ";
	
	if(!empty($selectwhere))
	{
		$sp .= "WHERE  ".$selectwhere;
	}
	
	
	$statement = $db_con->prepare($sp);
	$count = 0;
	
	if(!empty($statement)) 
	{ 

	$statement->execute(); 	
	
	$count = $statement->fetchColumn(); 
	}
	
	return $count;
}


function cart_stk($act)
{
	global $set_sess,$db_con;
	
	$result = $db_con->query("SELECT pqrcode, prd_attr, qty FROM my_cart WHERE session_rec = '$set_sess' GROUP BY pqrcode ");
	$result->execute();

	if($act == "tot_crt") //IF THE FUNCTION IS TO GET TOTAL CART ITEM TOTAL
	{
		$cartCount = $result->rowCount();
		$all_cart = ($cartCount > 9) ? '9+' : $cartCount;
		return $all_cart;
	}
	elseif($act =="cart_amt") // TO CHECK FOR PRODUCT PRICES TOTAL
	{
		$results = $result->fetchAll();
		$tt = 0;
		foreach($results as $rs)
		{
			$prd_id = $rs['pqrcode']; //GET PRODUCT ID
			
			$prd_result = $db_con->query("SELECT psell, pdiscount,ksp_id FROM kmartstockprds WHERE pqrcode = '$prd_id' ");
			$prd_result->execute();
			$rt = $prd_result->fetch();
				
			//DISCOUNT Check
			if(!empty($rt)){
				//$dis_actual = $rt['psell'] - $rt['pdiscount'];
				//$dis_price = (!empty($rt['pdiscount']) && $rt['pdiscount'] > 0) ? $dis_actual : $rt['psell'];
				
				$chk_sl = $rt['psell'];    $chk_ds = $rt['pdiscount'];
				if($rs['prd_attr'] == 'promo'){
				//FROM GENERAL FEATURED SPECIAL PROMO
				$chk_ftp = $db_con->prepare("SELECT * FROM kmt_ft_prds WHERE ksp_id = '$rt[ksp_id]' ");
				$chk_ftp->execute(); $fpd = $chk_ftp->fetch();
				
				$chk_sl = (!empty($fpd) && !empty($fpd['km_sell'])) ? $fpd['km_sell'] : $rt['psell'];
				$chk_ds = (!empty($fpd) && !empty($fpd['km_discount'])) ? $fpd['km_discount'] : $rt['pdiscount'];
				}
		
				$shw_ds = calcprcs($chk_sl,$chk_ds,'ssl');
				$shw_dsc = calcprcs($chk_sl,$chk_ds,'sds');
				
				$ds_cur = ($shw_ds * $rs["qty"]);
				$tt += $ds_cur;
			}
		}
		return $tt;
	}
}


function calcprcs($prosld,$prodcd,$prowat){
	
	
	$sl_pc = $prosld;   $ds_pc = $prodcd;
	
	$calc_sld = (!empty($ds_pc) && $ds_pc > 0) ?  ($sl_pc - $ds_pc) : $sl_pc ;
	$calc_dsc = (!empty($ds_pc) && $ds_pc > 0) ?  '<del><span class="price-amount"><span class="currencySymbol">GH₵</span>'.$sl_pc.'</span></del>' : '' ;
	
	//CHECK IF GENERAL DISCOUNT
	$gnz_dst = getOne('pgs_settings'," st_rec = 'gndiscount' ",'st_value');
	$ckgnds = ($gnz_dst > 0) ? $gnz_dst : 0;
	$shwptg = number_format((float)((($ds_pc / $sl_pc)*100)),0); //GET DISCOUNT %
	$nwshwptg = number_format((float)($sl_pc-($sl_pc*($ckgnds/100))),0); // GET DISCOUNT VALUE
	
	$shw_pec = (!empty($ckgnds)) ? 0 : $shwptg;
	$shw_ds = (!empty($ckgnds)) ? $nwshwptg : $calc_sld;
	$shw_dsc = (!empty($ckgnds)) ? '<del><span class="price-amount"><span class="currencySymbol">GH₵ </span>'.$sl_pc.'</span></del>' : $calc_dsc;
	
	if($prowat == "spc"){
		return $shw_pec;
	}
	elseif($prowat == "ssl"){
		return $shw_ds;
	}
	elseif($prowat == "sds"){
		return $shw_dsc;
	}
}


/*function mklogsess($frusd,$sskn){
    global $set_sess,$db_con;
    
	$splg = $db_con->prepare("SELECT plck_id FROM puc_log_session_chk WHERE user_id = :email AND status = 1 ");
	$splg->execute(array(":email"=>$frusd));
	$count_logz = $splg->rowCount();
	if($count_logz > 0){
		$lz = $splg->fetch();
		$up_lgz = $db_con->prepare("UPDATE puc_log_session_chk SET status = 0 WHERE user_id = :usrd");
		$up_lgz->bindParam(':usrd',$frusd); $up_lgz->execute();
	}
	
	$ins_lgz = $db_con->prepare("INSERT INTO puc_log_session_chk(user_id, sess_token, status) VALUES(:usrd, :sstkn, 1)");
	$ins_lgz->bindParam(':usrd',$frusd); $ins_lgz->bindParam(':sstkn',$ses_tkn); $ins_lgz->execute();
}*/


function chksess($nwusrd,$cdgen){
    global $set_sess,$db_con;
    
    $splg = $db_con->prepare("SELECT plck_id FROM puc_log_session_chk WHERE user_id = :email AND status = 1 ");
	$splg->execute(array(":email"=>$nwusrd));
	$count_logz = $splg->rowCount();
	if($count_logz > 0){
		$lz = $splg->fetch();
		$up_lgz = $db_con->prepare("UPDATE puc_log_session_chk SET status = 0 WHERE user_id = :usrd"); $up_lgz->bindParam(':usrd',$nwusrd); $up_lgz->execute();
	}
	$ins_lgz = $db_con->prepare("INSERT INTO puc_log_session_chk(user_id, sess_token, status) VALUES(:usrd, :sstkn, 1)");
	$ins_lgz->bindParam(':usrd',$nwusrd); $ins_lgz->bindParam(':sstkn',$cdgen); $ins_lgz->execute();
}


/**************************************PASSWORD ************************************/

class PasswordHash {
	var $itoa64;
	var $iteration_count_log2;
	var $portable_hashes;
	var $random_state;

	function __construct($iteration_count_log2, $portable_hashes)
	{
		$this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

		if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
			$iteration_count_log2 = 8;
		$this->iteration_count_log2 = $iteration_count_log2;

		$this->portable_hashes = $portable_hashes;

		$this->random_state = microtime();
		if (function_exists('getmypid'))
			$this->random_state .= getmypid();
	}

	function PasswordHash($iteration_count_log2, $portable_hashes)
	{
		self::__construct($iteration_count_log2, $portable_hashes);
	}

	function get_random_bytes($count)
	{
		$output = '';
		if (@is_readable('/dev/urandom') &&
		    ($fh = @fopen('/dev/urandom', 'rb'))) {
			$output = fread($fh, $count);
			fclose($fh);
		}

		if (strlen($output) < $count) {
			$output = '';
			for ($i = 0; $i < $count; $i += 16) {
				$this->random_state =
				    md5(microtime() . $this->random_state);
				$output .= md5($this->random_state, TRUE);
			}
			$output = substr($output, 0, $count);
		}

		return $output;
	}

	function encode64($input, $count)
	{
		$output = '';
		$i = 0;
		do {
			$value = ord($input[$i++]);
			$output .= $this->itoa64[$value & 0x3f];
			if ($i < $count)
				$value |= ord($input[$i]) << 8;
			$output .= $this->itoa64[($value >> 6) & 0x3f];
			if ($i++ >= $count)
				break;
			if ($i < $count)
				$value |= ord($input[$i]) << 16;
			$output .= $this->itoa64[($value >> 12) & 0x3f];
			if ($i++ >= $count)
				break;
			$output .= $this->itoa64[($value >> 18) & 0x3f];
		} while ($i < $count);

		return $output;
	}

	function gensalt_private($input)
	{
		$output = '$P$';
		$output .= $this->itoa64[min($this->iteration_count_log2 + 5,
		    30)];
		$output .= $this->encode64($input, 6);

		return $output;
	}

	function crypt_private($password, $setting)
	{
		$output = '*0';
		if (substr($setting, 0, 2) === $output)
			$output = '*1';

		$id = substr($setting, 0, 3);
		# We use "$P$", phpBB3 uses "$H$" for the same thing
		if ($id !== '$P$' && $id !== '$H$')
			return $output;

		$count_log2 = strpos($this->itoa64, $setting[3]);
		if ($count_log2 < 7 || $count_log2 > 30)
			return $output;

		$count = 1 << $count_log2;

		$salt = substr($setting, 4, 8);
		if (strlen($salt) !== 8)
			return $output;

		# We were kind of forced to use MD5 here since it's the only
		# cryptographic primitive that was available in all versions
		# of PHP in use.  To implement our own low-level crypto in PHP
		# would have resulted in much worse performance and
		# consequently in lower iteration counts and hashes that are
		# quicker to crack (by non-PHP code).
		$hash = md5($salt . $password, TRUE);
		do {
			$hash = md5($hash . $password, TRUE);
		} while (--$count);

		$output = substr($setting, 0, 12);
		$output .= $this->encode64($hash, 16);

		return $output;
	}

	function gensalt_blowfish($input)
	{
		# This one needs to use a different order of characters and a
		# different encoding scheme from the one in encode64() above.
		# We care because the last character in our encoded string will
		# only represent 2 bits.  While two known implementations of
		# bcrypt will happily accept and correct a salt string which
		# has the 4 unused bits set to non-zero, we do not want to take
		# chances and we also do not want to waste an additional byte
		# of entropy.
		$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

		$output = '$2a$';
		$output .= chr(ord('0') + $this->iteration_count_log2 / 10);
		$output .= chr(ord('0') + $this->iteration_count_log2 % 10);
		$output .= '$';

		$i = 0;
		do {
			$c1 = ord($input[$i++]);
			$output .= $itoa64[$c1 >> 2];
			$c1 = ($c1 & 0x03) << 4;
			if ($i >= 16) {
				$output .= $itoa64[$c1];
				break;
			}

			$c2 = ord($input[$i++]);
			$c1 |= $c2 >> 4;
			$output .= $itoa64[$c1];
			$c1 = ($c2 & 0x0f) << 2;

			$c2 = ord($input[$i++]);
			$c1 |= $c2 >> 6;
			$output .= $itoa64[$c1];
			$output .= $itoa64[$c2 & 0x3f];
		} while (1);

		return $output;
	}

	function HashPassword($password)
	{
		$random = '';

		if (CRYPT_BLOWFISH === 1 && !$this->portable_hashes) {
			$random = $this->get_random_bytes(16);
			$hash =
			    crypt($password, $this->gensalt_blowfish($random));
			if (strlen($hash) === 60)
				return $hash;
		}

		if (strlen($random) < 6)
			$random = $this->get_random_bytes(6);
		$hash =
		    $this->crypt_private($password,
		    $this->gensalt_private($random));
		if (strlen($hash) === 34)
			return $hash;

		# Returning '*' on error is safe here, but would _not_ be safe
		# in a crypt(3)-like function used _both_ for generating new
		# hashes and for validating passwords against existing hashes.
		return '*';
	}

	function CheckPassword($password, $stored_hash)
	{
		$hash = $this->crypt_private($password, $stored_hash);
		if ($hash[0] === '*')
			$hash = crypt($password, $stored_hash);

		# This is not constant-time.  In order to keep the code simple,
		# for timing safety we currently rely on the salts being
		# unpredictable, which they are at least in the non-fallback
		# cases (that is, when we use /dev/urandom and bcrypt).
		return $hash === $stored_hash;
	}
}
$st_hasher = new PasswordHash(8, TRUE);
/**************************************PASSWORD ************************************/







class Request
{
    
    /**
     * Retrieves IP address set in the request header.
     *
     * Each ISPs sets them following their own logic. There is also a possibility for the user
     * to easily spoof their IP address.
     *
     * So using this for mission critical situations is not advisable.
     * If you are getting the IP address for casual logging purposes, then this is fine.
     */
    public function getIpAddress()
    {
        $ipAddress = '';
        if (! empty($_SERVER['HTTP_CLIENT_IP']) && $this->isValidIpAddress($_SERVER['HTTP_CLIENT_IP'])) {
            // check for shared ISP IP
            $ipAddress = $_SERVER['HTTP_CLIENT_IP'];
        } else if (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // check for IPs passing through proxy servers
            // check if multiple IP addresses are set and take the first one
            $ipAddressList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($ipAddressList as $ip) {
                if ($this->isValidIpAddress($ip)) {
                    $ipAddress = $ip;
                    break;
                }
            }
        } else if (! empty($_SERVER['HTTP_X_FORWARDED']) && $this->isValidIpAddress($_SERVER['HTTP_X_FORWARDED'])) {
            $ipAddress = $_SERVER['HTTP_X_FORWARDED'];
        } else if (! empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->isValidIpAddress($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
            $ipAddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
        } else if (! empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->isValidIpAddress($_SERVER['HTTP_FORWARDED_FOR'])) {
            $ipAddress = $_SERVER['HTTP_FORWARDED_FOR'];
        } else if (! empty($_SERVER['HTTP_FORWARDED']) && $this->isValidIpAddress($_SERVER['HTTP_FORWARDED'])) {
            $ipAddress = $_SERVER['HTTP_FORWARDED'];
        } else if (! empty($_SERVER['REMOTE_ADDR']) && $this->isValidIpAddress($_SERVER['REMOTE_ADDR'])) {
            $ipAddress = $_SERVER['REMOTE_ADDR'];
        }
        return $ipAddress;
    }
    
    /**
     * To validate if an IP address is both a valid and does not fall within
     * a private network range.
     *
     * @access public
     * @param string $ip
     */
    public function isValidIpAddress($ip)
    {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
            return false;
        }
        return true;
    }
    
    public function getLocation($ip)
    {
        $ch = curl_init('http://ipwhois.app/json/' . $ip);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $json = curl_exec($ch);
        curl_close($ch);
        // Decode JSON response
        $ipWhoIsResponse = json_decode($json, true);
        // Country code output, field "country_code"
        return $ipWhoIsResponse;
    }
}




function getlocamt($stp){
    $requestModel = new Request();
    $ip = $requestModel->getIpAddress();
    $isValidIpAddress = $requestModel->isValidIpAddress($ip);
    
    
    if ($isValidIpAddress == "") {
        $sttu = "crnt";
        $visitor_ip = $_SERVER['REMOTE_ADDR'];
        $visitor_country = "Ghana"; 
    } else {
        $sttu = "frgn";
        $geoLocationData = $requestModel->getLocation($ip);
        $visitor_ip = $geoLocationData['ip'];
        $visitor_country = $geoLocationData['country'];
    }
     
    if($stp == "status"){
        return $sttu;
    }elseif($stp == "country"){
        return (!empty($visitor_country)) ? $visitor_country : 'Ghana';
    }else{
        return (!empty($visitor_ip)) ? $visitor_ip : '154.160.3.187 ';
    }
    
}


function chkprcd($shw,$fgd){
    $ckcty = (!empty(getlocamt("country")) && getlocamt("country") != "Ghana") ? "exchange" : '';
    
    $rtpck = '';
    if($ckcty == "exchange"){
        $rtpck = gtOne("acc_puc_tickets"," pt_id = '".$fgd."' ","tk_usd_amount");
    }
    
    $cury = (!empty($shw) && empty($rtpck)) ? "GHS" : "$";
    
    if(empty($rtpck)){
        $rtpck = number_format(gtOne("acc_puc_tickets"," pt_id = '".$fgd."' ","tk_amount"));
    }
    return (!empty($shw)) ? $cury.$rtpck : $rtpck;
}






function plstatus($sdf,$fhj){
	$vbms = "";
$ck_vr = "";
$mkpsp = "";
$mkadmbt = "";
if(!empty($sdf)){
	$ck_vr = gtOne("policy_granted"," pl_id = '$sdf' AND policy_ref = '$fhj' ","pg_id");
	
	if(!empty($ck_vr)){
		$mkadmbt = "showbuttonforadmin";
		$fr_fl = gtOne("policy_granted"," pg_id = '$ck_vr' ","grant_recs");
		$fr_rw = gtOne("policy_granted"," pg_id = '$ck_vr' ","grant_review");
		$fr_st = gtOne("policy_granted"," pg_id = '$ck_vr' ","grant_status");
		
		$ck_vn = gtOne("policy_granted"," pg_id = '$ck_vr' ","grant_status");
		if(!empty($ck_vn) && $ck_vn == "Yes"){
			if($type_session == "Admin_sstyp" || $type_session == "Client_sstyp"){
				$ck_ad = gtOne("policy_granted"," pg_id = '$ck_vr' ","admin_status");
				if(!empty($ck_ad) && $ck_ad == "Publish"){
					if($type_session == "Admin_sstyp"){
						$clss = "alert-light-success";
						$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Granted! Policy Response Sent; Client View Published.</h4>';
					}
					else{
						$mkpsp = "makeview";
						$clss = "alert-light-success";
						$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Granted! Application Accepted. View Response.</h4>';
					}
				}
				elseif(!empty($ck_ad) && $ck_ad == "Deny"){
					if($type_session == "Admin_sstyp"){
						$clss = "alert-light-danger";
						$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Granted! Policy Response Sent; Client View Denied.</h4>';
					}
					else{
						$clss = "alert-light-danger";
						$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Failed! Can\'t Accept Your Application.</h4>';
					}
				}
				else{
					if($type_session == "Admin_sstyp"){
						$clss = "alert-light-danger";
						$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Granted! Policy Response Sent; Awaiting Approval View.</h4>';
					}
					else{
						$clss = "alert-light-info";
						$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Pending! Policy Response Under Review.</h4>';
					}
				}
			}
			elseif($type_session == "Vendor_sstyp"){
				$clss = "alert-light-success";
				$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Granted! Policy Response Sent.</h4>';
			}
			else{
				$clss = "alert-light-info";
				$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Pending! Policy Response Under Review.</h4>';
			}
		}
		else{
			if($type_session == "Admin_sstyp"){
				$clss = "alert-light-danger";
				$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Failed ! Policy Response Denied.</h4>';
			}
			elseif($type_session == "Vendor_sstyp"){
				$clss = "alert-light-danger";
				$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Failed ! Policy Response Denied.</h4>';
			}
			else{
				$clss = "alert-light-info";
				$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Pending! Policy Response Under Review.</h4>';
			}
		}
	}
	else{
		$chk_py = getOne("users_payments"," user_id = '$prd_ft[tus_id]' AND order_id = '$grec'  ORDER BY rp_id DESC","rp_id");
		if(!empty($chk_py)){
			$chk_vr = getOne("users_payments"," rp_id = '$chk_py'  ORDER BY rp_id DESC","status");
			
			if(!empty($chk_vr) && $chk_vr == "verified"){
				$clss = "alert-light-success";
				$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Success! Payment Completed.</h4>';
			}
			else{
				if($type_session == "Admin_sstyp" || $type_session == "Vendor_sstyp"){
					$clss = "alert-light-danger";
					$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Pending ! Waiting for Client to Complete Payment.</h4>';
				}
				else{
					$mkpsp = "makecontinue";
					$clss = "alert-light-warning";
					$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Pending ! Complete Payment to Proceed.</h4>';
				}
			}
		}else{
			if($type_session == "Admin_sstyp" || $type_session == "Vendor_sstyp"){
				$clss = "alert-light-danger";
				$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Pending ! Waiting for Client Payment.</h4>';
			}
			else{
				$mkpsp = "makepayment";
				$clss = "alert-light-danger";
				$vbms = '<h4 class="text-dark text-center d-block mb-0 font-weight-bold">Pending ! Proceed to Make Payment.</h4>';
			}
		}
	}	
}
}
?>



