<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------

/**
*
* Create database connection
* @access	public
* @param	string
* @return	bool	TRUE if the current version is $version or higher
*/
$Config = new CI_Config();
if($Config->installed()!='INSTALLED') header('location: install/index.php');
$server=mysqli_connect($Config->db_host(), $Config->db_username(), $Config->db_password());
$db=mysqli_select_db($server, $Config->db_name());
global $server;

function utf8_to_unicode($str) {
	$unicode = array();
	$values = array();
	$lookingFor = 1;
	for ($i = 0; $i < strlen($str); $i++) {	
		$thisValue = ord($str[$i]);		
		if ($thisValue < 128) {			
			$unicode[] = str_pad(dechex($thisValue), 4, "0", STR_PAD_LEFT);
		} else {
			if (count($values) == 0) $lookingFor = ($thisValue < 224) ? 2 : 3;
				$values[] = $thisValue;
			if (count($values) == $lookingFor) {
				$number = ($lookingFor == 3) ?
				(($values[0] % 16) * 4096) + (($values[1] % 64) * 64) + ($values[2] % 64):
				(($values[0] % 32) * 64) + ($values[1] % 64);
				$number = strtoupper(dechex($number));		
				$unicode[] = str_pad($number, 4, "0", STR_PAD_LEFT);
				$values = array();
				$lookingFor = 1;
			} 
		} 
	} 
	return ($unicode);
}


if ( ! function_exists('sendSMS')){
	function sendSMS($message_id) {
		global $LANG;
		global $server;
		mysqli_query($server, "UPDATE messagedetails SET `status` = 'processing' WHERE `id` = '$message_id'");
		$THIS_MESSAGE_ID = $message_id;
		/***
		"	For more flexibility, we defined a constant THIS_MESSAGE_ID to hold the id of this curent message
		*	singleMessageData(MESSAGE_ID,REQUIRED_FIELD_NAME) can be used to get any data for the message
		*	This will be useful when developing SMS modules or inplementing DLR
		*	You can refere to the "messagedetails" table for various fild names to use in your call
		***/
		$main_id = singleMessageData($THIS_MESSAGE_ID,'message_id');
		$gateway_id = singleMessageData($THIS_MESSAGE_ID,'gateway_id');
		$customer_id = singleMessageData($THIS_MESSAGE_ID,'customer_id');
		$reseller_id = userData($customer_id,'reseller');
		$to = singleMessageData($THIS_MESSAGE_ID,'recipient');
		$message = singleMessageData($THIS_MESSAGE_ID,'message');
		$type = singleMessageData($THIS_MESSAGE_ID,'type');
		$duration = singleMessageData($THIS_MESSAGE_ID,'duration');
		$country = singleMessageData($THIS_MESSAGE_ID,'country_id');
		$pageCount = countPage($message,$type,$duration);
		$cost = smsCost($to,$type,$country,$pageCount,$customer_id);
		
		$DoLoadGateway = 1;
		if(numberBlacklisted($to)) {
			$error = $LANG['The recipient is currently blacklisted'];	
			mysqli_query($server, "UPDATE messagedetails SET `status` = 'failed' WHERE `id` = '$message_id'");
			mysqli_query($server, "UPDATE messagedetails SET `notice` = '$error' WHERE `id` = '$message_id'");
			$DoLoadGateway = 0;
			return $error;
		}

		if($gateway_id<1) {
			$error = $LANG['No gateway defined for this message type'];	
			mysqli_query($server, "UPDATE messagedetails SET `status` = 'failed' WHERE `id` = '$message_id'");
			mysqli_query($server, "UPDATE messagedetails SET `notice` = '$error' WHERE `id` = '$message_id'");
			$DoLoadGateway = 0;
			return $error;
		}
		if($customer_id>0) {
			$balance = userWalletBalance($customer_id);
			if($cost>$balance) {
				$error = $LANG['Insufficient balance'];	
				mysqli_query($server, "UPDATE messagedetails SET `status` = 'failed' WHERE `id` = '$message_id'");
				mysqli_query($server, "UPDATE messagedetails SET `notice` = '$error' WHERE `id` = '$message_id'");
				$DoLoadGateway = 0;
				return false;
			}
			if($reseller_id>0) {
				$resellerBalance = userWalletBalance($reseller_id);
				$resellerBalanceSys = $resellerBalance/userExchangeRate($reseller_id);
				$resellerBalanceLocal = round($resellerBalanceSys*userExchangeRate($customer_id),4);
				if(round($cost,4)>$resellerBalanceLocal) {
					$error = 'Message sending denied by admin';	
					mysqli_query($server, "UPDATE messagedetails SET `status` = 'failed' WHERE `id` = '$message_id'");
					mysqli_query($server, "UPDATE messagedetails SET `notice` = '$error' WHERE `id` = '$message_id'");
					$DoLoadGateway = 0;
					return false;
				}
			}
		}
		$THIS_MESSAGE_GATEWAY = $gateway_id;
		//do cutting check
		$cutting_limit = smsGatewayData($gateway_id,'cutting_limit'); 
		$cutting_percent = smsGatewayData($gateway_id,'cutting_percent'); 
		if($cutting_limit > 0 && $cutting_percent > 0) {
		    $smsRecipts = countSMSRecipients($main_id);
		    if($smsRecipts >= $cutting_limit) {
			    $to_send = round(($cutting_percent/100)*countSMSRecipients($main_id));
    			$already_sent = countSentRecipients($main_id);
    			if($already_sent >= $to_send) {
    				$DoLoadGateway = 0;
    				mysqli_query($server, "UPDATE `messagedetails` SET `cost` = '$cost' WHERE `id` = '$message_id'");	
    				mysqli_query($server, "UPDATE messagedetails SET `status` = 'sent' WHERE `id` = '$message_id'");
    				mysqli_query($server, "UPDATE messagedetails SET `notice` = '' WHERE `id` = '$message_id'");
					return false;
    			}
		    }
		}
		//check gateway hour limits
		$hour_limit = round(smsGatewayData($gateway_id,'hour_limit')/60); 
		$jobs = smsGatewayData($gateway_id,'jobs'); 
		$nextStart = smsGatewayData($gateway_id,'nextStart'); 
		if($hour_limit > 0) {
			$minute_limit = round(smsGatewayData($gateway_id,'hour_limit')/60); 
			if($minute_limit<1)$minute_limit=1;
			if($jobs >= $minute_limit) {
				if(time() >= $nextStart) {
					$DoLoadGateway = 1;
					mysqli_query($server, "UPDATE `sms_gateways` SET `jobs` = '1' WHERE `id` = '$gateway_id'");	
					mysqli_query($server, "UPDATE `sms_gateways` SET `nextStart` = '".time()."' WHERE `id` = '$gateway_id'");	
				} else {
					$DoLoadGateway = 0;
					mysqli_query($server, "UPDATE messagedetails SET `status` = 'queued' WHERE `id` = '$message_id'");
				}
			} else {
				$DoLoadGateway = 1;
				$newjob = $jobs+1;
				mysqli_query($server, "UPDATE `sms_gateways` SET `jobs` = '$newjob' WHERE `id` = '$gateway_id'");	
			}
		}
		if($DoLoadGateway > 0) {
			//load the message gateway. Remember $THIS_MESSAGE_GATEWAY and $THIS_MESSAGE_ID will be useful in your module
			$alias = smsGatewayData($gateway_id,'alias');
			include 'smsapi/'.$alias.'/index.php';
		}
	}
	return true;
}

	function sendEmail($from,$sender,$subject,$to,$message) {
		global $LANG;
		$email_from = $sender.'<'.$from.'>';
		$email_subject = $subject;
		$to = $to;
		//Build HTML Message
		$emessage2 = '<html><body>';
		$emessage2 .= $message;
		$emessage2 .= '</body></html>';
		$body = $emessage2;
		$smtpfrom = getSetting('smtpUsername');
		
		if(!empty($smtpfrom)) {
			require_once BASEPATH.'Mailer/PHPMailerAutoload.php';
			$mail = new PHPMailer;

			//$mail->SMTPDebug = 3;                               // Enable verbose debug output			
			$mail->isSMTP();                                      // Set mailer to use SMTP
			$mail->Host =  getSetting('smtpServer');  			// Specify main and backup SMTP servers
			$mail->SMTPAuth = true;                               // Enable SMTP authentication
			$mail->Username = getSetting('smtpUsername');         // SMTP username
			$mail->Password = getSetting('smtpPassword');          // SMTP password
			$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
			$mail->Port = getSetting('smtpPort');                  // TCP port to connect to
			
			$mail->setFrom($smtpfrom, $sender);
			//set recipients
			$emailList = explode(',', $to);
			if(count($emailList) > 1) {
				foreach($emailList as $emailAdd) {
					$mail->addAddress($emailAdd);   
					$mail->isHTML(true);                                  // Set email format to HTML
					
					$mail->Subject = $subject;
					$mail->Body    = $body;
					$mail->AltBody = 'This email contain HTML that could not be displayed by your email reader. Please use a HTML email reader instead.';
					
					if(!$mail->send()) {
						$return = resendEmail($from,$sender,$subject,$emailAdd,$message);
					} else {
						$return = 'Sent';
					}				
				}
			} else {
				$mail->addAddress($to); 
				$mail->isHTML(true);                                  // Set email format to HTML
				
				$mail->Subject = $subject;
				$mail->Body    = $body;
				$mail->AltBody = 'This email contain HTML that could not be displayed by your email reader. Please use a HTML email reader instead.';
				
				if(!$mail->send()) {
					$return = resendEmail($from,$sender,$subject,$to,$message);
				} else {
					$return = 'Sent';
				}				
			} 
		} else {
		//Send Mail using PHP Mailer
			$headers = "From: " . getSetting('smtpUsername'). "\r\n";
			$headers .= 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";	
			//Send the email!
			mail($to,$email_subject,$emessage2,$headers);	
		}
	}	


	function resendEmail($from,$sender,$subject,$to,$message) {
		global $LANG;
		$email_from = $sender.'<'.$from.'>';
		$email_subject = $subject;
		$to = $to;
		//Build HTML Message
		$emessage = '<html><body>';
		$emessage .= $message;
		$emessage .= '</body></html>';
		$body = $emessage;
		$smtpfrom = getSetting('smtpUsername');
		
		if(!empty($smtpfrom)) {
			require_once BASEPATH.'Mailer/PHPMailerAutoload.php';
			$mail = new PHPMailer;

			//$mail->SMTPDebug = 3;                               // Enable verbose debug output			
			$mail->isMail() ;//$mail->isSMTP();                                      // Set mailer to use SMTP
			$mail->Host =  getSetting('smtpServer');  			// Specify main and backup SMTP servers
			$mail->SMTPAuth = true;                               // Enable SMTP authentication
			$mail->Username = getSetting('smtpUsername');         // SMTP username
			$mail->Password = getSetting('smtpPassword');          // SMTP password
			$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
			$mail->Port = getSetting('smtpPort');                  // TCP port to connect to
			
			$mail->setFrom($smtpfrom, $sender);
			//set recipients
			$emailList = explode(',', $to);
			if(count($emailList) > 1) {
				foreach($emailList as $emailAdd) {
					$mail->addAddress($emailAdd);   
					$mail->isHTML(true);                                  // Set email format to HTML
					
					$mail->Subject = $subject;
					$mail->Body    = $body;
					$mail->AltBody = 'This email contain HTML that could not be displayed by your email reader. Please use a HTML email reader instead.';
					
					if(!$mail->send()) {
						$return = 'Error: ' . $mail->ErrorInfo;
					} else {
						$return = 'Sent';
					}				
				}
			} else {
				$mail->addAddress($to); 
				$mail->isHTML(true);                                  // Set email format to HTML
				
				$mail->Subject = $subject;
				$mail->Body    = $body;
				$mail->AltBody = 'This email contain HTML that could not be displayed by your email reader. Please use a HTML email reader instead.';
				
				if(!$mail->send()) {
					$return = 'Error: ' . $mail->ErrorInfo;
				} else {
					$return = 'Sent';
				}				
			} 
		} else {
		//Send Mail using PHP Mailer
			$headers = "From: " . getSetting('smtpUsername'). "\r\n";
			$headers .= 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";	
			//Send the email!
			mail($to,$email_subject,$emessage,$headers);	
		}
	}	

	
function shorten($intro, $len) { 
	$string = $intro;
	if (strlen($string) > $len) 
	{
    // truncate string
    $string = $stringCut = substr($string, 0, $len);
    // make sure it ends in a word so assassinate doesn't become ass...
    //$string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... '; 
	}
	return $string.'... ';
}
function reduceDate($date,$number) {
	if($number < 1) {
		$number = 1;	
	}
	$seconds = $number*60*60*24;
	$date = strtotime($date)-$seconds;
	return date('Y-m-d', $date);
}
function increaseDate($date,$number) {
	if($number < 1) {
		$number = 1;	
	}
	$seconds = $number*60*60*24;
	$date = strtotime($date)+$seconds;
	return date('Y-m-d', $date);
}
function addMinutes($date,$number) {
	 $minutes_to_add = $number; 
	 $newtimestamp = strtotime($date) + ($number*60);
	date('Y-m-d H:i:s', $newtimestamp); 
	
return 	date('Y-m-d H:i:s', $newtimestamp);
}
function scheduledBackup() {
	global $server;
	$tables = array();
	$result = mysqli_query($server,'SHOW TABLES');
	while($row = mysqli_fetch_row($result)) {
		$tables[] = $row[0];
	}	
	foreach($tables as $table){
		$result = mysqli_query($server,'DROP TABLE '.$table);
	}	
}
function getMonthDays($month) {
	$days = 31;
	if($month == '02') {
		$days = 29;	
	}
	if($month == '04' || $month == '06' || $month == '09' || $month == '11') {
		$days = 30;	
	}
	return $days;
}
function timeElapsed($ptime,$endtime='')
{
	global $LANG;
	if(empty($endtime))
	$endtime = time();
	if(!is_numeric($ptime))
	$ptime = strtotime($ptime);
	if(!is_numeric($endtime))
    $endtime = strtotime($endtime);
	
	$etime = $endtime - $ptime;
	if ($etime < 1)
    {
        return $LANG['Just now'];
    }

    $a = array( 365 * 24 * 60 * 60  =>  $LANG['year'],
                 30 * 24 * 60 * 60  =>  $LANG['month'],
			      7 * 24 * 60 * 60  =>  $LANG['week'],
                      24 * 60 * 60  =>  $LANG['day'],
                           60 * 60  =>  $LANG['hour'],
                                60  =>  $LANG['minute'],
                                 1  =>  $LANG['second']
                );
    $a_plural = array( 'year'   => $LANG['years'],
                       'month'  => $LANG['months'],
					   'week'  => $LANG['weeks'],
                       'day'    => $LANG['days'],
                       'hour'   => $LANG['hours'],
                       'minute' => $LANG['minutes'],
                       'second' => $LANG['seconds']
                );

    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' '.$LANG['ago'];
        }
    }
}

function getInterval($minutes) {
	$days = 'Every Hour';
	if($minutes > '60') {
		$days = $minutes/60;
		$days = 'Every '.$days.' Hours';	
	}
	if($minutes == '1440') {
		$days = $minutes/(60*24);
		$days = 'Once Daily';	
	}
	if($minutes >= '2880') {
		$days = $minutes/(60*24);
		$days = 'Every '.$days.' Days';	
	}	
	return $days;
}


function countCommas($value) {
	$value = explode(',', $value);
	return count($value);
}

function alterPhone($gsm,$code='') {
	$code = str_replace('+', '', $code);
	$array = is_array($gsm);
	$gsm = ($array) ? $gsm : explode(",",$gsm);
	$outArray = array();
	if(!empty($code)) {
		foreach($gsm as $item) {
			if(!empty($item)){
				$item1 = ltrim($item, '0');
				$item1 = (string)$item1;
				$codelen = strlen($code);
				$chk = substr($item1,0,$codelen);
				if($chk != $code) {
					$item1 = $code.$item1;
				} else {
					$item1 = $item1;
				}
				$outArray[] = $item1; 
			}
		}
	} else {
		$outArray = $gsm;
	}
	$return = ($array) ? $outArray : implode(",",$outArray);	
	return $return;
}

function removeDuplicate($myArray) {
	$array = is_array($myArray);
	$myArray = ($array) ? $myArray: explode(",",$myArray);
	$myArray = array_flip(array_flip(array_reverse($myArray,true)));
	return ($array) ? $myArray : implode(',',$myArray);
}
function mceil($number) {
	$array = explode(".",$number);
	$deci = ((int)$array[1] > 0) ? 1 : 0;
	return (int)$array[0] + $deci;
}
function messageLength($textMessage) {
	$test_Len = strlen($textMessage);
	$lines = substr_count( $textMessage, "\n" );
	$messageLength = $test_Len - $lines;
return $messageLength;	
}
function removeAllSpace($text) {
	return $string = preg_replace('/\s+/', '', $text);;	
}
function stripNonNumeric($test) {
	return preg_replace("/[^0-9,.]/", "",$test);		
}
function setTimeZone() {
	global $server;
	$serverTimeZone = getSetting('timeZone');
	if(userRole()>2) $serverTimeZone = userData(getUser(),'timezone_id');
	
	if(empty($serverTimeZone) || $serverTimeZone==0) $serverTimeZone = getSetting('timeZone',0);
	date_default_timezone_set($serverTimeZone);
	$timzn = date_default_timezone_get();	
}

function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('0 Bytes'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
}

function roleName($role) {
	if($role==1) {
		return 'Supper Admin';
	}
	if($role==2) {
		return 'Manager';
	}
	if($role==3) {
		return 'Reseller';
	}
	if($role==4) {
		return 'Customer';
	}
	return 'Unknow';
}

function backup_tables($type='Full system database backup',$tables = '*'){ 
	global $server;
	$return = '';
	
	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysqli_query($server,'SHOW TABLES');
		while($row = mysqli_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
	
	//cycle through
	foreach($tables as $table)
	{
		$result = mysqli_query($server,'SELECT * FROM '.$table);
		$num_fields = mysqli_num_fields($result);
		
		$return.= 'DROP TABLE '.$table.';';
		$row2 = mysqli_fetch_row(mysqli_query($server,'SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";
		
		for ($i = 0; $i < $num_fields; $i++) 
		{
			while($row = mysqli_fetch_row($result))
			{
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j<$num_fields; $j++) 
				{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = @ereg_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}
	
	//save file
	$database_backup = 'backups/db_backup'.time().'.sql';
	$handle = fopen($database_backup,'w+');
	fwrite($handle,$return);
	fclose($handle);
	
	//insert to record
	$filename = 'db_backup'.time().'.sql';
	$date = date('Y-m-d H:i:s');

	$add = mysqli_query($server,"INSERT INTO backups (`id`, `date`, `type`, `file`) 
			VALUES (NULL, '$date', '$type', '$filename');") or die(mysql_error());
	return $filename;
}


function restore_tables($filename){
	global $server;

	$templine = '';
	// Read in entire file
	$lines = file($filename);
	// Loop through each line
	foreach ($lines as $line){
		if (substr($line, 0, 2) == '--' || $line == '')
			continue;
	
	$templine .= $line;
		if (substr(trim($line), -1, 1) == ';')	{
			mysqli_query($server,$templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($server) . '<br /><br />');
			$templine = '';
		}
	}
}
function getLogo() {
	$logo = getSetting('siteLogo');	
	if(empty($logo)) $logo = getSetting('siteLogo',0);	
	if(empty($logo)) $logo = 'logo.png';
	return $logo;
}
function logEvent($user,$event) {
	global $server;
	$date = time();
	$ip = getUserIP();
	if(isAdmin(getUser())) {
		$user = getUser();	
	}
	mysqli_query($server, "INSERT INTO logs (`user_id`, `event`, `date`, `ip`)	VALUES ('$user', '$event', '$date','$ip');") or die (mysqli_error($server));
}
function createNotice($user,$note) {
	global $server;
	$date = time();
	$note = mysqli_real_escape_string($server,$note);
	mysqli_query($server, "INSERT INTO notice (`customer_id`, `note`, `date`, `is_seen`) VALUES ('$user', '$note', '$date','0');") or die (mysqli_error($server));
}
function validateUser($login,$password) {
	global $server;	
	global $LANG;
	$message = 'You have not supplied any login credentails';
  	$query="SELECT * FROM users WHERE username = '$login'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$num = mysqli_num_rows($result);
	if($num < 1) {
    	$message = "Your login credentail is not associated with any user here. Please check your details";
	} else {
		$pwsalt = explode( ":",$row["password"]);	
		$pass2 = $row["password"];		
		if(md5($password . $pwsalt[1]) != $pwsalt[0] && md5($password) != $row["password"]) {	
		   $message = "Oops! Your username or password is incorrect.";
		} else {
			$message = $row['id'];	
		}
	}
 	return $message;
}
function usernameExist($username) {
	global $server;	
	$query = "SELECT * FROM users WHERE username = '$username'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	if($num < 1) {
		 $found = 0;
	} else {
		$found = 1;
	}	
	return $found;
}
function currencyInUse($id) {
	global $server;	
	$query = "SELECT * FROM users WHERE currency_id = '$id'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	if($num < 1) {
		 return false;
	} else {
		return true;
	}	
}

function inSMSChat($from) {
	global $server;	
	$from = str_replace('+','',$from);
	$query = "SELECT * FROM smschat WHERE `number` = '$from'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	if($num < 1) {
		 return false;
	} else {
		return true;
	}	
}

function numberBlacklisted($to) {
	global $server;	
	$to = str_replace('+','',$to);
	$query = "SELECT * FROM blacklist WHERE `phone` = '$to'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	if($num < 1) {
		 return false;
	} else {
		return true;
	}	
}

function lastChatDate($from) {
	global $server;	
	$from = str_replace('+','',$from);
	$query = "SELECT * FROM smschat WHERE `number` = '$from' ORDER BY id DESC LIMIT 1";
	$result = mysqli_query($server,$query);  
	$num = mysqli_num_rows($result);
	$row = mysqli_fetch_assoc($result); 
	if($num>0) {
		return $row['date'];	
	}
	return 0;
}

function countNewChats($from) {
	global $server;	
	$from = str_replace('+','',$from);
	$query = "SELECT * FROM smschat WHERE `number` = '$from' AND `seen` = 0";
	$result = mysqli_query($server,$query);  
	return $num = mysqli_num_rows($result);	
}

function countCountry($id) {
	global $server;	
	$query = "SELECT * FROM users WHERE country_id = '$id'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	return $num;
}
function countInbox($id,$status='') {
	global $server;	
	$query = "SELECT * FROM inbox WHERE customer_id = '$id'";
	if(!empty($status)) $query .= " AND is_read = 0";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	return $num;
}

function getUserTime($userID) { 
	$tc = userData($userID,'country_id');
	$tz = countryTimeZone($tc);
	$timestamp = time();
	$dt = new DateTime("now", new DateTimeZone($tz)); 
	$dt->setTimestamp($timestamp); 
	return $dt->format('Y-m-d H:i:s');	
}
function showInboxCount($user) {
	if(countInbox($user,'yes')>0)
	echo '<span class="new badge red">'.countInbox($user,'yes').'</span>';	
}

function currencyExist($title,$symbol,$code,$id) {
	global $server;	
	$query = "SELECT * FROM currencies WHERE title = '$title' OR symbol = '$symbol' OR `code` = '$code'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	$row = mysqli_fetch_assoc($result); 
	if($num < 1) {
		 return 0;
	} else {
		if($row['id'] == $id) {
			return 0;	
		} else {
			return 1;	
		}
	}	
}
function countryExist($title,$id) {
	global $server;	
	$query = "SELECT * FROM countries WHERE name = '$title'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	$row = mysqli_fetch_assoc($result); 
	if($num < 1) {
		 return 0;
	} else {
		if($row['id'] == $id) {
			return 0;	
		} else {
			return 1;	
		}
	}	
}
function countryAdded($country,$id) {
	global $server;	
	$query = "SELECT * FROM allowed_countries WHERE country_id = '$country'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	$row = mysqli_fetch_assoc($result); 
	if($num < 1) {
		 return 0;
	} else {
		if($row['id'] == $id) {
			return 0;	
		} else {
			return 1;	
		}
	}	
}

function countryyInUse($id) {
	global $server;	
	$query = "SELECT * FROM users WHERE country_id = '$id'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	if($num < 1) {
		 return false;
	} else {
		return true;
	}	
}
function validateUserPIN($id,$password) {
	global $server;	
	global $LANG;
	$message = 'You have not supplied any valid PIN';
  	$query="SELECT * FROM users WHERE id = '$id'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$num = mysqli_num_rows($result);
	if($num < 1) {
    	$message = "You are not loged in. Please login and try again";
	} else {
		$pwsalt = explode( ":",$row["pin"]);	
		$pass2 = $row["pin"];		
		if(md5($password . $pwsalt[1]) != $pwsalt[0] && md5($password) != $row["password"]) {	
		   $message = "Oops! Your PIN is incorrect.";
		} else {
			$message = $row['id'];	
		}
	}
 	return $message;
}

function curl_get_contents($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

function gateAPIBalance($url) {
	if(empty($url)) return 'Unknown';
	$returned = curl_get_contents($url);
	if(!empty($returned)) {
		return $balance = correctNumber($returned);
	}	
	return 'Unknown';
}

function loadSMSGatewayParams($id) {
	global $server;
	$query="SELECT * FROM sms_gateways WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	return json_encode(mysqli_fetch_assoc($result));
	
}
//Get exchange rate for currencies
function getExchangeRate($from,$to) {
	$url = 'http://finance.yahoo.com/d/quotes.csv?f=l1d1t1&s='.$from.$to.'=X';
	$handle = fopen($url, 'r');
	if ($handle) {
		$result = fgetcsv($handle);
		fclose($handle);
	}
	$rate = $result[0];
	$datetime = $result[1].' '.$result[2];	
	return $rate;
}

//check if admin
function isAdmin($id) {
	global $server;	
	$query="SELECT * FROM users WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$isReseller = $row['role_id'];	
	if($isReseller > 2) {
	return false;
	} else {
	return true;
	}
}
function isResold($id) {
	global $server;	
	$query="SELECT * FROM users WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$reseller = $row['reseller'];	
	if($reseller < 1) {
	return false;
	} else {
	return true;
	}
}

function isReseller($id) {
	global $server;	
	$query="SELECT * FROM users WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$isReseller = $row['role_id'];	
	if($isReseller == 3) {
	return true;
	} else {
	return false;
	}
}
//check if super admin
function isSuperAdmin($id) {
	global $server;	
	$query="SELECT * FROM users WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$isReseller = $row['role_id'];	
	if($isReseller > 1) {
	return false;
	} else {
	return true;
	}
}

function paymentGatewayData($id,$field) {
  global $server;	
	$query="SELECT $field as value FROM paymentgateways WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}
function singleMessageData($id,$field) {
  global $server;	
	$query="SELECT $field as value FROM messagedetails WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}

function smsGatewayData($id,$field) {
  global $server;	
	$query="SELECT $field as value FROM sms_gateways WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}
function paymentGatewayTemplateData($alias,$field) {
  global $server;	
	$query="SELECT $field as value FROM paymentgateway_templates WHERE alias = '$alias'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}
function smsGatewayTemplateData($alias,$field) {
  global $server;	
	$query="SELECT $field as value FROM api_templates WHERE id = '$alias'"; 
	if(!is_numeric($alias)) $query="SELECT $field as value FROM api_templates WHERE alias = '$alias'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}

function transactionData($id,$field) {
  global $server;	
	$query="SELECT $field as value FROM transactions WHERE transaction_reference = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}

//get user data
function userData($id,$field) {
  global $server;	
	$query="SELECT $field as value FROM users WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}
function addressbookData($id,$field) {
  global $server;	
	$query="SELECT $field as value FROM phonebooks WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}
function marketinglistData($id,$field) {
  global $server;	
	$query="SELECT $field as value FROM marketinglist WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if($value=='0') return '0';
	if(empty($value)) {
	return '';
	} else {
	return $value;
	}
}
function canAccessList($id,$user) {
	global $server;	
	$query = "SELECT * FROM marketinglist_owners WHERE marketinglist_id = '$id' AND customer_id = '$user'";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$found = mysqli_num_rows($result);
	if($found > 0) return true;
	return false;
}
function canAccessPhonebook($id,$user) {
	global $server;	
	$query = "SELECT * FROM phonebook_owners WHERE phonebook_id = '$id' AND customer_id = '$user'";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$found = mysqli_num_rows($result);
	if($found > 0) return true;
	return false;
}

function getDefaultSenderID($customer) {
	$reseller = userData($customer,'reseller');
	$smsSender = getSetting('smsSender',$reseller);
	$sender = userData($customer,'default_sender_ID');	
	if(!empty($sender)) {
		return $sender;
	} else {
		return $smsSender;
	}
}

function sendPhoneVerify($customer,$token) {
	global $server;
	$reseller = userData($customer,'reseller');
	$sender_id = getSetting('smsSender',$reseller);
	$phone = userData($customer,'phone');
	$country = userData($customer,'country_id');
	$email = userData($customer,'email');
	$fname = userData($customer,'first_name');
	$lname = userData($customer,'last_name');
	$customer_id = $reseller;
	$message = "Hi $fname. Your phone number verification code is $token";
	//$country = getDestinationCountry($phone);
		mysqli_query($server, "INSERT INTO sentmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`sent_from`, `gateway_id`, `ip`, `notice`, `to_count`) 
		VALUES ('$message','$phone', '$customer_id', 'sms', '','".date('Y-m-d H:i:s')."', '$sender_id','0','0', '0', '','$country', 'queued', 'portal', '0', '0.0.0.0', '', '1');") ;
}

function sendWelcomeSMS($customer) {
	global $server;
	$reseller = userData($customer,'reseller');
	$sender_id = getSetting('smsSender',$reseller);
	$country = userData($customer,'country_id');
	$phone = userData($customer,'phone');
	$email = userData($customer,'email');
	$fname = userData($customer,'first_name');
	$lname = userData($customer,'last_name');
	$link_domain = home_base_url();
	if(!empty(getSetting('resellerDomain',$reseller)))	{
		$link_domain = 'http://'.getSetting('resellerDomain',$reseller);
	}
	$message = getSetting('newAccountSMS');
	$message = mysqli_real_escape_string($server,$message);
	if(!empty($message)) {
		$message = strtr($message, array("{name}" => $fname.' '.$lname, 
			"{email}" => $email,
			"{password}" => '*******',
			"{company}" => getSetting('businessName',$reseller),
			"{brand_name}" => getSetting('businessName',$reseller),
			"{url}" => $link_domain,
			"{phone}" => $phone,
			"{amount}" => 0,
			"{balance}" => 0
		));	
	$customer_id = $reseller;
	//$country = getDestinationCountry($phone);
		mysqli_query($server, "INSERT INTO sentmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`sent_from`, `gateway_id`, `ip`, `notice`, `to_count`) 
		VALUES ('$message','$phone', '$customer_id', 'sms', '','".date('Y-m-d H:i:s')."', '$sender_id','0','0', '0', '','$country', 'queued', 'portal', '0', '0.0.0.0', '', '1');") ;
	}
}

function sendNewpasswordSMS($customer,$password) {
	global $server;
	$reseller = userData($customer,'reseller');
	$sender_id = getSetting('smsSender',$reseller);
	$phone = userData($customer,'phone');
	$country = userData($customer,'country_id');
	$email = userData($customer,'email');
	$fname = userData($customer,'first_name');
	$lname = userData($customer,'last_name');
	$link_domain = home_base_url();
	if(!empty(getSetting('resellerDomain',$reseller)))	{
		$link_domain = 'http://'.getSetting('resellerDomain',$reseller);
	}
	$message = getSetting('newPasswordSMS');
	$message = mysqli_real_escape_string($server,$message);
	if(!empty($message)) {
		$message = strtr($message, array("{name}" => $fname.' '.$lname, 
			"{email}" => $email,
			"{password}" => $password,
			"{company}" => getSetting('businessName',$reseller),
			"{brand_name}" => getSetting('businessName',$reseller),
			"{url}" => $link_domain,
			"{phone}" => $phone,
			"{amount}" => 0,
			"{balance}" => 0
		));	
	$customer_id = $reseller;
	//$country = getDestinationCountry($phone);
		mysqli_query($server, "INSERT INTO sentmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`sent_from`, `gateway_id`, `ip`, `notice`, `to_count`) 
		VALUES ('$message','$phone', '$customer_id', 'sms', '','".date('Y-m-d H:i:s')."', '$sender_id','0','0', '0', '','$country', 'queued', 'portal', '0', '0.0.0.0', '', '1');") ;
	}
}

function sendTransactionSMS($customer,$amount) {
	global $server;
	$reseller = userData($customer,'reseller');
	$sender_id = getSetting('smsSender',$reseller);
	$phone = userData($customer,'phone');
	$country = userData($customer,'country_id');
	$email = userData($customer,'email');
	$fname = userData($customer,'first_name');
	$lname = userData($customer,'last_name');
	$link_domain = home_base_url();
	if(!empty(getSetting('resellerDomain',$reseller)))	{
		$link_domain = 'http://'.getSetting('resellerDomain',$reseller);
	}
	$message = getSetting('orderApproveSMS');
	$message = mysqli_real_escape_string($server,$message);
	if(!empty($message)) {
		$message = strtr($message, array("{name}" => $fname.' '.$lname, 
			"{email}" => $email,
			"{password}" => '******',
			"{company}" => getSetting('businessName',$reseller),
			"{brand_name}" => getSetting('businessName',$reseller),
			"{url}" => $link_domain,
			"{phone}" => $phone,
			"{amount}" => $amount.' '.userCurrencyCode($customer),
			"{balance}" => userWalletBalance($customer).' '.userCurrencyCode($customer)
		));	
	$customer_id = $reseller;
	//$country = getDestinationCountry($phone);
		mysqli_query($server, "INSERT INTO sentmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`sent_from`, `gateway_id`, `ip`, `notice`, `to_count`) 
		VALUES ('$message','$phone', '$customer_id', 'sms', '','".date('Y-m-d H:i:s')."', '$sender_id','0','0', '0', '','$country', 'queued', 'portal', '0', '0.0.0.0', '', '1');") ;
	}
}

function getDestinationCountry($phone) {
	global $server;	
	$phone = strtr ($phone, array ('+' => ''));	
	$query = "SELECT * FROM country_codes ORDER BY id DESC";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
    while ($rows = mysqli_fetch_assoc($result)) {
        $code = $rows['code'];
		$code = ltrim($code);
		$code = strtr ($code, array ('+' => ''));	
		$title = $rows['title'];
		$title = preg_replace("/[*0-9+]/","",$title);
		$name = ltrim($title);
		$len = strlen($code); 
		if(substr($phone,0,$len) == $code && $len > 0 && !empty($code)){
			$country = $title;  break;
		} else {
			$country  = 'Unknown';	
		}
	}
	return $country;	
}
function getDestinationCode($phone) {
	global $server;	
	$country = 0;
	$phone = strtr ($phone, array ('+' => ''));	
	$query = "SELECT * FROM country_codes ORDER BY id DESC";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
    while ($rows = mysqli_fetch_assoc($result)) {
        $code = $rows['code'];
		$code = ltrim($code);
		$code = strtr ($code, array ('+' => ''));	
		$title = $rows['title'];
		$title = preg_replace("/[*0-9+]/","",$title);
		$name = ltrim($title);
		$len = strlen($code); 
		if(substr($phone,0,$len) == $code && $len > 0 && !empty($code)){
			$country = $code;  break;
		}
	}
	return $country;	
}

function getCustomerDestinationRoute($type,$phone,$customer) {
	global $server;	
	$phone = strtr ($phone, array ('+' => ''));	
	$ccode = getDestinationCode($phone);
	$country  = defaultCustomerRoute($type,$customer);
	$query = "SELECT * FROM routes WHERE `type` = '$type' AND country_code = '$ccode' AND customer_id = '$customer'";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
    while ($rows = mysqli_fetch_assoc($result)) {
		$country2 = defaultCustomerCountryRoute($type,$customer,$ccode);
		if($country2>0)$country=$country2;
        $code = $ccode.$rows['operator_code'];
		$code = ltrim($code);
		$code = strtr ($code, array ('+' => ''));	
		$title = $rows['gateway_id'];
		$len = strlen($code); 
		if(substr($phone,0,$len) == $code && $len > 0 && !empty($code)){
			$country = $title;  break;
		} 
	}
	return $country;	
}

function getDestinationRoute($type,$phone,$customer,$gateway=0) {
	global $server;	
	if($gateway > 0) return $gateway;
	$phone = strtr ($phone, array ('+' => ''));	
	$ccode = getDestinationCode($phone);
	$hasCust = 0;
	if($customer > 0) {
		$hasCust = getCustomerDestinationRoute($type,$phone,$customer);
		if($hasCust>0) { 
			return $hasCust;
		}
	}
	$country  = defaultRoute($type);
	$query = "SELECT * FROM routes WHERE `type` = '$type' AND country_code = '$ccode'";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
    while ($rows = mysqli_fetch_assoc($result)) {
		$country2 = defaultCountryRoute($type,$ccode);
		if($country2>0)$country=$country2;
        $code = $ccode.$rows['operator_code'];
		$code = ltrim($code);
		$code = strtr ($code, array ('+' => ''));	
		$title = $rows['gateway_id'];
		$len = strlen($code); 
		if(substr($phone,0,$len) == $code && $len > 0 && !empty($code)){
			$country = $title;  break;
		} 
	}
	if($gateway > 0) {
		return $gateway;	
	}
	return $country;	
}

function defaultRoute($type) {
  global $server;	
	$query = "SELECT * FROM routes WHERE `type` = '$type' AND country_code = '0' AND operator_code = 0 AND customer_id = 0 LIMIT 1";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['gateway_id'];	
	if(empty($value)) {
	return 0;
	} else {
	return $value;
	}
}
function defaultCustomerRoute($type,$customer) {
  global $server;	
	$query = "SELECT * FROM routes WHERE `type` = '$type' AND country_code = '0' AND operator_code = 0 AND customer_id = '$customer' LIMIT 1";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['gateway_id'];	
	if(empty($value)) {
	return 0;
	} else {
	return $value;
	}
}
function defaultCountryRoute($type,$country) {
  global $server;	
	$query = "SELECT * FROM routes WHERE `type` = '$type' AND country_code = '$country' AND operator_code = 0 AND customer_id = 0 LIMIT 1";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['gateway_id'];	
	if(empty($value)) {
	return 0;
	} else {
	return $value;
	}
}
function defaultCustomerCountryRoute($type,$customer,$country) {
  global $server;	
	$query = "SELECT * FROM routes WHERE `type` = '$type' AND country_code = '$country' AND operator_code = 0 AND customer_id = '$customer' LIMIT 1";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['gateway_id'];	
	if(empty($value)) {
	return 0;
	} else {
	return $value;
	}
}
//get user image
function userImage($id) {
  global $server;	
	$query="SELECT photo as value FROM users WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if(empty($value)) {
	return 'files/user.png';
	} else {
	return 'files/'.$value;
	}
}

//get withdrawal method details
function withdrawalOption($id) {
  global $server;	
	$query="SELECT * FROM withdrawal_option WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['paypal_id'];	
	if(!empty($value)) {
	return '<strong>PayPal</strong>:- '.$value;
	} else {
	return '<strong>Bank Transfer</strong>: ('.$row['bank_name'].'), '.$row['account_name'].', '.$row['account_number'];
	}
}
//check if method is paypal
function isPayPal($withdrawal) {
  global $server;	
	$query="SELECT * FROM withdrawal_option WHERE id = '$withdrawal'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['paypal_id'];	
	if(empty($value)) {
	return false;
	} else {
	return true;
	}
}

function removeHTML($text) {
	$a = array('<p>','</p>','<div>','</div>');
	$b = array(' ','<br>',' ','<br>');
	return str_replace($a,$b,$text);	
}

function userExchangeRate($user) {
	$currency = userData($user,'currency_id');
	if(isAdmin($user)) return 1;
	return 	currencyRate($currency);
}
function userCurrencySymbol($id) {
  global $server;	
  $currency = userData($id,'currency_id') ;
 	if(isAdmin($id)) return currencySymbol(getSetting('defaultCurrency',0));
	$query="SELECT * FROM currencies WHERE id = '$currency'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['symbul'];	
}
function transactionType($id) {
  global $server;	
	$query="SELECT * FROM transaction_types WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['title'];	
}
function lastRate($currency) {
  global $server;	
	$query="SELECT * FROM rate_log WHERE currency_id = '$currency' AND date LIKE '%".date('Y-m-d')."%' ORDER BY date DESC LIMIT 1,1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['rate'];	
}
function dateRate($currency,$date) {
  global $server;	
	$query="SELECT * FROM rate_log WHERE currency_id = '$currency' AND date LIKE '%$date%' ORDER BY date DESC LIMIT 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['rate'];	
}

function convertDate($date) {
	if(is_numeric($date)) {
		$date = date('Y-m-d',$date)	;
	} else {
		$date = strtotime($date);
		$date = date('Y-m-d', $date);
	}
	return $date;
}
function convertTime($date) {
	if(is_numeric($date)) {
		$date = date('Y-m-d H:i:s',$date);
		$date2 = date('Y-m-d',$date);
	} else {
		$date = strtotime($date);
		$date = date('Y-m-d H:i:s', $date);
		$date2 = date('Y-m-d',$date);
	}
	return str_replace($date2.' ','',$date);
}
function dateAverageRate($currency,$date) {
  global $server;	
	$query="SELECT sum(rate) as rate, count(id) as total FROM rate_log WHERE currency_id = '$currency' AND date LIKE '%$date%'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return round($row['rate']/$row['total'],2);	
}

function ratePercent($old,$new) {
	$percent = (($new-$old)/$new)*100;
	return round($percent,2);
}

function rateStatus($old,$new) {
	if($old>$new) {
		return '<i class="red"><i class="fa fa-sort-desc"></i>';	
	} else {
		return '<i class="green"><i class="fa fa-sort-asc"></i>';
	}
}

function userCurrencyCode($id) {
  global $server;	
  $currency = userData($id,'currency_id') ;
  if(isAdmin($id)) return currencyCode(getSetting('defaultCurrency',0));
	$query="SELECT * FROM currencies WHERE id = '$currency'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['code'];	
}
function memberByEmail($email,$user=0) {
  global $server;	
  $reseller = userData($user,'reseller') ;
	$query="SELECT * FROM users WHERE email = '$email' AND reseller = '$reseller' OR reseller = '$user' LIMIT 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$id =  $row['id'];
	if($user > 0 && $id==$user)
	$id = 0;
	return $id;	
}

function sunTransactions($date='') {
  global $server;	
  	$added = '';
	if(!empty($date)) $added = " AND t.`date` LIKE '%$date%'";
	$query="SELECT SUM(t.cost/c.rate) as value FROM transactions t JOIN users u ON t.customer_id = u.id JOIN currencies c ON u.currency_id = c.id WHERE t.status LIKE 'completed' AND t.is_earned = 0 AND t.cost > 0".$added; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}

function sunBalance($date='') {
  global $server;	
  	$added = '';
	$query="SELECT SUM(t.credits/c.rate) as value FROM transactions t JOIN users u ON t.customer_id = u.id JOIN currencies c ON u.currency_id = c.id WHERE t.status LIKE 'completed'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$spent  = $row['value'];	
	
	$query="SELECT SUM(m.cost/c.rate) as value FROM messagedetails m JOIN users u ON m.customer_id = u.id JOIN currencies c ON u.currency_id = c.id WHERE m.cost > 0"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$sent  = $row['value'];	
	
	$value = $spent-$sent;
	return $value;
}

function creditUsed($id) {
  global $server;	
	$query="SELECT SUM(cost) as value FROM messagedetails WHERE customer_id = '$id' AND status LIKE 'sent'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}
function creditEarned($id) {
  global $server;	
	$query="SELECT SUM(credits) as value FROM transactions WHERE customer_id = '$id' AND status LIKE 'completed' AND is_earned = 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}
function refferedSales($id) {
  global $server;	
	$query="SELECT count(id) as value FROM transactions WHERE customer_id = '$id' AND status LIKE 'completed' AND is_earned = 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}
function refferedSignups($id) {
  global $server;	
	$query="SELECT count(id) as value FROM users WHERE referrer = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}
function countCustomers() {
  global $server;	
	$query="SELECT count(id) as value FROM users WHERE role_id = '4'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}
function countReseller() {
  global $server;	
	$query="SELECT count(id) as value FROM users WHERE role_id = '3'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}
function countNewSender() {
  global $server;	
	$query="SELECT count(id) as value FROM sender_id WHERE status = 'pending'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}
function countNewTicket($user=0) {
  global $server;	
	$query="SELECT count(t.id) as value FROM tickets t JOIN users u ON t.customer_id = u.id WHERE t.customer_reply = '1' AND t.parent_id = 0 AND u.reseller = '$user'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}
function messageCost($id) {
  global $server;	
	$query="SELECT SUM(cost) as value FROM messagedetails WHERE message_id = '$id' AND status LIKE 'sent'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	if(empty($value)) return 0.000;
	return $value;
}
function messageProgress($id) {
  global $server;	
	$query="SELECT count(id) as value FROM messagedetails WHERE message_id = '$id' AND status NOT LIKE '%queued%'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	$query="SELECT count(id) as value FROM messagedetails WHERE message_id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value2 = $row['value'];	
	return $value.'/'.$value2;
}
function sentMessageProgress($id) {
  global $server;	
	$query="SELECT count(id) as value FROM messagedetails WHERE message_id = '$id' AND status LIKE '%sent%'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	$query="SELECT count(id) as value FROM messagedetails WHERE message_id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value2 = $row['value'];	
	return $value.'/'.$value2;
}

function userWalletBalance($id) {
  global $server;	
	$query="SELECT SUM(credits) as value FROM transactions WHERE customer_id = '$id' AND status LIKE 'Completed'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value-creditUsed($id);
}
function userCreditShared($id) {
  global $server;	
	$query="SELECT SUM(credits) as value FROM transactions WHERE customer_id = '$id' AND status LIKE 'Completed' AND credits < 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}

function userLastRecharge($id) {
  global $server;	
	$query="SELECT credits as value FROM transactions WHERE customer_id = '$id' AND status LIKE 'Completed' AND credits > 0 AND is_earned < 1 ORDER BY id DESC LIMIT 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}

function userAllRecharge($id) {
  global $server;	
	$query="SELECT sum(credits) as value FROM transactions WHERE customer_id = '$id' AND status LIKE 'Completed' AND credits > 0 AND is_earned < 1 "; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$value = $row['value'];	
	return $value;
}

function allWalletBalance($id) {
  global $server;	
	$query="SELECT SUM(t.amount_in) as value FROM transactions t JOIN users u ON t.customer_id = u.id WHERE t.type = '2' AND t.status LIKE 'Completed' AND u.role_id > 2"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$amount_in = $row['value'];	
	$query="SELECT SUM(t.amount_out) as value FROM transactions t JOIN users u ON t.customer_id = u.id WHERE t.type = '2' AND t.status LIKE 'Completed' AND u.role_id > 2"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$amount_out = $row['value'];	
	$value = $amount_in-$amount_out;
	return $value;
}
function allBTCBalance($id) {
  global $server;	
	$query="SELECT SUM(amount_in) as value FROM transactions WHERE type = '1' AND status LIKE 'Completed'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$amount_in = $row['value'];	
	$query="SELECT SUM(amount_out) as value FROM transactions WHERE type = '1' AND status LIKE 'Completed'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$amount_out = $row['value'];	
	$value = $amount_in-$amount_out;
	return $value;
}

function keywordExist($keyword,$list,$code) {	
  global $server;	
	$query="SELECT id as value FROM marketinglist WHERE (optin_keyword LIKE '%$keyword%' OR optout_keyword LIKE '%$keyword%') AND shortcode LIKE '%$code%' LIMIT 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$found = $row['value'];
	if($list > 0 && $found == $list) return false;
	if($found > 0) return true;
	return false;
}
function contactExist($phone,$list,$type) {
  global $server;	
	$query="SELECT * FROM marketingcontacts WHERE phone = '$phone' AND marketinglist = '$list'"; 
	if($type=='contact') {
		$query="SELECT * FROM contacts WHERE phone = '$phone' AND phonebook_id = '$list'"; 
	}
	$result = mysqli_query($server,$query) or die(mysqli_error($server));
	$x = mysqli_num_rows($result);
	return $x;
}
function email_address_registered($email) {
	global $server;
	$query = "SELECT * FROM users WHERE email = '$email'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);	
	if($num < 1) {	
		return false;
	}
	return true;
}
function correctNumber($sring) {
	return preg_replace('/[^0-9.]/', '', $sring);;	
}
function userBTCBalance($id) {
  global $server;	
  return getBTCBalance($id);
}
function defaultCurrencyName() {
  global $server;	
  $id = getSetting('defaultCurrency');
	$query="SELECT * FROM currencies WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['title'];	
}
function defaultCurrencyCode() {
  global $server;	
  $id = getSetting('defaultCurrency');
	$query="SELECT * FROM currencies WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['code'];	
}
function defaultCurrencySymbol() {
  global $server;	
  $id = getSetting('defaultCurrency');
	$query="SELECT * FROM currencies WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['symbul'];	
}
function getLastID($table) {
  global $server;	
	$query="SELECT * FROM `".$table."` ORDER BY id DESC LIMIT 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['id'];	
}
function defaultCurrencyRate() {
  global $server;	
  $id = getSetting('defaultCurrency');
	$query="SELECT * FROM currencies WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['rate'];	
}
function currencyName($id) {
  global $server;	
	$query="SELECT * FROM currencies WHERE id = '$id' OR `code` = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['title'];	
}
function currencySymbol($id) {
  global $server;	
	$query="SELECT * FROM currencies WHERE id = '$id' OR `code` = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['symbul'];	
}
function currencyRate($id) {
  global $server;	
	$query="SELECT * FROM currencies WHERE id = '$id' OR `code` = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['rate'];	
}
function currencyCode($id) {
  global $server;	
	$query="SELECT * FROM currencies WHERE id = '$id' OR `code` = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['code'];	
}
function countNotice($user) {
  global $server;	
	$query="SELECT count(id) as value FROM notice WHERE customer_id = '$user' AND is_seen = 0"; 
	if(isAdmin($user)) 
	$query="SELECT count(id) as value FROM notice WHERE (customer_id = '$user' OR customer_id = '0') AND is_seen = 0"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function forbiddenAllowed($id) {
  global $server;	
	$query="SELECT * FROM forbidden_country WHERE country_id = '$id' LIMIT 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['id'];	
}

function countryCurrency($id) {
  global $server;	
	$query="SELECT * FROM allowed_countries WHERE country_id = '$id' LIMIT 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['currency_id'];	
}
function forbiddenSenderID($sender,$userID) {
  global $server;	
  $resellerID = userData($userID,'reseller');
  $query="SELECT * FROM fobidden_sender WHERE sender_id LIKE '$sender' AND (customer_id = 0 OR customer_id = '$resellerID')"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$numb = mysqli_num_rows($result);
	if($numb > 0) return true;
	return false;	
}

function forbiddenEmail($email,$userID) {
  global $server;	
  $resellerID = userData($userID,'reseller');
  $query="SELECT * FROM fobidden_email WHERE (email LIKE '%$email%' OR '$email' LIKE CONCAT('%', `email`, '%')) AND (customer_id = 0 OR customer_id = '$resellerID')"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$numb = mysqli_num_rows($result);
	if($numb > 0) return true;
	return false;	
}

function forbiddenWord($word,$userID) {
  global $server;	
  $resellerID = userData($userID,'reseller');
  $query="SELECT * FROM forbidden_words WHERE ('$word' LIKE CONCAT('%', `word`, '%')) AND (customer_id = 0 OR customer_id = '$resellerID')"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$numb = mysqli_num_rows($result);
	if($numb > 0) return true;
	return false;	
}

function forbiddenIP($ip,$userID) {
  global $server;	
  $resellerID = userData($userID,'reseller');
  $query="SELECT * FROM fobidden_ip WHERE ('$ip' LIKE CONCAT('%', `ip`, '%')) AND (customer_id = 0 OR customer_id = '$resellerID')";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$numb = mysqli_num_rows($result);
	if($numb > 0) return true;
	return false;	
}


function getCountryList($default) {		
	global $server;		
	$return = '';	
	$query="SELECT * FROM countries order by country_name asc";
    $result = mysqli_query($server,$query);
    while ($rows = mysqli_fetch_assoc($result)) {
        $id = $rows['id'];
        $title = $rows['country_name'];
		$title = preg_replace("/[*0-9+]/","",$title);
		$title = strtr($title, array ('\'' => ' '));
		$value = ltrim($title);
        $return .= '<option '; 
		if(forbiddenAllowed($id)>0) { 	$return .= ' disabled '; }
		if($default == $id || stripos(ltrim($title),$default) !== false) $return .= 'selected ';  
	    $return .= 'value="'.$id.'">'.$title.'</option>';
	}
	return $return;
}

function getCurrencyList($default) {		
	global $server;		
	$return = '';	
	$query="SELECT * FROM currencies order by title asc";
    $result = mysqli_query($server,$query);
    while ($rows = mysqli_fetch_assoc($result)) {
        $id = $rows['id'];
        $title = $rows['title'];
        $return .= '<option '; 
		if($default == $id || stripos(ltrim($title),$default) !== false) $return .= 'selected ';  
	    $return .= 'value="'.$id.'">'.$title.'</option>';
	}
	return $return;
}

function listAddressbook($user,$default) {		
	global $server;		
	$default = explode(',',$default);
	$return = '';	
	$query="SELECT * FROM phonebook_owners where customer_id = '$user' order by id desc";
    $result = mysqli_query($server,$query);
    while ($rows = mysqli_fetch_assoc($result)) {
        $id = $rows['phonebook_id'];
		$owner = $rows['is_owner'];
        $title = addressbookData($id,'title');
		if($owner < 1) $title .= ' (Shared)';
		$value = ltrim($title);
        $return .= '<option '; 
		if (in_array($id, $default)) $return .= 'selected ';  
	    $return .= 'value="'.$id.'">'.$title.'</option>';
	}
	return $return;
}
function listSenderID($user,$ype='') {		
	global $server;		
	$default = userData($user,'default_sender_ID');
	$return = '';	
	$query="SELECT * FROM sender_id where customer_id = '$user' and status = 'approved' and type LIKE '%$type%' order by id desc";
    $result = mysqli_query($server,$query);
    while ($rows = mysqli_fetch_assoc($result)) {
        $sender_id = $rows['sender_id'];
        $return .= '<option '; 
		if($default == $sender_id) $return .= 'selected ';  
	    $return .= 'value="'.$sender_id.'">'.$sender_id.'</option>';
	}
	return $return;
}
function getCycle($cycle) {
	if($cycle == '1') return 'Monthly';
	if($cycle == '3') return 'Quarterly';
	if($cycle == '6') return 'Semi-Annually';
	if($cycle == '12') return 'Annually';
	return 'One-time';	
}
function listShortcodes($user,$default='') {		
	global $server;		
	$return = '';	
	$query="SELECT * FROM shortcodes where customer_id = '$user' OR is_public = 1 order by id desc";
    $result = mysqli_query($server,$query);
    while ($rows = mysqli_fetch_assoc($result)) {
        $sender_id = $rows['shortcode'];
		$addon = '';
		if($rows['is_public']==1) $addon = ' (Shared)';
        $return .= '<option '; 
		if($default == $sender_id) $return .= 'selected ';  
	    $return .= 'value="'.$sender_id.'">'.$sender_id.$addon.'</option>';
	}
	return $return;
}

function listByKeyword($word,$shortcode) {
  global $server;	
  $shortcode = str_ireplace('+','',$shortcode);	
  $query="SELECT * FROM marketinglist WHERE ('$word' LIKE CONCAT('%', `optout_keyword`, '%') OR '$word' LIKE CONCAT('%', `optin_keyword`, '%')) AND shortcode = '$shortcode'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$numb = mysqli_num_rows($result);
	$rows = mysqli_fetch_assoc($result);
	//if($numb > 0) return true;
	return $rows['id'];
}

function checkOptOutKey($word,$shortcode) {
  global $server;	
  $shortcode = str_ireplace('+','',$shortcode);	
  $query="SELECT * FROM marketinglist WHERE ('$word' LIKE CONCAT('%', `optout_keyword`, '%')) AND shortcode = '$shortcode'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$numb = mysqli_num_rows($result);
	$rows = mysqli_fetch_assoc($result);
	//if($numb > 0) return true;
	return $rows['id'];
}

function checkOptinKey($word,$shortcode) {
  global $server;	
  $shortcode = str_ireplace('+','',$shortcode);	
  $query="SELECT * FROM marketinglist WHERE ('$word' LIKE CONCAT('%', `optin_keyword`, '%')) AND shortcode = '$shortcode'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$numb = mysqli_num_rows($result);
	$rows = mysqli_fetch_assoc($result);
	//($numb > 0) return true;
	return $rows['id'];
}


function shortcodeOwner($number) {		
	global $server;	
	$number = str_ireplace('+','',$number);	
	$return = '0';	
	$query="SELECT * FROM shortcodes WHERE shortcode = '$number'";
    $result = mysqli_query($server,$query);
    $rows = mysqli_fetch_assoc($result);
    $return = $rows['customer_id'];
	return $return;
}

function listMarketingList($user,$default) {		
	global $server;		
	$default = explode(',',$default);
	$return = '';	
	$query="SELECT * FROM marketinglist_owners where customer_id = '$user' order by id desc";
    $result = mysqli_query($server,$query);
    while ($rows = mysqli_fetch_assoc($result)) {
        $id = $rows['marketinglist_id'];
		$owner = $rows['is_owner'];
        $title = addressbookData($id,'title');
		if($owner < 1) $title .= ' (Shared)';
		$value = ltrim($title);
        $return .= '<option '; 
		if (in_array($id, $default)) $return .= 'selected ';  
	    $return .= 'value="'.$id.'">'.$title.'</option>';
	}
	return $return;
}
function countPage($message,$type,$duration) {
	$lenght = countCharacters($message);
	if (strlen($message) != strlen(utf8_decode($message))){
		if($lenght <= 70) {	$page = 1;
		} elseif($lenght > 70 && $lenght <= 140) { 	$page = 2;
		} elseif($lenght > 140 && $lenght <= 210) {	$page = 3;
		} elseif($lenght > 210 && $lenght <= 280) {	$page = 4;
		} elseif($lenght > 280 && $lenght <= 350) {	$page = 5;
		} elseif($lenght > 350 && $lenght <= 420) {	$page = 6;
		} elseif($lenght > 420 && $lenght <= 490) {	$page = 7;
		} elseif($lenght > 490 && $lenght <= 560) {	$page = 8;
		} elseif($lenght > 560 && $lenght <= 630) {	$page = 9;
		} elseif($lenght > 630 && $lenght <= 700) {	$page = 10;
		} elseif($lenght > 700 && $lenght <= 770) {	$page = 11;
		} elseif($lenght > 770 && $lenght <= 840) {	$page = 12;
		} elseif($lenght > 840 && $lenght <= 910) {	$page = 13;
		} else{ $page = 14; }
	} else {
		if($lenght <= 160) {	$page = 1;
		} elseif($lenght > 160 && $lenght <= 306) { $page = 2;
		} elseif($lenght > 306 && $lenght <= 459) {	$page = 3;
		} elseif($lenght > 459 && $lenght <= 612) {	$page = 4;
		} elseif($lenght > 612 && $lenght <= 765) {	$page = 5;
		} elseif($lenght > 765 && $lenght <= 918) {	$page = 6;	
		} else{ $page = 7; }
	}
	if($type=='mms' || $type=='whatsapp') $page = 1;
	if($type=='voice') $page = $duration;
	return $page;
}

function countRecipient($to) {
	$searchKeys = array("\r\n","<br>","\n","\r",";"," ");
	$replaceKeys = array(",",",",",",",");
	$to = str_replace( $searchKeys , $replaceKeys , $to);
	$to = preg_replace("/[^0-9+,]/", "", $to );
	$to = rtrim($to,',');
	if(empty($to)) return 0;
	$to = explode(',',$to);	
	$to = removeDuplicate($to);
	return count($to);
}
function defaultCost($type,$user) {
  	global $server;	
  	$reseller = userData($user,'reseller');
	$query="SELECT * FROM rates WHERE type = '$type' AND reseller_id = '$reseller' AND country_code = '0' AND operator_code = '0'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['rate'];	
}

function defaultCustomerCost($type,$user) {
  	global $server;	
  	$reseller = userData($user,'reseller');
	$query="SELECT * FROM rates WHERE type = '$type' AND customer_id = '$user' AND country_code = '0' AND operator_code = '0'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['rate'];	
}
function customerSMSCost($to,$type,$country,$page,$user) {
  	global $server;		
	$to = alterPhone($to,countryPhoneCode($country));
	$to = removeDuplicate($to);
	$requiredCredit = 0;

	$query="SELECT * FROM rates WHERE type = '$type' AND customer_id = '$user' AND country_code != '0'";
    $result = mysqli_query($server,$query);
    $countryPrices = array();
	while ($rows = mysqli_fetch_assoc($result)) {
        if($rows['operator_code']==0) {
			$countryPrices[] = explode(':',$rows['country_code'].''.':'.$rows['rate']);
		} else {
			$countryPrices[] = explode(':',$rows['country_code'].$rows['operator_code'].':'.$rows['rate']);
		}
	}
    $recipientList = explode(",", $to);
	for($i=0; $i < count($recipientList); $i++){
		$unitcost = defaultCustomerCost($type,$user);
		for($j=0; $j < count($countryPrices); $j++){
			$len = strlen($countryPrices[$j][0]); 
			if(substr($recipientList[$i],0,$len) == $countryPrices[$j][0] && $len > 0 && !empty($countryPrices[$j][0])){
				$unitcost=$countryPrices[$j][1]; 
				break;
			}
		} 
	 	$requiredCredit += ($page*$unitcost);
	} 
	return $requiredCredit;
}

function getCountryByCode($phone) {
	global $server;
	$phone = strtr ($phone, array ('+' => ''));	
	$sql = "SELECT * FROM country_codes ORDER BY id DESC";
	$result = mysqli_query($server,$sql) or die(mysqli_error($server));
	while ($rows = mysqli_fetch_assoc($result)) { 
		$code = $rows['code'];
		$code = ltrim($code);
		$code = strtr ($code, array ('+' => ''));	
		$title = $rows['title'];	
		$title = preg_replace("/[*0-9+]/","",$title);
		$name = ltrim($title);
		$name = rtrim($name);
		$len = strlen($code); 
		if(substr($phone,0,$len) == $code && $len > 0 && !empty($code)){
			$country = $name; 
			$query="SELECT * FROM countries WHERE country_name LIKE '%$country%' LIMIT 1"; 
			$result = mysqli_query($server,$query) or die(mysqli_error($server));  
			$row = mysqli_fetch_assoc($result); 
			$country =  $row['id'];
			break;
		} else {
			$country  = 'Unknown';	
		}
	}
	return $country;	
}

function smsCost($to,$type,$country,$page,$user=0) {
	global $server;	
	$requiredCredit = customerSMSCost($to,$type,$country,$page,$user);	
	if(countRecipient($to) < 1) return 0;
	if($requiredCredit < 1) {
		$reseller = userData($user,'reseller');
		$to = alterPhone($to,countryPhoneCode($country));
		$to = removeDuplicate($to);
		$requiredCredit = 0;
		$query="SELECT * FROM rates WHERE type = '$type' AND reseller_id = '$reseller' AND country_code > 0 AND customer_id < 1";
		$result = mysqli_query($server,$query);
		$countryPrices = array();
		while ($rows = mysqli_fetch_assoc($result)) {
			if($rows['operator_code']==0) {
				$countryPrices[] = explode(':',$rows['country_code'].''.':'.$rows['rate']);
			} else {
				$countryPrices[] = explode(':',$rows['country_code'].$rows['operator_code'].':'.$rows['rate']);
			}
		}
		$recipientList = explode(",", $to);
		for($i=0; $i < count($recipientList); $i++){			
			$unitcost = defaultCost($type,$user);
			for($j=0; $j < count($countryPrices); $j++){
				$len = strlen($countryPrices[$j][0]); 
				if(substr($recipientList[$i],0,$len) == $countryPrices[$j][0] && $len > 0 && !empty($countryPrices[$j][0])){
					$unitcost=$countryPrices[$j][1]; 
					break;
				}
			} 
			$requiredCredit += ($page*$unitcost);
		} 
	}
	return $requiredCredit;
}

function getContacts($list,$type='phonebook') {
  	global $server;		
	$query="SELECT * FROM contacts WHERE phonebook_id = '$list'";
	if($type=='marketing') {
		$query="SELECT * FROM marketingcontacts WHERE marketinglist = '$list'";
	}
    $result = mysqli_query($server,$query);
    $contacts = '';
	while ($rows = mysqli_fetch_assoc($result)) {
        $contacts .= $rows['phone'].',';
	}
	return rtrim($contacts,',');	
}

function countContacts($list,$type='phonebook') {
  	global $server;		
	$query="SELECT count(id) as value FROM contacts WHERE phonebook_id = '$list'";
	if($type=='marketing') {
		$query="SELECT count(id) as value FROM marketingcontacts WHERE marketinglist = '$list'";
	}
    $result = mysqli_query($server,$query);
    $row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function countListUsers($list,$type='phonebook') {
  	global $server;		
	$query="SELECT count(id) as value FROM phonebook_owners WHERE phonebook_id = '$list'";
	if($type=='marketing') {
		$query="SELECT count(id) as value FROM marketinglist_owners WHERE marketinglist_id = '$list'";
	}
    $result = mysqli_query($server,$query);
    $row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function correctRecipient($to) {
	$searchKeys = array("\r\n","<br>","\n","\r",";"," ");
	$replaceKeys = array(",",",",",",",");
	$to = str_replace( $searchKeys , $replaceKeys , $to);
	$to = preg_replace("/[^0-9+,]/", "", $to );
	return $to;
}
function countCharacters($text) {
	$text_Len = strlen($text);
	if (strlen($text) != strlen(utf8_decode($text))){
		$test_Len = strlen(utf8_decode($text));
	}
	$text_Len = strlen($text);
	$lines = substr_count( $text, "\n" );
	$messageLength = $text_Len - $lines;
return $messageLength;	
}

function checkPassword($pwd) {
    $errors = '';
    if (strlen($pwd) < 8) {
        $errors = "Password too short! Please use 8 characters at least";
    }else if (!preg_match("#[0-9]+#", $pwd)) {
        $errors = "Password must include at least one number!";
    }else if (!preg_match("#[a-zA-Z]+#", $pwd)) {
        $errors = "Password must include at least one letter!";
    }     
    return $errors;
}
function checkEmailAddress($email) {
	if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
     	return false;
    }
	return true;	
}
function countryName($id) {
  global $server;
   if(!is_numeric($id)) return $id;	
	$query="SELECT * FROM countries WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$title = $row['country_name'];
	return $title;	
}
function countryTimeZone($id) {
  global $server;	
	$query="SELECT zone_name FROM time_zone t JOIN countries c ON t.country_code = c.country_code WHERE c.id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$title = $row['zone_name'];
	return $title;	
}

function rateExist($customer,$country,$operator,$type,$reseller) {
	global $server;	
	$query="SELECT * FROM rates WHERE customer_id = '$customer' AND `country_code` = '$country'  AND `operator_code` = '$operator'  AND `type` = '$type'  AND `reseller_id` = '$reseller' LIMIT 1";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$x = $row['id'];
	return $x;
}
function routeExist($customer,$country,$operator,$type,$group) {
	global $server;	
	$query="SELECT * FROM routes WHERE customer_id = '$customer' AND `country_code` = '$country'  AND `operator_code` = '$operator'  AND `type` = '$type'  AND `group_id` = '$group' LIMIT 1";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$x = $row['id'];
	return $x;
}

function countryCode($id) {
  global $server;	
	$query="SELECT * FROM countries WHERE id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$title = $row['country_code'];
	return $title;	
}
function countryPhoneCode($id) {
  global $server;	
	$query="SELECT * FROM country_codes WHERE title LIKE '%".countryName($id)."%'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	$title = preg_replace("/[^0-9]/","",$row['code']);
	if($id < 1) return '';
	return $title;	
}

function allCountryList($default) {		
	global $server;		
	$return = '';	
	$query="SELECT * FROM countries order by id asc";
    $result = mysqli_query($server,$query);
    while ($rows = mysqli_fetch_assoc($result)) {
        $id = $rows['id'];
        $title = $rows['name'];
		$title = preg_replace("/[*0-9+]/","",$title);
		$title = strtr($title, array ('\'' => ' '));
		$value = ltrim($title);
           $return .= '<option '; 
		   if($default == $id || stripos(ltrim($title),$default) !== false) $return .= 'selected ';  
		   $return .= 'value="'.$id.'">'.$title.'</option>';
	}
	return $return;
}

function loadLanguages() {		
	global $server;		
	$return = '';	
	$query="SELECT * FROM language where enabled = 1 order by title asc";
    $result = mysqli_query($server,$query);
    while ($rows = mysqli_fetch_assoc($result)) {
        $alias = ltrim($rows['alias']);
        $title = $rows['title'];
		echo "<a href='index.php?lang=$alias'><strong>$title</strong></a>";
	}
	return $return;
}


function getUserIP() {
	return getenv('REMOTE_ADDR');	
}

function getVisitorCountry() {
	$user_ip = getUserIP2();	
    $details = @json_decode(curl_get_contents("http://ipinfo.io/".$user_ip."/json"),true);
    $city = @$details->city;
    $country = @$details->country;
	if(empty($country)) $country = getSetting('defaultCountry', getUser());
	return $country;	
}
function getUserIP2() {
    if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
            $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($addr[0]);
        } else {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}
function make_request($request_path,$body=null) {
    $base_url = 'https://api.coinbase.com';
	$key = getSetting('apiKey');
	$secret = getSetting('apiSecret');
	$API_VERSION = '2015-08-31';
    $timestamp = time();
    $curl     = curl_init();
    $curlOpts = array();

    if (is_null($body)) {
      $method = 'GET';
      $curlOpts[CURLOPT_HTTPGET] = 1;
      $queryString=null;
    } else  {
      $method = 'POST';
      $queryString = json_encode($body);
      $curlOpts[CURLOPT_POSTFIELDS] = $queryString;
      $curlOpts[CURLOPT_POST]       = 1;
    }

    $headers = array(
        'Content-Type: application/json',
        'CB-VERSION: ' . $API_VERSION,
        'CB-ACCESS-KEY: ' . $key,
        'CB-ACCESS-SIGN: ' . hash_hmac("sha256", $timestamp.$method.$request_path.$queryString, $secret),
        'CB-ACCESS-TIMESTAMP: ' . $timestamp
    );

    $curlOpts[CURLOPT_URL]            = $base_url . $request_path;
    $curlOpts[CURLOPT_HTTPHEADER]     = $headers;
    $curlOpts[CURLOPT_RETURNTRANSFER] = true;
	$curlOpts[CURLOPT_SSL_VERIFYPEER] = false;

    curl_setopt_array($curl, $curlOpts);
	if(curl_error($curl)) {
		return  $response = curl_error($curl);	

	}		
    return $response = curl_exec($curl);
}

//create btc sub account
function createCoinbaseWallet($name) {
	$body = array( "name" => $name );
	$request_path = '/v2/accounts';
	$result = make_request($request_path,$body);
	$response = json_decode($result,true);
	return $response['data']['id'];
}
function getRefererUserID($string) {
	global $server;
	$query="SELECT * FROM users WHERE affiliate_id = '$string'"; 
	$result = mysqli_query($server, $query);  
	$row = mysqli_fetch_assoc($result); 
	$id = $row['id'];
	return $id;
}
function payAffiliate($user_id,$amount,$reference) {
	global $server;
	global $LANG;	
	//get payer
	$result = mysqli_query($server,"SELECT * FROM transactions WHERE transaction_reference = '$reference'"); 
	$row = mysqli_fetch_assoc($result);
	$owner = $row['customer_id'];
	//convert to local value
	$income = round($amount/userExchangeRate($owner),4);
	//get commision
	$commission = getSetting('affiliatePayValue');
	$commType = getSetting('affiliatePayType');
	if($commType!='fixed') {
		$commission = round(($commission/100)*$income,4);
	}
	
	$referrer_id = userData($user_id,'referrer');
	
	$date = date('Y-m-d H:i:s', time());			$user_id = $referrer_id;
	$description = 'Affiliate commission';			$credits = $commission*userExchangeRate($user_id);
	$method = 'system';								$cost = 0;
	$reference = genRandomPassword(6).time();		$gateway_response = 'ok';
	$approved_by = 'System';						$is_earned = '1';
	$status = 'completed';							$validity = '0';
	
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');") or die (mysqli_error($server));	
}

function processTransaction($Transaction_ref) {
	global $server;
	global $LANG;
	$result = mysqli_query($server,"SELECT * FROM transactions WHERE transaction_reference = '$Transaction_ref'"); 
	$row = mysqli_fetch_assoc($result);
	$user_id = $row['customer_id'];
	$amount = $row['credits'];
	$status = $row['status'];
	$Payment_gateway = $row['method'];
	$referrer_id = userData($user_id,'referrer');
	$reseller = userData($user_id,'reseller');
	
	//pay affiliate
	if(strtolower($status != 'completed')) {
		if($referrer_id>0) {
			payAffiliate($user_id,$amount,$Transaction_ref);
		}
			
		mysqli_query($server, "UPDATE `transactions` SET `status` =  'completed' WHERE `transaction_reference` = '$Transaction_ref'");
		mysqli_query($server, "UPDATE `transactions` SET `paid_on` =  '".date('Y-m-d H:i:s')."' WHERE `transaction_reference` = '$Transaction_ref'");	
		
		//send email
		$mail = "Hi ".userData($user_id,'first_name').". <br><p>Your account has been credited with ".number_format($amount).' '.userCurrencyCode($user_id)." SMS credits. You now have a total of ".number_format(userWalletBalance($user_id),3).' '.userCurrencyCode($user_id)." SMS Credits on your balance.</p><p>Details of this transaction is available under the <strong>Transaction Log</strong> menu on your account.</p><p><br><strong>".getSetting('businessName')." Team</strong><hr><small>This is not a marketing email. Please discard if received in error </small></p>";
		$subject = getSetting('businessName',$reseller).' Transaction Notification';
		
		if(!empty(getSetting('orderApproveEmail',$reseller))) {
			$mail = getSetting('orderApproveEmail',$reseller);
			$mail = strtr($mail, array("{name}" => userData($user_id,'first_name'), 
							"{email}" => userData($user_id,'email'),
							"{password}" => '',
							"{company}" => getSetting('businessName',$reseller),
							"{url}" => $link_domain,
							"{phone}" => userData($user_id,'phone'),
							"{amount}" => number_format($amount,3).' '.userCurrencyCode($user_id),
							"{balance}" => number_format(userWalletBalance($user_id),3).' '.userCurrencyCode($user_id)
							));	
			$subject = 	getSetting('orderApproveEmailSubject',$reseller);				
			$subject = strtr($subject, array("{name}" => userData($user_id,'first_name'), 
							"{email}" => userData($user_id,'email'),
							"{password}" => '',
							"{company}" => getSetting('businessName',$reseller),
							"{url}" => $link_domain,
							"{phone}" => userData($user_id,'phone'),
							"{amount}" => number_format($amount,3).' '.userCurrencyCode($user_id),
							"{balance}" => number_format(userWalletBalance($user_id),3).' '.userCurrencyCode($user_id)
							));	
		}
		sendEmail(getSetting('smtpUsername',$reseller),getSetting('businessName',$reseller),$subject,userData($user_id,'email'),$mail);
		//create hook variables
		$vars = array(
					 "reference"=>$Transaction_ref, 
					 "credits"=>$amount,
					 "amount"=>$row['cost'], 
					 "customer_id"=>$user_id,
					 "method"=>$Payment_gateway, 
					 "description"=>$row['description']
					 );
		$_SESSION['EventVals'] = $vars;
		
		$Payment_gateway_name = paymentMethod($Payment_gateway);
		logEvent($user_id,'Completed transaction: '.$Transaction_ref.' via '.$Payment_gateway_name);		
		createNotice($user_id,"Hi. You have just added ".number_format($amount,3).' '.userCurrencyCode($user_id)." credits to your account");
		sendTransactionSMS($user_id,number_format($amount,3));
	}
	global $hooks; $hooks->do_action('OrderComplete');
	return true;
}

//Validate BTC Address
function validate($address){
        $decoded = decodeBase58($address);
 
        $d1 = hash("sha256", substr($decoded,0,21), true);
        $d2 = hash("sha256", $d1, true);
 
        if(substr_compare($decoded, $d2, 21, 4)){
                throw new \Exception("bad digest");
        }
        return true;
}
function decodeBase58($input) {
        $alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
 
        $out = array_fill(0, 25, 0);
        for($i=0;$i<strlen($input);$i++){
                if(($p=strpos($alphabet, $input[$i]))===false){
                        throw new \Exception("invalid character found");
                }
                $c = $p;
                for ($j = 25; $j--; ) {
                        $c += (int)(58 * $out[$j]);
                        $out[$j] = (int)($c % 256);
                        $c /= 256;
                        $c = (int)$c;
                }
                if($c != 0){
                    throw new \Exception("address too long");
                }
        }
 
        $result = "";
        foreach($out as $val){
                $result .= chr($val);
        }
 
        return $result;
}

function minOrder($userID) {
	if(userData($userID,'min_order') > 0) {
		$return = userData($userID,'min_order');
	} else {
		$return = getSetting('minCreditOrder');	
	}
	if($return > 0) return $return;
	return '0'; 
}

function toUserCurrency($amount,$from_user,$to_user) {
	$income = round($amount/userExchangeRate($from_user),4); //value in system default currency
	$out = round($income*userExchangeRate($to_user),4);	
	return $out;
}

function customCreditCost($volum,$customer) {
	global $server;	
	$query="SELECT `cost` as value FROM dynamic_credit_cost WHERE min_order >= '$volum' AND max_order <= '$volum' AND customer_id = '$customer'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$num = mysqli_num_rows($result);
	if($num < 1) return '0';
	$row = mysqli_fetch_assoc($result); 
	return $row['value']*userExchangeRate($customer);
}

function getUserTax($user,$amount) {
	$return = 0;
	if( (getSetting('taxAmount')>0) && userData($user,'no_tax') < 1) {
		$tax = getSetting('taxAmount')/100;
		$tax = $tax*$amount;
		$return = $tax;
	}
	return $return;
}

function countRoute($user=0) {
  	global $server;	
	$query="SELECT count(id) as value FROM routes WHERE 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}
function countPayGates($user=0) {
  	global $server;	
	$query="SELECT count(id) as value FROM paymentgateways WHERE customer_id = '$user'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}
function countSMSGates($user=0) {
  	global $server;	
	$query="SELECT count(id) as value FROM sms_gateways WHERE 1"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function getUserVat($user,$amount) {
	$return = 0;
	if( (getSetting('vatAmount')>0) && userData($user,'no_tax') < 1) {
		$vat = getSetting('vatAmount')/100;
		$vat = $vat*$amount;
		$return = $vat;
	}
	return $return;
}

function paymentMethod($gateway) {
	$name = paymentGatewayData($gateway,'title');
	if(!is_numeric($gateway)) $name = ucfirst($gateway);
	return $name;
}

function gatewayCharge($user,$gateway,$amount) {
	$fixed = paymentGatewayData($gateway,'charges_fix')*userExchangeRate($user);
	$perc = paymentGatewayData($gateway,'charges_perc');
	$perc = $perc/100;
	$perc = $perc*$amount;
	$return = round($fixed+$perc,3);
	return $return;
}
function getCreditCost($volum=0,$user=0) {
	global $resellerID;
	global $server;	
	if(customCreditCost($volum,getUser())> 0) {
		return customCreditCost($volum,getUser());	
	}
	if($volum == 0) {	
		$query="SELECT `cost` as value FROM dynamic_credit_cost WHERE min_order = 0 AND max_order = 0 AND reseller_id = '$resellerID'"; 
		$result = mysqli_query($server,$query) or die(mysqli_error($server));  
		$row = mysqli_fetch_assoc($result); 
		return $row['value']*userExchangeRate(getUser());
	} else {
		$query="SELECT `cost` as value FROM dynamic_credit_cost WHERE min_order >= '$volum' AND max_order <= '$volum' AND reseller_id = '$resellerID'"; 
		$result = mysqli_query($server,$query) or die(mysqli_error($server));  
		$num = mysqli_num_rows($result);
		if($num<1) {
			$query="SELECT `cost` as value FROM dynamic_credit_cost WHERE min_order = 0 AND max_order = 0 AND reseller_id = '$resellerID'"; 
			$result = mysqli_query($server,$query) or die(mysqli_error($server));  
			$row = mysqli_fetch_assoc($result); 
			return $row['value']*userExchangeRate(getUser());
		}
		$row = mysqli_fetch_assoc($result); 
		return $row['value']*userExchangeRate(getUser());
	}
}

function countAllSMS($from,$to) {
  	global $server;	
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	$query="SELECT count(id) as value FROM messagedetails WHERE $users (`datetime` BETWEEN '$from' AND '$to')"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}
function countSMSRecipients($id) {
  	global $server;	
	$query="SELECT count(id) as value FROM messagedetails WHERE message_id = '$id'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}
function countSentRecipients($id) {
  	global $server;	
	$query="SELECT count(id) as value FROM messagedetails WHERE message_id = '$id' AND status != 'queued'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function countAllCustomerSMS($from,$to,$customer) {
  	global $server;	
	$users = " customer_id = '".$customer."' AND ";
	$query="SELECT count(id) as value FROM messagedetails WHERE $users (`datetime` BETWEEN '$from' AND '$to')"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function countSentSMS($from,$to) {
  	global $server;	
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	$query="SELECT count(id) as value FROM messagedetails WHERE $users (`datetime` BETWEEN '$from' AND '$to') AND `status` LIKE 'sent'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function countPendingSMS($from,$to) {
  	global $server;	
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	$query="SELECT count(id) as value FROM messagedetails WHERE $users (`datetime` BETWEEN '$from' AND '$to') AND `status` LIKE 'queued'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}
function countFailedSMS($from,$to) {
  	global $server;	
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	$query="SELECT count(id) as value FROM messagedetails WHERE $users (`datetime` BETWEEN '$from' AND '$to') AND `status` NOT LIKE 'sent'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}
function countSMS($from,$to,$type='',$status='',$message_id='') {
  	global $server;	
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	$mess = '';
	if($message_id>0) { $mess = " message_id = '$message_id' AND "; $users = ''; }
	$query="SELECT count(id) as value FROM messagedetails WHERE $mess $users (`datetime` BETWEEN '$from' AND '$to') AND `type` LIKE '%$type%' AND `status` LIKE '$status'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function countSMSByCountry($country,$from,$to,$type='',$status='',$message_id='') {
  	global $server;	
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	$mess = '';
	if($message_id>0) { $mess = " message_id = '$message_id' AND "; $users = '';}
	$query="SELECT count(id) as value FROM messagedetails WHERE $mess $users country_id = '$country' AND (`datetime` BETWEEN '$from' AND '$to') AND `type` LIKE '%$type%' AND `status` LIKE '%$status%'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}
function countDateSMS($from,$type='',$status) {
  	global $server;	
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	$query="SELECT count(id) as value FROM messagedetails WHERE $users (`datetime` LIKE '%$from%') AND `type` LIKE '%$type%' AND `status` LIKE '$status'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function countDateSMSByCountry($country,$from,$type='',$status='') {
  	global $server;	
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	$query="SELECT count(id) as value FROM messagedetails WHERE $users country_id = '$country' AND (`datetime` LIKE '%$from%') AND `type` LIKE '%$type%' AND `status` LIKE '%$status%'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	return $row['value'];	
}

function countryChatData($days) {
	global $server;	
	$ticks = '[';
	$data = '[';
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	if($days<1) {
		$from='1970-01-01 00:00:00';
		$to=date('Y-m-d').' 23:59:59';
		$query="SELECT * FROM messagedetails WHERE $users (`datetime` BETWEEN '$from' AND '$to') GROUP BY country_id";
		$result = mysqli_query($server,$query) or die(mysqli_error($server));
		$x = 0;
		while ($rows = mysqli_fetch_assoc($result)) {	
			$id = $rows['country_id'];
			$ticks .= '['.$x.',\''.countryName($id).'\'], ';
			$data .= '['.$x.','.countSMSByCountry($id,$from,$to,'','').'], ';
			$x++;
		}
	} else {
		
	}
	$ticks .= ']';
	$data .= ']';
		
	$return = 'var ticks = '.$ticks.';';
  	$return .= 'var data = '.$data.';';	
	return $return;
}

function countryChatData2($days) {
	global $server;	
	$ticks = '';
	$data = '';
	$data2 = '';
	$users = " customer_id = '".getUser()."' AND ";
	if(isAdmin(getUser())) $users = '';
	if($days<1) {
		$from='1970-01-01 00:00:00';
		$to=date('Y-m-d').' 23:59:59';
		$query="SELECT * FROM messagedetails WHERE $users (`datetime` BETWEEN '$from' AND '$to') GROUP BY country_id";
		$result = mysqli_query($server,$query) or die(mysqli_error($server));
		$x = 0;
		while ($rows = mysqli_fetch_assoc($result)) {	
			$id = $rows['country_id'];
			$ticks .= '"'.countryName($id).'", ';
			$data .= countSMSByCountry($id,$from,$to,'','sent').', ';
			$data2 .= countSMSByCountry($id,$from,$to,'','failed').', ';
			$x++;
		}
	} else {
		
	}
		
	$return = 'labels: ['.$ticks.'],';
  	$return .= 'datasets: [
							{
								label: "Sent",
								fillColor: "#2e7d32",
								strokeColor: "transparent",
								highlightFill: "#003300",
								highlightStroke: "#B3B3B3",
								data: ['.$data.']
							},
							{
								label: "Failed",
								fillColor: "#b71c1c",
								strokeColor: "transparent",
								highlightFill: "#FF3300",
								highlightStroke: "#B3B3B3",
								data: ['.$data2.']
							}
						]';	
	return $return;
}

function smsChatData($days) {
	global $LANG;
	$ticks = '';
	$data = '';
	$data2 = '';
	if($days<2) {
		for ($x=1;$x<25;$x++) {
			$from=date('Y-m-d').' '.sprintf("%02d", $x).':00:00';
			$to=date('Y-m-d').' '.sprintf("%02d", $x).':59:59';
			$data .= " {x: '".$x.':00'."', Sent: ".countSMS($from,$to,'','sent').", Failed: ".countSMS($from,$to,'','failed')."},";
		}
	} else {
		$today = date('Y-m-d'); 
		if($days==7) {
			for ($x=7;$x>0;$x--) {
				$time = strtotime($today.'-'.$x.' days');
				$from=date('Y-m-d',$time);
				$data .= " {x: '".$from."', Sent: ".countDateSMS($from,'','sent').", Failed: ".countDateSMS($from,'','failed')."},";
			}
			$data .= " {x: '".$today."', Sent: ".countDateSMS($today,'','sent').", Failed: ".countDateSMS($today,'','failed')."},";
		} else if($days==30) {
			for ($x=30;$x>0;$x--) {
				$time = strtotime($today.'-'.$x.' days');
				$from=date('Y-m-d',$time);
				$data .= " {x: '".$from."', Sent: ".countDateSMS($from,'','sent').", Failed: ".countDateSMS($from,'','failed')."},";
			}
			$data .= " {x: '".$today."', Sent: ".countDateSMS($today,'','sent').", Failed: ".countDateSMS($today,'','failed')."},";
		} else if($days==31) {
			for ($x=date('j');$x>0;$x--) {
				$time = strtotime($today.'-'.$x.' days');
				$from=date('Y-m-d',$time);
				$data .= " {x: '".$from."', Sent: ".countDateSMS($from,'','sent').", Failed: ".countDateSMS($from,'','failed')."},";
			}
			$data .= " {x: '".$today."', Sent: ".countDateSMS($today,'','sent').", Failed: ".countDateSMS($today,'','failed')."},";
		} else if($days==3) {
			for ($x=90;$x>0;$x--) {
				$time = strtotime($today.'-'.$x.' days');
				$from=date('Y-m-d',$time);
				$data .= " {x: '".$from."', Sent: ".countDateSMS($from,'','sent').", Failed: ".countDateSMS($from,'','failed')."},";
			}
			$data .= " {x: '".$today."', Sent: ".countDateSMS($today,'','sent').", Failed: ".countDateSMS($today,'','failed')."},";
		} else if($days==6) {
			for ($x=180;$x>0;$x--) {
				$time = strtotime($today.'-'.$x.' days');
				$from=date('Y-m-d',$time);
				$data .= " {x: '".$from."', Sent: ".countDateSMS($from,'','sent').", Failed: ".countDateSMS($from,'','failed')."},";
			}
			$data .= " {x: '".$today."', Sent: ".countDateSMS($today,'','sent').", Failed: ".countDateSMS($today,'','failed')."},";
		} else if($days==12) {
			$data .= " {x: 'January', Sent: ".countDateSMS(date('Y').'-01','','sent').", Failed: ".countDateSMS(date('Y').'-01','','failed')."},";
			$data .= " {x: 'February', Sent: ".countDateSMS(date('Y').'-02','','sent').", Failed: ".countDateSMS(date('Y').'-02','','failed')."},";
			$data .= " {x: 'March', Sent: ".countDateSMS(date('Y').'-03','','sent').", Failed: ".countDateSMS(date('Y').'-03','','failed')."},";
			$data .= " {x: 'April', Sent: ".countDateSMS(date('Y').'-04','','sent').", Failed: ".countDateSMS(date('Y').'-04','','failed')."},";
			$data .= " {x: 'May', Sent: ".countDateSMS(date('Y').'-05','','sent').", Failed: ".countDateSMS(date('Y').'-05','','failed')."},";
			$data .= " {x: 'June', Sent: ".countDateSMS(date('Y').'-06','','sent').", Failed: ".countDateSMS(date('Y').'-06','','failed')."},";
			$data .= " {x: 'July', Sent: ".countDateSMS(date('Y').'-07','','sent').", Failed: ".countDateSMS(date('Y').'-07','','failed')."},";
			$data .= " {x: 'August', Sent: ".countDateSMS(date('Y').'-08','','sent').", Failed: ".countDateSMS(date('Y').'-08','','failed')."},";
			$data .= " {x: 'September', Sent: ".countDateSMS(date('Y').'-09','','sent').", Failed: ".countDateSMS(date('Y').'-09','','failed')."},";
			$data .= " {x: 'October', Sent: ".countDateSMS(date('Y').'-10','','sent').", Failed: ".countDateSMS(date('Y').'-10','','failed')."},";
			$data .= " {x: 'November', Sent: ".countDateSMS(date('Y').'-11','','sent').", Failed: ".countDateSMS(date('Y').'-11','','failed')."},";
			$data .= " {x: 'December', Sent: ".countDateSMS(date('Y').'-12','','sent').", Failed: ".countDateSMS(date('Y').'-12','','failed')."},";
		}
	}
		
	$return = $data;
	return $return;
}

function smsChatData2($days) {
	$ticks = '[';
	$data = '[';
	$data2 = '[';
	if($days<2) {
		for ($x=1;$x<25;$x++) {
			$from=date('Y-m-d').' '.sprintf("%02d", $x).':00:00';
			$to=date('Y-m-d').' '.sprintf("%02d", $x).':59:59';
			$ticks .= '['.($x-1).',\''.$x.':00'.'\'], ';
			$data .= '['.($x-1).','.countSMS($from,$to,'','sent').'], ';
			$data2 .= '['.($x-1).','.countSMS($from,$to,'','failed').'], ';
		}
	} else {
		$today = date('Y-m-d'); 
		if($days==7) {
			for ($x=7;$x>0;$x--) {
				$time = strtotime($today.'-'.$x.' days');
				$from=date('Y-m-d',$time);
				$ticks .= '['.$x.',\''.$from.'\'], ';
				$data .= '['.$x.','.countDateSMS($from,'','sent').'], ';
				$data2 .= '['.$x.','.countDateSMS($from,'','failed').'], ';
			}
			$ticks .= '[0,\''.$today.'\'], ';
			$data .= '[0,'.countDateSMS($today,'','sent').'], ';
			$data2 .= '[0,'.countDateSMS($today,'','failed').'], ';
		} else if($days==30) {
			
		} else if($days==31) {
			
		} else if($days==3) {
			
		} else if($days==6) {
			
		} else if($days==12) {
			
		}
	}
	$ticks .= ']';
	$data .= ']';
	$data2 .= ']';
		
	$return = 'var ticks = '.$ticks.';';
  	$return .= 'var data = '.$data.';'; //send	
	$return .= 'var data2 = '.$data2.';'; //failed    
	return $return;
}
//show message 
function showMessage($message,$color) {
	$added = '';
	if(!empty($message))
	echo ' <div class="col s12 m12 l12">
                            <div class="card '.$color.' lighten-5">
                                <div class="card-content">
                                     '.$message.'
                                </div>
                            </div>
                        </div>';
}

function exportToCSV($name,$table,$fields,$extra='') {
	global $server;
	$name .= date('Y_m_d_h_i_s');
    $sql = "SELECT $fields FROM `$table` ".$extra;
	$result = $server->query($sql);
	if (!$result) die('Couldn\'t fetch records');
	$num_fields = mysqli_num_fields($result);
	$headers = array();
	foreach(explode(',',$fields) as $heds)  {
		$headers[] = ucfirst($heds);
	}
	$fp = fopen('php://output', 'w');
	if ($fp && $result) {
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename="'.$name.'.csv"');
		header('Pragma: no-cache');
		header('Expires: 0');
		fputcsv($fp, $headers);
		while ($row = $result->fetch_array(MYSQLI_NUM)) {
			fputcsv($fp, array_values($row));
		}
		die;
	}
} 

//Show verification popup
function showVerify() {
	global $server;
	global $LANG;
	$userID = getUser();
	//resend verification link
	$query="SELECT * FROM users WHERE id = '$userID'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$track = $row['email_verified'];
	$track2 = $row['phone_verified'];
	if($track != 0) {
	$mail = "<h2 align='center'>Verify your email address</h2>";
	$mail .= "<hr>";
	$mail .= "<p align='center'>In order to start using your ".getSetting('businessName')." account, you need to confirm your email address.</p>";
	$mail .= '<p align="center"><a href="'.home_base_url().'?vf='.$track.'"><button style="margin: 5px auto; border: 0; color: white; padding: 10px; background: #c99419" >Very Email Address</button></a></p>';
	$mail .= "<hr><p align='center'>If you did not sign up for this account, you can ignore this email and the account will be deleted.</p>";
	$sender = getSetting('businessName');
	$subject = "Please Verify Your Email Address";
	$from = getSetting('smtpUsername');
	sendEmail($from,$sender,$subject,$row['email'],$mail);
	//show full scrteen notice
?>
            <div style="overflow-x: hidden; width: 99.99%; height: 99.99%; z-index: 1000; position: fixed; top: 0; left: 0; background: rgba(0,0,0,0.7);">
        	 <div class="row"><br><br>
                
                 <div class="row no-m-t no-m-b">
                    <div class="col s12 m12 l12">
                        <div class="card deep-orange darken-3">
                            <div class="card-content white-text">
							<?=$LANG['verify_email_warning'].'<br><p><br>
				<a href="" onclick="alert(\''.$LANG['We have just sent a new link to you'].'\')" class="btn green">'.$LANG['Resend Verification Link'].'</a> <a href="index.php?logout" class="btn btn-default">'.$LANG['Sign Out'].'</a></p>'?>
                            </div>
                        </div>
                    </div>
                 </div>
				
             </div>
          </div>          
<?php
	} else {
		if($track2 != 0) {
			sendPhoneVerify($userID,$track2);	
			?>
            <div style="overflow-x: hidden; width: 99.99%; height: 99.99%; z-index: 1000; position: fixed; top: 0; left: 0; background: rgba(0,0,0,0.7);">
        	 <div class="row"><br><br>
                
                 <div class="row no-m-t no-m-b">
                    <div class="col s12 m12 l12">
                        <div class="card deep-orange darken-3">
                            <div class="card-content white-text">
							<?=$LANG['verify_phone_warning'].'<br><p><br>
				<a href="" onclick="alert(\''.$LANG['We have just sent a new code to you'].'\')" class="btn green">'.$LANG['Resend Code'].'</a> <a href="index.php?logout" class="btn btn-default">'.$LANG['Sign Out'].'</a></p>'?>
                			
                            </div>
                        </div>
                    </div>
                 </div>
                 
                 <div class="row no-m-t no-m-b">
                    <div class="col s1 m2 l3"></div>
                    <div class="col s10 m8 l6">
                        <div class="card white">
                            <div class="card-content black-text">
                            	<form action="" onSubmit="return false;" method="post" id="verify">
                                <div class="row no-m-t no-m-b">
                                 <div class="input-field col s12">
                                   <input id="code" type="number" class="validate" required >
                                   <label for="code"><?=$LANG['Verification Code']?></label>
                                 </div>
                                </div>
                                <div class="row no-m-t no-m-b">
                                <button id="verP-button" class="btn ight-blue darken-4" type="submit"><i class="fa fa-check"></i> <?=$LANG['Verify']?> </button>
                                <span id="verP-spin" class="btn-flat" style="display: none;"><i class="fa fa-spinner fa-spin"></i> <strong><?=$LANG['Please wait']?>...</strong></span>
                          		</div>
                                </form>
                            </div>
                         </div>
                    </div>
                    <div class="col s1 m2 l3"></div>
                 </div>           
				
             </div>
          </div>          
		<?php		
		}
	}
}

?>
