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

if (!function_exists('_obenc'))
{
	function _obenc($inp="", $keyLen=8)
	{
		$key = str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
		$key = substr($key, 0, $keyLen);
		$ret = $key . base64_encode(xor_string($inp, $key));
		
		return str_replace('=', '' ,$ret);
	}
}
if (!function_exists('_obdec'))
{
	function _obdec($inp="", $keyLen=8)
	{
		$key = substr($inp, 0, $keyLen);
		$inp = substr($inp, $keyLen);
		$ret = xor_string(@base64_decode($inp), $key);
		return $ret;
	}
}
if (!function_exists('xor_string'))
{
	function xor_string($string='', $key='')
	{
		for($i = 0; $i < strlen($string); $i++)
		{
			$string[$i] = ($string[$i] ^ $key[$i % strlen($key)]);
		}

		return $string;
	}
}

if (!function_exists('_obencnum'))
{
	function _obencnum($input="")
	{
		$rand = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 10);
		// $input = 6474;
		$output = $rand;
		// $input .= substr(crc32($input), 0, 1);
		for ($i=0; $i<strlen($input); $i++)
		{
			$output .= $rand[substr($input, $i, 1)];
		}

		$output .= $rand[substr(crc32($output), 0, 1)];

		return $output;
	}
}
if (!function_exists('_obdecnum'))
{
	function _obdecnum($input="")
	{
		$rand = substr($input, 0, 10);
		$crc = strpos($rand, substr($input, -1));
		$input = substr($input, 10, -1);

		if (substr(crc32($rand . $input), 0, 1) == $crc)
		{
			$output = "";
			for ($i=0; $i<strlen($input); $i++)
			{
				$output .= strpos($rand, $input[$i]);
			}

			return $output;
		}

		return false;
	}
}

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

if (!function_exists('sal_mod_active'))
{
	function sal_mod_active($mod='')
	{
		$salmodule = get_company('salModCodes');
		$salmodule = explode(',', !empty($salmodule) ? $salmodule : "");
		if (in_array($mod,$salmodule)) {
			return true;
		}
		return false;
	}
}

if (!function_exists('set_user_data'))
{
	function set_user_data($val='')
	{
		$CI = & get_instance();

		if (get_company()) {
			if (!empty($val['conId'])) {
				// set contact tags in session
				$con_tags =  $CI->db->select('tagId')->from('contacts_tags')->where(array('cId' => get_company('id'), 'conId' => $val['conId'],'tagId !=' => 0))->get()->result_array();
				$val['tags'] = array();
				foreach ($con_tags as $row) {
					$val['tags'][] = $row['tagId'];
				}			
			}
			
			// check branch modle enabled
			if (sal_mod_active(BRANCH_MOD))
			{
				$usr_loc = $CI->db->select('locid')->from('compusers_location')->where(array('cId' => get_company('id'),'uId' => $val['id']))->get()->result_array();
				$val['locs'] = array();
				foreach ($usr_loc as $row) {
					$val['locs'][] = $row['locid'];
				}
			}

			if (!empty($val['roleId']))
			{
				$where = array('roleId'=>$val['roleId']);
				$CI->db->select('modCode,actionRights')->from('role_permissions');
				$CI->db->where($where);
				$CI->db->group_start();
				$CI->db->where('cId', get_company('id'));
				$CI->db->or_where('cId', 0);
				$CI->db->group_end();
				$CI->db->order_by('cId','desc');
				$val['rights'] = array_key_index($CI->db->get()->result_array(),'modCode');
			}
		}

		$CI->session->set_userdata('user', $val);
	}
}

if (!function_exists('get_user_data'))
{
	function get_user_data($key='', $strict=false)
	{
		$CI = & get_instance();

		// $userData = $CI->session->get_userdata('user');
		$userData = $CI->session->userdata('user');

		if (!$userData)
		{
			return null;
		}

		if (empty($userData['defaultbId']))
		{
			//if defaultbId is empty set company mainbId 
			$userData['defaultbId'] = get_company('mainbId');
		}

		// if (!$userData)
		// {
		// 	if (defined('OBO_JOBS') && $key=='defaultbId') {
		// 		return get_company('mainbId');
		// 	}
		// 	return null;
		// }
		if (isset($userData[$key]))
		{
			return $userData[$key];
		}
		else if($strict)
		{
			return null;
		}

		return $userData;
	}
}
if (!function_exists('isTrial'))
{
	function isTrial()
	{
		$licData = get_user_data("licenseData", true);
		return (!empty($licData) && !empty($licData["isTrial"])) ? true : false;
	}
}
if (!function_exists('isFree'))
{
	function isFree()
	{
		$licData = get_user_data("licenseData", true);
		return (!empty($licData) && !empty($licData["isFree"])) ? true : false;
	}
}
if (!function_exists('isPro'))
{
	function isPro()
	{
		$licData = get_user_data("licenseData", true);
		return (!empty($licData) && !empty($licData["isPro"])) ? true : false;
	}
}
if (!function_exists('isExpired'))
{
	function isExpired()
	{
		$licData = get_user_data("licenseData", true);
		return (!defined("APP_EXP") && !empty($licData) && !empty($licData["isExpired"])) ? true : false;
	}
}
if (!function_exists('getExpireDue'))
{
	function getExpireDue($expiredOn=null)
	{
		if (!$expiredOn)
		{
			$licData = get_user_data("licenseData", true);
			if (!empty($licData) && !empty($licData["expiredOn"]))
			{
				$expiredOn = $licData["expiredOn"];
			}
			else
			{
				return false;
			}
		}

		$ts = strtotime(date("Y-m-d", time()) . "00:00:00");
		$daysLeft = ($expiredOn - $ts) / (60*60*24);

		return $daysLeft;
	}
}
if (!function_exists('canSave'))
{
	function canSave()
	{
		$licData = get_user_data("licenseData", true);
		if (defined("APP_EXP") || (defined('IS_DEMO')) || ($licData && !empty($licData['plan']) && $licData['plan']!='T'))
		{
			return true;
		}

		$expiredOn = getExpireDue();
		if ($expiredOn === false)
		{
			return true;
		}

		// Grace period for expired users.
		if($expiredOn < -2) {
			return false;
			header('Content-type: application/json');
			http_response_code(402);
			echo json_encode(array(0, 'License expired kindly contact OutputBooks Support support@srimax.com Thank you !!!', array()));
			exit();
		} 
		return true;
	}
}

if (!function_exists('set_company'))
{
	function set_company($key="", $val="")
	{
		$CI = & get_instance();

		if (is_array($key))
		{
			if (!empty($key["salSettings"]))
			{
				$key = array_merge($key, $key["salSettings"]);
			}

			$CI->session->set_userdata('company', $key);
		}
		else if ($key && $val)
		{
			$company = get_company();
			$company[$key] = $val;
			$CI->session->set_userdata('company', $company);
		}
	}
}

if (!function_exists('get_company'))
{
	function get_company($key='', $defVal=null)
	{
		$CI = & get_instance();

		$companyData = $CI->session->userdata('company');

		if (!$companyData)
		{
			return null;
		}

		if ($key && !is_array($key))
		{
			return isset($companyData[$key]) ? $companyData[$key] : $defVal;
		} else if (is_array($key)) {
			$result = array();
			foreach($key as $val) {
				$result[$val] = isset($companyData[$val]) ? $companyData[$val] : $defVal;
			}
			return $result;
		}

		return $companyData;
	}
}

if (!function_exists('array_key_index'))
{
	// If key is not empty then the returned array is indexed by the value.
	function array_key_index($data, $key = '', $duplicate = false)
	{
		if (!$data || $key=='')
		{
			return $data;
		}
		$array	= array();
		foreach ($data as $val)
		{
			if ($duplicate)
			{
				$array[$val[$key]][] = $val;
			}
			else
			{
				$array[$val[$key]] = $val;
			}
		}
		return $array;
	}
}

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

if (!function_exists('print_E'))
{
	function print_E($inp='')
	{
		echo '<pre style="white-space:pre-wrap;">';
		print_R($inp);
		echo '</pre>';
	}
}
//----------------------------------------------------

if (!function_exists('isCloud'))
{
	function isCloud()
	{
		return defined("APP_EXP") || defined("APP_CLD");
	}
}

if (!function_exists('isLogedin'))
{
	function isLogedin()
	{
		$CI = & get_instance();
		return $CI->session->userdata('is_logged_in');
	}
}

if (!function_exists('ob_gencert'))
{
	function ob_gencert($compName="", $email="info@srimax.com", $city="Sivakasi", $state="TamilNadu", $country="IN", $keyName="client")
	{
		$dn = array(
			"countryName" => $country,
			"stateOrProvinceName" => $state,
			"localityName" => $city,
			"organizationName" => $compName,
			"organizationalUnitName" => "Accounts",
			"commonName" => "outputbooks.com",
			"emailAddress" => $email
		);

		// Generate a new private (and public) key pair
		$privkey = openssl_pkey_new(array(
			"digest_alg" => "sha256",
			"private_key_bits" => 2048,
			"private_key_type" => OPENSSL_KEYTYPE_RSA
		));

		if (!$privkey)
		{
			return false;
		}

		// Generate a certificate signing request
		$csr = openssl_csr_new($dn, $privkey, array(
			"digest_alg" => "sha256"
		));

		if (!$csr)
		{
			return false;
		}

		// Generate a self-signed cert, valid for 365 days
		$x509 = openssl_csr_sign($csr, null, $privkey, $days=365, array(
			"digest_alg" => "sha256"
		));

		if (empty($keyName))
		{
			$keyName = "client";
		}

		// Save your private key, CSR and self-signed cert for later use
		openssl_csr_export($csr, $csrout);
		file_put_contents($keyName . ".csr", $csrout);

		openssl_x509_export($x509, $certout);
		file_put_contents($keyName . ".crt", $certout);

		$ssl_password = "SrimaxOutputTunnel2018";
		openssl_pkey_export($privkey, $pkeyout, $password);
		file_put_contents($keyName . ".key", $pkeyout);

		// Show any errors that occurred here
		while (($e = openssl_error_string()) !== false)
		{
			echo $e . "<br>";
		}

		return true;
	}
}
if (!function_exists('justify'))
{
	function justify($str, $justify='L', $desired_length=0)
	{
		$CI = & get_instance();
		$max_length = $CI->config->item('print_char_length');
		
		$desired_length = floor($desired_length && ($desired_length<$max_length)?$desired_length:$max_length);
		$length = strlen( $str );
		// $desired_length--;
		$str = substr($str,0,$desired_length);
		// if($length>$desired_length) {
		// 	if (!$wrap) {
		// 		$str = substr($str,0,$desired_length);
		// 	} else {
		// 		// print_r(explode( "\n", wordwrap( $str, $desired_length )));exit;
		// 		$str_in = explode( "\n", wordwrap( $str, $desired_length )  );
		// 		foreach ($str_in as $str) {
		// 			return justify($str, $justify, $desired_length,false).nl();
		// 		}
		// 		return false;
		// 	}
		// }
		switch ($justify) {
			case 'R':
				$str = str_pad($str, $desired_length, " ",STR_PAD_LEFT);
			break;
			case 'C':
				$str = str_pad($str, $desired_length, " ", STR_PAD_BOTH);
			break;
		}
		// $desired_length++;
		$str = str_pad($str, $desired_length, " ");
		return $str;
	}
}

if (!function_exists('nl'))
{
	function nl($str='')
	{
		$CI = & get_instance();
		$max_length = $CI->config->item('print_char_length');
		if ($str)
		{
			$str = PHP_EOL . str_pad('', $max_length, $str);
		}
		return $str . PHP_EOL;
	}
}

if (!function_exists('drawline'))
{
	function drawline($str='')
	{
		if ($str)
		{
			$CI = & get_instance();
			$max_length = $CI->config->item('print_char_length');
			return str_pad('', $max_length, $str);
		}
		return "";
	}
}

if (!function_exists('dot_print'))
{
	function dot_print ($str, $justify='L', $desired_length=0)
	{
		$CI = & get_instance();
		$max_length = $CI->config->item('print_char_length');

		$value = wordwrap(strip_tags($str), $max_length, PHP_EOL);
		$value = explode(PHP_EOL, $value);
		$n = count($value);
		$str = '';
		for ($i=0;$i<$n;$i++)
		{
			switch ($justify)
			{
				case 'R':
					$str .= str_pad($value[$i], $desired_length, " ",STR_PAD_LEFT);
				break;
				case 'C':
					$str .= str_pad($value[$i], $desired_length, " ", STR_PAD_BOTH);
				break;
				default:
					$str .= str_pad($value[$i], $desired_length," ");
				break;
			}
			if ($n>1)
			{
				$str .=PHP_EOL;
			}
		}

		return $str;
	}
}

if (!function_exists('get_timezone_date')) {
	function get_timezone_date($date_format='Y-m-d H:i:s',$user_zone='UP55') {
		$CI = & get_instance();
		$CI->load->helper('date');
		$timestamp = strtotime(gmdate('Y-m-d H:i:s'));		
		$local_timestamp = gmt_to_local($timestamp, $user_zone);
		return date($date_format,$local_timestamp);
	}
}

/*if (!function_exists('get_user_agent')) {
	function get_user_agent() {
		$result['details'] = $u_agent = $_SERVER['HTTP_USER_AGENT'];
		
		 // Get real visitor IP behind CloudFlare network
		 if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
			$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
			$_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
		}
		$client  = @$_SERVER['HTTP_CLIENT_IP'];
		$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
		$remote  = $_SERVER['REMOTE_ADDR'];

		if(filter_var($client, FILTER_VALIDATE_IP))
		{
			$uip = $client;
		}
		elseif(filter_var($forward, FILTER_VALIDATE_IP))
		{
			$uip = $forward;
		}
		else
		{
			$uip = $remote;
		}
		$result['deviceIP'] = $uip;

		$ub = '';
		if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
		{
			$bname = 'Internet Explorer';
			$ub = "MSIE";
		}
		elseif(preg_match('/Firefox/i',$u_agent))
		{
			$bname = 'Mozilla Firefox';
			$ub = "Firefox";
		}
		elseif(preg_match('/Chrome/i',$u_agent))
		{
			$bname = 'Google Chrome';
			$ub = "Chrome";
		}
		elseif(preg_match('/Safari/i',$u_agent))
		{
			$bname = 'Apple Safari';
			$ub = "Safari";
		}
		elseif(preg_match('/Opera/i',$u_agent))
		{
			$bname = 'Opera';
			$ub = "Opera";
		}
		elseif(preg_match('/Netscape/i',$u_agent))
		{
			$bname = 'Netscape';
			$ub = "Netscape";
		}
		$result['clientName'] = $ub;
		return $result;
	}
}*/

if (!function_exists('access_log')) {
	function access_log() {
		$CI = & get_instance();
		$u_agent = get_user_agent();
		$CI->db->select('*')->from('useraccess');
		$CI->db->where(array('uId'=>get_user_data('id'),'cId' => get_company('id'),'userIp' => $u_agent['deviceIP']));
		$row = $CI->db->get()->row_array();
		
		if ($row) {
			// $userIP = ($row['userIP'])?explode(',',$row['userIP']):array();
			// if (!in_array($uip,$userIP)) {
			// 	$userIP[] = $uip;
			// }
			// $CI->db->where('id', $row['id']);					
			// $CI->db->update('useraccess', array('userIP' => implode(',',$userIP), 'accCnt '=> ++$row['accCnt']));			
			$CI->db->where('id', $row['id']);					
			$CI->db->update('useraccess', array('accCnt '=> ++$row['accCnt']));
		} else {
			$CI->db->insert('useraccess',array('userIP' => $u_agent['deviceIP'], 'uId' => get_user_data('id'),'cId' => get_company('id'),'accCnt'=>1, 'deviceId' => get_user_data('deviceId',true)));
		}
	}
}

if (!function_exists("getBackupLog"))
{
	function getBackupLog()
	{
		$CI = & get_instance();

		$CI->db->select("aDate, aValue, aRelValue, devDetails");
		$CI->db->from("trans_log");
		$CI->db->where(array(
			// "cId" => get_company('id'),
			"aEvent" => "BL"
		));
		$CI->db->order_by("aDate", "desc");
		$data = $CI->db->get()->row_array();

		return $data;
	}
}

/*if (!function_exists('get_user_agent'))
{
	function get_user_agent( $u_agent = null ) {
		if( $u_agent === null && isset($_SERVER['HTTP_USER_AGENT']) ) {
			$u_agent = $_SERVER['HTTP_USER_AGENT'];
		}

		if( $u_agent === null ) {
			throw new \InvalidArgumentException('parse_user_agent requires a user agent');
		}

		$platform = '';
		$browser  = '';
		$version  = '';



		$empty = array( 'details' => $u_agent, 'deviceIP' => '','os' => $platform, 'clientName' => $browser);

		if( !$u_agent ) {
			return $empty;
		}

		$client  = @$_SERVER['HTTP_CLIENT_IP'];
		$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
		$remote  = $_SERVER['REMOTE_ADDR'];

		if(filter_var($client, FILTER_VALIDATE_IP))
		{
			$uip = $client;
		}
		elseif(filter_var($forward, FILTER_VALIDATE_IP))
		{
			$uip = $forward;
		}
		else
		{
			$uip = $remote;
		}
		$empty['deviceIP'] = $uip;

		if( preg_match('/\((.*?)\)/m', $u_agent, $parent_matches) ) {
			preg_match_all('/(?P<platform>BB\d+;|Android|CrOS|Tizen|iPhone|iPad|iPod|Linux|(Open|Net|Free)BSD|Macintosh|Windows(\ Phone)?|Silk|linux-gnu|BlackBerry|PlayBook|X11|(New\ )?Nintendo\ (WiiU?|3?DS|Switch)|Xbox(\ One)?)
					(?:\ [^;]*)?
					(?:;|$)/imx', $parent_matches[1], $result);

			$priority = array( 'Xbox One', 'Xbox', 'Windows Phone', 'Tizen', 'Android', 'FreeBSD', 'NetBSD', 'OpenBSD', 'CrOS', 'X11' );

			$result['platform'] = array_unique($result['platform']);
			if( count($result['platform']) > 1 ) {
				if( $keys = array_intersect($priority, $result['platform']) ) {
					$platform = reset($keys);
				} else {
					$platform = $result['platform'][0];
				}
			} elseif( isset($result['platform'][0]) ) {
				$platform = $result['platform'][0];
			}
		}

		if( $platform == 'linux-gnu' || $platform == 'X11' ) {
			$platform = 'Linux';
		} elseif( $platform == 'CrOS' ) {
			$platform = 'Chrome OS';
		}

		preg_match_all('%(?P<browser>Camino|Kindle(\ Fire)?|Firefox|Iceweasel|IceCat|Safari|MSIE|Trident|AppleWebKit|
					TizenBrowser|(?:Headless)?Chrome|YaBrowser|Vivaldi|IEMobile|Opera|OPR|Silk|Midori|Edge|Edg|CriOS|UCBrowser|Puffin|OculusBrowser|SamsungBrowser|
					Baiduspider|Googlebot|YandexBot|bingbot|Lynx|Version|Wget|curl|
					Valve\ Steam\ Tenfoot|
					NintendoBrowser|PLAYSTATION\ (\d|Vita)+)
					(?:\)?;?)
					(?:(?:[:/ ])(?P<version>[0-9A-Z.]+)|/(?:[A-Z]*))%ix',
			$u_agent, $result);

		// If nothing matched, return null (to avoid undefined index errors)
		if( !isset($result['browser'][0]) || !isset($result['version'][0]) ) {
			if( preg_match('%^(?!Mozilla)(?P<browser>[A-Z0-9\-]+)(/(?P<version>[0-9A-Z.]+))?%ix', $u_agent, $result) ) {
				// return array( 'platform' => $platform ?: null, 'browser' => $result['browser'], 'version' => isset($result['version']) ? $result['version'] ?: null : null );
				$empty['os'] = $platform ?: '';
				$empty['clientName'] = $result['browser'];
			}

			return $empty;
		}

		if( preg_match('/rv:(?P<version>[0-9A-Z.]+)/i', $u_agent, $rv_result) ) {
			$rv_result = $rv_result['version'];
		}

		$browser = $result['browser'][0];
		$version = $result['version'][0];

		$lowerBrowser = array_map('strtolower', $result['browser']);

		$find = function ( $search, &$key, &$value = null ) use ( $lowerBrowser ) {
			$search = (array)$search;

			foreach( $search as $val ) {
				$xkey = array_search(strtolower($val), $lowerBrowser);
				if( $xkey !== false ) {
					$value = $val;
					$key   = $xkey;

					return true;
				}
			}

			return false;
		};

		$key = 0;
		$val = '';
		if( $browser == 'Iceweasel' || strtolower($browser) == 'icecat' ) {
			$browser = 'Firefox';
		} elseif( $find('Playstation Vita', $key) ) {
			$platform = 'PlayStation Vita';
			$browser  = 'Browser';
		} elseif( $find(array( 'Kindle Fire', 'Silk' ), $key, $val) ) {
			$browser  = $val == 'Silk' ? 'Silk' : 'Kindle';
			$platform = 'Kindle Fire';
			if( !($version = $result['version'][$key]) || !is_numeric($version[0]) ) {
				$version = $result['version'][array_search('Version', $result['browser'])];
			}
		} elseif( $find('NintendoBrowser', $key) || $platform == 'Nintendo 3DS' ) {
			$browser = 'NintendoBrowser';
			$version = $result['version'][$key];
		} elseif( $find('Kindle', $key, $platform) ) {
			$browser = $result['browser'][$key];
			$version = $result['version'][$key];
		} elseif( $find('OPR', $key) ) {
			$browser = 'Opera Next';
			$version = $result['version'][$key];
		} elseif( $find('Opera', $key, $browser) ) {
			$find('Version', $key);
			$version = $result['version'][$key];
		} elseif( $find('Puffin', $key, $browser) ) {
			$version = $result['version'][$key];
			if( strlen($version) > 3 ) {
				$part = substr($version, -2);
				if( ctype_upper($part) ) {
					$version = substr($version, 0, -2);

					$flags = array( 'IP' => 'iPhone', 'IT' => 'iPad', 'AP' => 'Android', 'AT' => 'Android', 'WP' => 'Windows Phone', 'WT' => 'Windows' );
					if( isset($flags[$part]) ) {
						$platform = $flags[$part];
					}
				}
			}
		} elseif( $find('YaBrowser', $key, $browser) ) {
			$browser = 'Yandex';
			$version = $result['version'][$key];
		} elseif( $find(array( 'Edge', 'Edg' ), $key, $browser) ) {
			$browser = 'Edge';
			$version = $result['version'][$key];
		} elseif( $find(array( 'IEMobile', 'Midori', 'Vivaldi', 'OculusBrowser', 'SamsungBrowser', 'Valve Steam Tenfoot', 'Chrome', 'HeadlessChrome' ), $key, $browser) ) {
			$version = $result['version'][$key];
		} elseif( $rv_result && $find('Trident', $key) ) {
			$browser = 'MSIE';
			$version = $rv_result;
		} elseif( $find('UCBrowser', $key) ) {
			$browser = 'UC Browser';
			$version = $result['version'][$key];
		} elseif( $find('CriOS', $key) ) {
			$browser = 'Chrome';
			$version = $result['version'][$key];
		} elseif( $browser == 'AppleWebKit' ) {
			if( $platform == 'Android' ) {
				$browser = 'Android Browser';
			} elseif( strpos($platform, 'BB') === 0 ) {
				$browser  = 'BlackBerry Browser';
				$platform = 'BlackBerry';
			} elseif( $platform == 'BlackBerry' || $platform == 'PlayBook' ) {
				$browser = 'BlackBerry Browser';
			} else {
				$find('Safari', $key, $browser) || $find('TizenBrowser', $key, $browser);
			}

			$find('Version', $key);
			$version = $result['version'][$key];
		} elseif( $pKey = preg_grep('/playstation \d/i', $result['browser']) ) {
			$pKey = reset($pKey);

			$platform = 'PlayStation ' . preg_replace('/\D/', '', $pKey);
			$browser  = 'NetFront';
		}

		$empty['os'] = $platform ?: '';
		$empty['clientName'] = $browser?: '';
		return $empty;
	}
}*/

if (!function_exists('get_user_agent'))
{
	function get_user_agent() {
		$CI = & get_instance();
		$CI->load->library('user_agent');

		$client  = @$_SERVER['HTTP_CLIENT_IP'];
		$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
		$remote  = $_SERVER['REMOTE_ADDR'];

		if(filter_var($client, FILTER_VALIDATE_IP))
		{
			$uip = $client;
		}
		elseif(filter_var($forward, FILTER_VALIDATE_IP))
		{
			$uip = $forward;
		}
		else
		{
			$uip = $remote;
		}
		// $ip = $CI->input->ip_address();		
		$return = array( 'details' => '', 'deviceIP' => '','os' => '', 'clientName' => '');
		$return['deviceIP'] = ($uip=='::1')?'localhost':$uip;

		$return['details'] = $CI->agent->agent;
		$return['os'] = $CI->agent->platform();
		if ($return['os']=='Unknown Platform' && strpos($return['details'],'Dart')!==false) {
			$return['os'] = 'Dart';
		}
		$return['clientName'] = $CI->agent->browser();

		return $return;
	}
}

if (!function_exists('apply_curr_fraction'))
{
	function apply_curr_fraction($currencyCode="INR", $dbConn=null)
	{
		$CI = & get_instance();
		$CI->config->load("currency_symbols");
		$currencies = $CI->config->item("currency");
		$curr = $currencies[$currencyCode];
		
		if (empty($curr) || empty($curr["fraction"]))
		{
			$curr["fraction"] = 2;
			return;
		}

		$tables = array(
			"ob_account" => array("balance"),
			"ob_banktrans" => array("debit", "credit"),
			"ob_contacts" => array("balance"),
			"ob_items" => array("saleRate", "purchaseRate"),
			"ob_item_attr" => array("saleRate"),
			"ob_price_item" => array("rateVal"),
			"ob_price_list" => array("rateVal"),
			"ob_stock_items" => array("rate", "mrp"),
			"ob_taxdetail" => array("taxRate"),
			"ob_taxreturns" => array("totAmount", "taxableAmount", "CGST", "SGST", "IGST", "CESS"),
			"ob_trans" => array("taxableAmount", "roundAmount", "totTax", "totAmount", "tdsAmount"),
			"ob_trans_acc" => array("debit", "credit", "dueAmount"),
			"ob_trans_items" => array("rate", "discAmount", "taxableAmount", "itemTotal"),
			"ob_trans_payment" => array("allotAmt", "tdsAmt", "writeoff"),
			"ob_trans_tax" => array("taxRate", "taxValue")
		);

		if (!$dbConn)
		{
			$dbConn = $CI->db;
		}

		foreach($tables as $table=>$fields)
		{
			foreach($fields as $field)
			{
				$dbConn->query("ALTER TABLE " . $table . " MODIFY " . $field . " decimal(11," . $curr["fraction"] . ");");
			}
		}
	}
}

if (!function_exists('is_english'))
{
	function is_english($str)
	{
		// if (strlen($str) != strlen(utf8_decode($str))) {
		if (strlen($str) != strlen(mb_convert_encoding($str, 'UTF-8', mb_list_encodings()))) {
			return false;
		} else {
			return true;
		}
	}
}

if (!function_exists('post_od_crm'))
{
	// curl -k -X POST -H "Accesskey-od:EyTLoWLgjRvwt9f2cSTe" 'https://cp.outputdesk.com/create/leads' -H "Content-Type: application/json" --data '{ "email": "", "name": "", "company": "", "phone": "","product": "Output Books" }'
	function post_od_crm($url="", $data=array())
	{
/*
		$data = array(
			"name"		=> $rawData["name"],
			"company"	=> $rawData["company_name"],
			"phone"		=> $rawData["phone"],
			"email"		=> $rawData["email"],
			"product"	=> "Output Books"
		);
*/

		// $url = "https://cp.outputdesk.com/" . $url;
		$url = "https://od.outputbooks.com/" . $url;

		$data = json_encode($data);

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		// curl_setopt($ch, CURLINFO_HEADER_OUT, true);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Accesskey-od: EyTLoWLgjRvwt9f2cSTe",
			"Content-Type: application/json",
			"Content-Length: " . strlen($data))
		);

		// curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
		// curl_setopt($ch, CURLOPT_PROXY, "http://192.168.2.1:3128");

		$response = curl_exec($ch);

		curl_close($ch);

		try {
			$response = json_decode($response, true);

			if (!empty($response))
			{
				// $rawData["id"];
				// $response["leadid"];
				return $response;
			}

			return false;
		} catch(Exception $e) {
			// "Error : " . $e->getMessage();
			return false;
		}
	}
}

if (!function_exists('get_image'))
{
	function get_image($data)
	{
		$image_url = '';
		if(!empty($data['imageId'])){
			$image_url = $data['path'] . get_company('id') . DS . 'images' . DS . $data['subDir'] . DS . implode(DS,str_split($data['imageId'])) . DS . $data['imageId'] . '_default' . $data['imgFileExt'];
		}
		return $image_url;
	}
}

if (!function_exists('get_obhash'))
{
	function get_obhash($text="", $hash="")
	{
		if (empty($text))
		{
			return false;
		}

		$CI = & get_instance();
		$salt = $CI->config->item("encryption_key");

		$myHash = substr(md5($salt . $text), 0, 8);

		if (!empty($hash))
		{
			return (strtolower($hash) == strtolower($myHash)) ? TRUE : FALSE;
		}

		return $myHash;
	}
}

if (!function_exists('ob_curl_post'))
{
	function ob_curl_post($url="", $postData=array(), $headers=array())
	{
		$ch = curl_init($url);

		curl_setopt($ch, CURLOPT_URL, $url);

		// curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
		$postData = json_encode($postData);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

		if (empty($headers))
		{
			$headers = array();
		}
		$headers[] = "Content-Type: application/json";
		$headers[] = "Content-Length: " . strlen($postData);

		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		// curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
		// curl_setopt($ch, CURLOPT_PROXY, "192.168.2.1:3128");
		// curl_setopt($ch, CURLOPT_PROXYUSERPWD, "admin:admin");

		// $user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36';
		// curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);

		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
		curl_setopt($ch, CURLOPT_BUFFERSIZE, 10);
		curl_setopt($ch, CURLOPT_POSTREDIR, 7);

		$response = curl_exec($ch);

		curl_close($ch);
		file_put_contents('sms1.txt',print_r($response, true).PHP_EOL,FILE_APPEND);
		return $response;
	}
}

if (!function_exists('key_compare_func'))
{

	function key_compare_func($a, $b)
	{
		if ($a === $b) {
			return 0;
		}
		return ($a > $b)? 1:-1;
	}
}
if (!function_exists('type_map'))
{
	function type_map($type, $rev=false)
	{
		$map_type = array(TRANSORD => PURORD, TRANSDEL => DELCHALLAN, TRANSRPT => PURRECP, MATDEL => DELCHALLAN, MATRPT => PURRECP);

		if ($rev) {
			$map_type = array_flip($map_type);
		}
		return !empty($map_type[$type])?$map_type[$type]:$type;
	}
}

if (!function_exists('get_shared_companies')) {
	function get_shared_companies() {
		$CI = & get_instance();

		$licData = get_user_data("licenseData", true);
		if (get_company('shareConbtwBranches',false)!=3 || empty($licData) || (empty($licData["isEnterprise"]) && empty($licData["isTrial"])))
		{
			return array();
		}
		
		$CI->db->select('distinct c.id',false)->from('companies as c');
		$CI->db->join('compsettings as cs','cs.cId = c.id');
		$CI->db->where(array('c.isActive' => 1, 'cs.shareConbtwBranches' => 3));
		// @ no need of compusers validation 
		// $CI->db->join('compusers as cu','c.id = cu.cId');
		// $CI->db->where(array('cu.userId' => get_user_data('id')));
		$tmp = $CI->db->get()->result_array();

		return $tmp?array_keys(array_key_index($tmp,'id')):array();
	}
}

if (!function_exists('sanitizeFileName'))
{
	function sanitizeFileName($string)
	{
		// Replace spaces with underscores
		$string = str_replace(' ', '_', $string);

		// Remove all characters except letters, numbers, underscores, and dashes
		$string = preg_replace('/[^A-Za-z0-9_\-]/', '', $string);

		// Optionally trim and return
		return trim($string, '_-');
	}
}
