<?php

class help {

	public static function url( $DOC_ROOT = ROOT_DIR, $MINI = FALSE ) {
		$DOC_ROOT = str_replace( "\\", "/", $DOC_ROOT );
		$SRV_URL = preg_replace( "~^{$_SERVER['DOCUMENT_ROOT']}~i", $_SERVER['SERVER_NAME'], $DOC_ROOT );
		$SCHEME = ($_SERVER['REQUEST_SCHEME'] ?? ($_SERVER['SERVER_PORT'] == '80' ? 'http' : 'https'));
		return (!$MINI ? ($SCHEME . "://") : '/') . $SRV_URL;
	}
	
	public static function sanitize($data, $escape = false) {
		if( is_array($data) ) {
			foreach( $data as $key => $value ) 
				$data[$key] = self::sanitize($value);
		} else {
			$data = trim($data);
			$data = stripslashes($data);
			$data = htmlspecialchars($data);
			if( $escape ) {
				global $link;
				$data = $link->real_escape_string($data);
			}
		};
		return $data;
	}
	
	public static function array_blend() {
		if( empty(func_get_args()) ) throw new exception(":array_blend() requires at least one array argument");
		$blender = array();
		foreach( func_get_args() as $key => $array ) {
			$index = $key + 1;
			if( !is_array($array) ) throw new exception(":array_blend() parameter {$index} must be an array");
			foreach( $array as $value) $blender[] = $value;
		};
		return $blender;
	}
	
	public static function keygen(int $len = 10, $spec_char = true) {
		$spec_char = $spec_char ? array('%', '@', '#', '$', '^', '&', '(', ')', '/', '?') : [];
		$char = self::array_blend(range(0,9), range('a', 'z'), range('A', 'Z'), $spec_char);
		shuffle($char);
		$result = array_slice($char, 0, $len);
		return implode('', $result);
	}
	
	public static function get_user($value, $col = 'email', $MORE = null) {
		global $link;
		$SQL = sQuery::select( 'tbl_users', "{$col} = '{$value}' {$MORE}" );
		$user = $link->query( $SQL )->fetch_assoc();
		if( $user && empty($user['pics']) ) $user['pics'] = 'default-avatar.png';
		return $user;
	}
	
	public static function process_image( ?array $image, int $max_KB = 1204 ) {
		if( is_null($image) ) return;
		$image['error_msg'] = null;
		if( $image['error'] ) {
			$image['error_msg'] = self::file_error_msg( $image['error'] );
			return $image;
		};
		$dimension = getimagesize($image['tmp_name']);
		if( !$dimension ) {
			$image['error'] = 9;
			$image['error_msg'] = "File is not a valid image";
			return $image;
		};
		$image['extension'] = explode("/", $dimension['mime'])[1];
		$image['width'] = $dimension[0];
		$image['height'] = $dimension[1];
		$image['kilobyte'] = round( $image['size'] / 1024, 1 );
		if( $image['kilobyte'] > $max_KB ) {
			$image['error'] = 10;
			$image['error_msg'] = "File size is too large";
			return $image;
		} else if( !in_array($image['extension'], ['jpeg', 'jpg', 'png']) ) {
			$image['error'] = 11;
			$image['error_msg'] = "File type not supported";
		};
		return $image;
	}
	
	public static function file_error_msg($index) {
		switch( $index ) {
			case 8: 
				return "A PHP extension stopped the file upload";
			case 7: 
				return "Failed to write file to disk";
			case 6: 
				return "Missing a temporary folder";
			case 4: 
				return "No file was uploaded";
			case 3:
				return "The uploaded file was only partially uploaded";
			case 2: 
				return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
			case 1: 
				return "The uploaded file exceeds the upload_max_filesize";
		};
		return null;
	}
	
	public static function QRCodeURL( string $string ) {
		error_reporting(0);
		ob_start();
		QRCode::png( $string );
		$image = ob_get_clean();
		$encode = base64_encode($image);
		$url = "data:image/png;base64,{$encode}";
		error_reporting(1);
		return $url;
	}
	
	public static function price_rate( $of = null ) {
		$of = strtoupper($of);
		$url = "https://bitpay.com/api/rates";
		$json = file_get_contents($url);
		$rates = json_decode($json, TRUE); 
		$data = array();
		$usd = 0;
		foreach( $rates as $price ) {
			$code = $price['code'];
			if( $code == 'USD' ) $usd = $price['rate'];
			$data[ $code ] = $price['rate'];
		};
		if( empty($of) ) return $data;
		else if( !isset($data[ $of ]) ) return 0;
		$result = round($usd / $data[ $of ], 2);
		return $result;
	}
	
	public static function stdCheck($value, $onTrue = 'Active', $onFalse = 'Inactive') {
		if( !empty($value) ) $context = "<i class='fas fa-check text-success mr-1'></i> {$onTrue}";
		else $context = "<i class='fas fa-times text-danger mr-1'></i> {$onFalse}";
		return "<span class='text-nowrap'>{$context}</span>";
	}
	
	public static function get_json($value) {
		if( empty($value) ) return [];
		$data = json_decode((string)$value, true);
		return $data;
	}
	
	public static function countries(?string $key = null) {
		$file = INC_DIR . '/Country-ISO-alpha-2-unicodes.json';
		$content = file_get_contents($file);
		$data = self::get_json($content);
		$countries = array();
		foreach( $data as $country ) {
			$countries[ ($country['Code']) ] = $country['Name'];
			if( $key && $key == $country['Code'] ) return $country['Name'];
		};
		return $countries;
	}
	
	public static function countries_dropdown(string $name = 'country', ?string $select = null) {
		$str = "<select name='{$name}' class='form-control'>";
		foreach(self::countries() as $code => $name) {
			$selected = (strtoupper($select) == $code) ? 'selected' : null;
			$str .= "\n\t<option value='{$code}' {$selected}>{$name}</option>";
		};
		$str .= "\n</select>\n";
		echo $str;
	}
	
	public static function generate_number(int $limit) {
		$numbers = range(0,9);
		$result = '';
		while( strlen($result) < $limit ) {
			shuffle($numbers);
			$result .= $numbers[0];
		};
		return $result;
	}
	
	public static function CREATE_OTP(string $title, string $email, callable $func) {
		$OTP = self::generate_number(4);
		$mailer = new mailer();
		$mailer->addAddress($email);
		$mailer->Subject = $title;
		$mailer->Body = $func($OTP);
		$mailer->send();
		return $OTP;
	}
	
}