<?

require_once ('Logger.php');

class Util {

	public static $T;
	protected static $logger;

    /**
     * Constructor function
     *
     */
    public function __construct()
    {
    }

    public static function var_dump_ret($mixed = null) {
      ob_start();
      var_dump($mixed);
      $content = ob_get_contents();
      ob_end_clean();
      return $content;
    }

		public static function encapsulateWithQuote($str, $separator=",", $encap="'") {
			$arr = explode($separator, $str);
 			return implode($separator, array_map(function($col) use ($encap) {
				return sprintf("%s%s%s", $encap, $col, $encap);
				}, $arr));

		}

		public static function pairingArrayObject($rows, $key, $value) {
			$arry = array();
			foreach ($rows as $i => $row) {
				$arry[$row[$key]] = $row[$value];
			}
			return $arry;
		}

	public static function parse_url_info($url) {
		$_I = null;
		$pattern = '/^(http|https):\/\/([a-zA-Z0-9_\-.]+)(.*)$/';
		if (preg_match( $pattern, $url, $match)) {
			$_I = [];
			$_I['protocol'] = $match[1];
			$_I['subdomain'] = $match[2];
			$_tmp = preg_split('/\./', $match[2]);
			$_I['domain'] = sprintf("%s.%s", $_tmp[sizeof($_tmp)-2], $_tmp[sizeof($_tmp)-1]);
			$_I['uri'] = $match[3];
		}
		return $_I;
	}

	public static function get_url_info() {
		if (!isset($T)) {
			$T['protocol'] = isset($_SERVER["HTTPS"]) ? 'https' : 'http';
			$T['domain'] = $_SERVER['SERVER_NAME']=='$servername' ? $_SERVER[HTTP_HOST] : $_SERVER['SERVER_NAME'] ;
		}

		$T['uri'] = $_SERVER['REQUEST_URI'];
		$T['dir'] = dirname($_SERVER['REQUEST_URI']);
		$T['page'] = basename($_SERVER['REQUEST_URI']);

		$T['web'] = $T['protocol'] . '://' . $T['domain'];
		$T['path'] = $T['protocol'] . '://' . $T['domain'] . $T['dir'];
		$T['url'] = $T['protocol'] . '://' . $T['domain'] . $T['uri'];

		return $T;
	}

	public static function get_request_headers() {

		if( !function_exists('apache_request_headers') ) {
        	function apache_request_headers() {
                $arh = array();
                $rx_http = '/\AHTTP_/';
                foreach($_SERVER as $key => $val) {
                        if( preg_match($rx_http, $key) ) {
                                $arh_key = preg_replace($rx_http, '', $key);
                                $rx_matches = array();
                                // do some nasty string manipulations to restore the original letter case
                                // this should work in most cases
                                $rx_matches = explode('_', strtolower($arh_key));
                                if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
                                        foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
                                        $arh_key = implode('-', $rx_matches);
                                }
                                $arh[$arh_key] = $val;
                        }
                }
                if(isset($_SERVER['CONTENT_TYPE'])) $arh['Content-Type'] = $_SERVER['CONTENT_TYPE'];
                if(isset($_SERVER['CONTENT_LENGTH'])) $arh['Content-Length'] = $_SERVER['CONTENT_LENGTH'];
                return( $arh );
        	}
		}

		return apache_request_headers();
	}

	// Function to get the client IP address
	public static function get_client_ip() {
	    $ipaddress = '';
	    if (getenv('HTTP_X_FORWARDED_FOR'))
	        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
	    else if(getenv('HTTP_X_FORWARDED'))
	        $ipaddress = getenv('HTTP_X_FORWARDED');
	    else if(getenv('HTTP_CLIENT_IP'))
	        $ipaddress = getenv('HTTP_CLIENT_IP');
	    else if(getenv('HTTP_FORWARDED_FOR'))
	        $ipaddress = getenv('HTTP_FORWARDED_FOR');
	    else if(getenv('HTTP_FORWARDED'))
	       $ipaddress = getenv('HTTP_FORWARDED');
	    else if(getenv('REMOTE_ADDR'))
	        $ipaddress = getenv('REMOTE_ADDR');
	    else
	        $ipaddress = 'UNKNOWN';

   		// fixed real exact IP address
		if ($i=strpos($ipaddress, ',')) {
   			$r = preg_split('/,/', $ipaddress);
   			//$p = strpos($r[0], ':') ? 1 : 0;
   			$p = 0; // always use first ip column
   			$ipaddress = $r[$p];
		}

	    return trim($ipaddress);
	}


	public static function encodeURI($uri) {
    	return preg_replace_callback("{[^0-9a-z_.!~*'();,/?:@&=+$#-]}i", function ($m) {
        	return sprintf('%%%02X', ord($m[0]));
    	}, $uri);
	}

	public static function selfURL() {
		$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
		$protocol = self::strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
		$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
		return $protocol."://".($_SERVER['SERVER_NAME']=='$servername'?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME']).$port.$_SERVER['REQUEST_URI'];
	}

	private static function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2)); }

	public static function isPostback() {
		$isPostBack = false;

		$referer = "";
		$thisPage = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

		if (isset($_SERVER['HTTP_REFERER'])){
    		$referer = $_SERVER['HTTP_REFERER'];
		}

		if ($referer == $thisPage){
    		$isPostBack = true;
		}

		return $isPostBack;
	}

	public static function toArray($in_qstr) {
	    $arry = [];
	    $tokens = explode('&', $in_qstr);
	    foreach ($tokens as $key => $value) {
	        if (preg_match( '/(.*)=(.*)/', $value, $match )) {
	            $arry[$match[1]] = $match[2];
	        }
	    }
	    return $arry;
	}

	public static function toQueryString($arry, $TS='&') {
	    $str = "";
	    foreach($arry as $key => $value) {
	        $str .= $TS . urlencode($key) . '=' . urlencode($value) ;
	    }
	    return substr($str, 1);
	}

	public static function replaceQueryString($in_qstr, $out_format, $dynamic=0, $skip=0) {
		parse_str($in_qstr, $qstr_arry);
		$o_url = null;

	    // get queryString of output format
	    $arry = [];
	    if (preg_match( '/http(.*)\?(.*)/', $out_format, $match)) {
			$o_url = 'http' . $match[1];
	        $o_qstr = $match[2];
			parse_str($o_qstr, $out_arry);
	        foreach ($out_arry as $key => $value) {
	            $out_arry[$key] = $qstr_arry[$key];
	        }

			# append rest query string
			# 2019-03-17 edited by Nack requested by Ket : to support dynamic query string
			if ($dynamic==1)
			foreach (array_slice($qstr_arry, $skip) as $key => $value) {
				if (!array_key_exists($key, $out_arry)) {
					$out_arry[$key] = $value;
				}
			}
	     } else return null;

	    return $o_url . (!empty($o_url) ? '?' : '') . Util::toQueryString($out_arry);
	}

	public static function parseArrayData($arry, $data, $use_def_if_blank=false, $left_join=1) {
		// if (self::$logger == null)
    	//     	self::$logger = Logger::getInstance($_SERVER['PHP_SELF']);
		$a = array();
		foreach($arry as $k => $def) {
			if (array_key_exists($k, $data)) {
				if ($use_def_if_blank) {
					if ($data[$k]==='' && $def!=='') {
						$a[$k] = $def;
					} else {
						$a[$k] = $data[$k];
					}
				} else {
					$a[$k] = $data[$k];
				}
			}
			else if($left_join) $a[$k] = $def; // set with the left join
		}
		return $a;
	}

	public static function convert2DropDownList($name, $rows, $key, $val, $placeholder=null, $exts=null, $default=null, $disabled=false, $class=null) {
		//if (self::$logger == null)
        //	self::$logger = Logger::getInstance($_SERVER['PHP_SELF']);
        $_multi = null;
		if (is_array($val)) { // merge columns which specific key
            foreach ($val as $col_name) {
				$_tmp = array_column($rows, $col_name, $key);
                if ($_multi == null) $_multi = $_tmp;
				else {
					foreach($_tmp as $k => $v) {
						$_multi[$k] .= ' ' . $_tmp[$k];
					}
				}
			}
		}

		$str = '<select'.(isset($class)?' class="' . $class. '"':'').' name="' . $name .'" id="ddl_' . $name . '"' . ($disabled?' disabled':'') . '>';
		if ($placeholder) $str .= '<option value="' . $placeholder['value'] . '" selected disabled>' . $placeholder['display'] . '</option>';
		foreach($rows as $row) {
			//self::$logger->debug($default . '<==>' . $row[$key]);
			//self::$logger->debug($default == $row[$key] ? 'T' : 'F');
			$str .= '<option value="' . $row[$key] . '"' . ( $default != null && $default==$row[$key] ? ' selected' : '' ) . '>'
				. (is_array($val) ? $_multi[$row[$key]]  : $row[$val] )
				. '</option>';
		}
		if ($exts)
			foreach($exts as $ext)
				$str .= '<option value="' . $ext[$key] . '"' . ( $default != null && $default==$ext[$key] ? ' selected' : '' ) . '>' . $ext[$val] . '</option>';
		$str .= '</select>';
		return $str;
	}

	public static function convert2CheckBox($name, $rows, $key, $val, $placeholder=null, $exts=null, $default=null, $checked=false, $class=null) {
		//if (self::$logger == null)
        //	self::$logger = Logger::getInstance($_SERVER['PHP_SELF']);

		$str = '';
		//if ($placeholder) $str .= '<input type="checkbox" name="' . $name . '" id= value="' . $placeholder['value'] . '" selected disabled>' . $placeholder['display'] . '</option>';
		foreach($rows as $row) {
			$str .= '<label>' . $row[$val];
			$str .= '<input'.(isset($class)?' class="' . $class. '"':'').' type="checkbox" name="' . $name . '" value="' . $row[$key] . '"' . ( ( $default != null && $default==$row[$key] ) || $checked ? ' checked' : '' ) . '>';
			$str .= '<span></span>';
			$str .= '</label>';
		}
		if ($exts)
			foreach($exts as $ext) {
				$str .= '<label>' . $ext[$val];
				$str .= '<input'.(isset($class)?' class="' . $class. '"':'').' type="checkbox" name="' . $name . '" value="' . $ext[$key] . '"' . ( ( $default != null && $default==$ext[$key] ) || $checked ? ' checked' : '' ) . '>';
				$str .= '<span></span>';
				$str .= '</label>';
			}
		return $str;
	}

	public static function convert2Radio($name, $rows, $key, $val, $placeholder=null, $exts=null, $default=null, $checked=false, $class=null) {
		//if (self::$logger == null)
        //	self::$logger = Logger::getInstance($_SERVER['PHP_SELF']);

		$str = '';
		//if ($placeholder) $str .= '<input type="checkbox" name="' . $name . '" id= value="' . $placeholder['value'] . '" selected disabled>' . $placeholder['display'] . '</option>';
		foreach($rows as $row) {
			$str .= '<input'.(isset($class)?' class="' . $class. '"':'').' type="radio" id="rd_'.$row[$val].'" name="' . $name . '" value="' . $row[$key] . '"' . ( ( $default != null && $default==$row[$val] ) || $checked ? ' checked' : '' ) . '>';
			$str .= '<label for="rd_'.$row[$val].'">' . $row[$val];
			$str .= '</label>';
		}
		if ($exts)
			foreach($exts as $ext) {
				$str .= '<input'.(isset($class)?' class="' . $class. '"':'').' type="radio" id="rd_'.$ext[$val].'" name="' . $name . '" value="' . $ext[$key] . '"' . ( ( $default != null && $default==$ext[$key] ) || $checked ? ' checked' : '' ) . '>';
				$str .= '<label for="rd_'.$ext[$val].'">' . $ext[$val];
				$str .= '</label>';
			}
		return $str;
	}

    public static function echos($text, $color="normal") {

		static $colors = array(
		'light_red' => "[1;31m",
		'light_green' => "[1;32m",
		'yellow' => "[1;33m",
		'light_blue' => "[1;34m",
		'magenta' => "[1;35m",
		'light_cyan' => "[1;36m",
		'white' => "[1;37m",
		'normal' => "[0m",
		'black' => "[0;30m",
		'red' => "[0;31m",
		'green' => "[0;32m",
		'brown' => "[0;33m",
		'blue' => "[0;34m",
		'cyan' => "[0;36m",
		'bold' => "[1m",
		'underscore' => "[4m",
		'reverse' => "[7m"
		);

		$str = chr(27) . $colors[$color] . $text . chr(27) . "[0m";

        if (PHP_SAPI === 'cli') {
			if (isset($_SERVER['TERM']) && $_SERVER['TERM']!=='unknown') {
				echo (new DateTime())->format('Y-m-d H:i:s | ') . $str;
			} else { // run with cron
				if (DEFINED('DAEMON_LOG')) {
					file_put_contents(DAEMON_LOG, (new DateTime())->format('Y-m-d H:i:s | ') . $str, FILE_APPEND);
            	}
        	}
        }
    }

	public static function util_search( $array, $keyname , $value ,$many=false ) 
	{
		// Check first
		$keyname = trim($keyname);
		$value = trim($value);
		$value = is_numeric($value)?$value:(string)$value;

		if ( empty( $array ) || empty( $keyname ) || is_array($array) == FALSE ) {
			return false;
		} else {
			$result = array();

			foreach ( $array as $a ) {
				if (  isset($a[$keyname]) &&  $a[$keyname] == $value )  {
					$result[] = $a;
				}
			}

			if ( empty($result) ) {
				return FALSE ;
			} else {
				if ( $many==true) {
					return  $result ;
				} else {
					return  $result[0] ;
				}

			}

		} // end if array
	}

	public static function clean_00( $value ) 
	{	
		$ret = $value;
		//if ( $value=="0.00" || $value=="0" ) return "0";
		if ( $value=="0.00" || $value=="0" ) return "0";
		if( strlen($value)>=1 ){
			list( $a, $b ) = explode(".",$value.".");
			if( $b=="00" ){
				$ret = $a;
			}
		}
		return $ret;
	}	
}
