<?php
	
	use Install\Core\Redirect;
  use Pecee\Http\Input\InputItem;
  use Pecee\SimpleRouter\SimpleRouter as Router;
	use Pecee\Http\Url;
	use Pecee\Http\Response;
	use Pecee\Http\Request;
	use Rakit\Validation\Validator;

	/**
	 * Get url for a route by using either name/alias, class or method name.
	 *
	 * The name parameter supports the following values:
	 * - Route name
	 * - Controller/resource name (with or without method)
	 * - Controller class name
	 *
	 * When searching for controller/resource by name, you can use this syntax "route.name@method".
	 * You can also use the same syntax when searching for a specific controller-class "MyController@home".
	 * If no arguments is specified, it will return the url for the current loaded route.
	 *
	 * @param string|null $name
	 * @param string|array|null $parameters
	 * @param array|null $getParams
	 * @return \Pecee\Http\Url
	 * @throws \InvalidArgumentException
	 */
	function url(?string $name = null, $parameters = null, ?array $getParams = null): Url
	{
		return Router::getUrl($name, $parameters, $getParams);
	}
	
	/**
	 * @return \Pecee\Http\Response
	 */
	function response(): Response
	{
		return Router::response();
	}
	
	/**
	 * @return \Pecee\Http\Request
	 */
	function request(): Request
	{
		return Router::request();
	}
	
	/**
	 * Get input class
	 * @param string|null $index Parameter index name
	 * @param string|mixed|null $defaultValue Default return value
	 * @param array ...$methods Default methods
	 * @return \Pecee\Http\Input\InputHandler|array|string|null
	 */
	function input($index = null, $defaultValue = null, ...$methods)
	{
		if ($index !== null) {
			return request()->getInputHandler()->value($index, $defaultValue, ...$methods);
		}
		
		return request()->getInputHandler();
	}

  /**
   * Set input value
   * @param string $key
   * @param mixed $value
   */
  function set_input(string $key, $value): void
  {
    request()->getInputHandler()->addPost($key, new InputItem($key, $value));
  }
	
	/**
	 * @param string $url
	 * @param int|null $code
	 */
	function redirect(string $url, ?int $code = null): void
	{
		if ($url == "/login") {
			$url .= "?redirect=".$_SERVER["REQUEST_URI"];
		}
		
		if ($code !== null) {
			response()->httpCode($code);
		}
		
		response()->redirect($url);
	}
	
	/**
	 * Redirect back to previous page
	 * @return Redirect
	 */
	function back(): Redirect
	{
		return new Redirect(request()->getReferer());
	}
	
	/**
	 * Validate data
	 * @param array $data
	 * @param bool $back
	 * @return array
	 */
	function validate(array $data = [], bool $back = true): array {
		$validator = new Validator;
		
		$validation = $validator->validate($_POST + $_FILES, $data);
		if ($validation->fails()) {
			response()->json([
				'success' => false,
				'errors' => $validation->errors()->all()
			]);
		}
		return [];
	}
	
	/**
	 * Get current csrf-token
	 * @return string|null
	 */
	function csrf_token(): ?string
	{
		$baseVerifier = Router::router()->getCsrfVerifier();
		if ($baseVerifier !== null) {
			return $baseVerifier->getTokenProvider()->getToken();
		}
		
		return null;
	}
	
	function post($parameter) {
		if (isset($_POST[$parameter])) {
			return htmlspecialchars(trim(strip_tags($_POST[$parameter])));
		}
		else {
			return false;
		}
	}
	
	function get($parameter) {
		if (isset($_GET[$parameter])) {
			return strip_tags(trim(addslashes($_GET[$parameter])));
		}
		else {
			return false;
		}
	}
	
	function generateSalt($length) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $randomString;
	}
	
	function createSHA256($password){
		$salt = generateSalt(16);
		$hash = '$SHA$'.$salt.'$'.hash('sha256', hash('sha256', $password).$salt);
		return $hash;
	}
	
	function checkSHA256($password, $realPassword){
		$parts = explode('$', $realPassword);
		$salt = $parts[2];
		$hash = hash('sha256', hash('sha256', $password).$salt);
		$hash = '$SHA$'.$salt.'$'.$hash;
		return (($hash == $realPassword) ? true : false);
	}
	
	function checkUsername($username) {
		return preg_match("/[^a-zA-Z0-9_]/", $username);
	}
	
  function datetime() {
    return date("Y-m-d H:i:s");
  }
	
	function escape_t__($string, $vars = [])
	{
	  return str_replace("'", "\'", t__($string, $vars));
	}
	
	function escape_e__($string, $vars = [])
	{
	  echo escape_t__($string, $vars);
	}
	
	function url_is($url): bool
	{
		return request()->getUrl() == url($url);
	}
	
	function sqlPost($par) {
		if (isset($_POST[$par])) {
			return strip_tags(trim($_POST[$par]));
		}
		else {
			return false;
		}
	}
	
	function phpFileEscape($text = null) {
		return addcslashes($text, '\'\\');
	}
	
	function checkPhp() {
		// PHP Version Check
		$supported = substr(phpversion(), 0, 3) == '7.4';
		
		return [
			'status'  => $supported ? 'success' : 'error',
			'version' => phpversion(),
		];
	}
	
	function checkCompatibility($extension, $required = true) {
		$loaded = extension_loaded($extension);
		return [
			'status'  => $loaded ? 'success' : ($required ? 'error' : 'warning'),
			'message' => $loaded ? 'active' : 'not_active',
		];
	}
	
	function checkPhpSettings($name, $expectedValue = null, $operator = null, $required = true) {
		$value = ini_get($name);
		
		if ($expectedValue === true || $expectedValue === false) {
			if ($expectedValue === true) {
				$result = $value == $expectedValue || $value == '1' || $value == 'On';
			} else {
				$result = $value == $expectedValue || $value == '0' || $value == 'Off';
			}
		} else {
			$result = version_compare($value, $expectedValue, $operator);
		}
		
		return [
			'status'  => $result ? 'success' : ($required ? 'error' : 'warning'),
			'value'   => $value,
		];
	}
	
	function checkIsWriteable($path) {
		$status = is_writable($path);
		return [
			'status'  => $status ? 'success' : 'error',
			'message' => $status ? 'writeable' : 'not_writeable',
		];
	}
	
	function getIP() {
		if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
			$ip = $_SERVER["HTTP_CF_CONNECTING_IP"];
		}
		else if (getenv("HTTP_CLIENT_IP")) {
			$ip = getenv("HTTP_CLIENT_IP");
		}
		else if (getenv("HTTP_X_FORWARDED_FOR")) {
			$ip = getenv("HTTP_X_FORWARDED_FOR");
			if (strstr($ip, ",")) {
				$tmp = explode (",", $ip);
				$ip = trim($tmp[0]);
			}
		}
		else {
			$ip = getenv("REMOTE_ADDR");
		}
		return $ip;
	}
	
	function getDomain($url) {
		$url = strtolower((isset(parse_url($url)["host"])) ? $url : '//'.$url);
		$pieces = parse_url($url);
		if (isset($pieces['host'])) {
			if (substr($pieces['host'], 0, 4) == 'www.') {
				$pieces['host'] = substr($pieces['host'], 4);
			}
			return $pieces['host'];
		}
		return false;
	}
	function _is_curl_installed() {
		if (in_array('curl', get_loaded_extensions())) {
			return true;
		}
		else {
			return false;
		}
	}