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

	function _get($parameter) {
    if (isset($_GET[$parameter])) {
      return strip_tags(trim(addslashes($_GET[$parameter])));
    }
    else {
      return false;
    }
  }
	
	function api(): Api
	{
		static $api = null;
		if ($api === null) {
			$api = new Api;
		}
		
		return $api;
	}
	
  /**
   * @return Response
   */
  function response(): Response
  {
    return Router::response();
  }
  
  /**
   * @return 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));
	}

/**
 * Validate data
 * @param array $data
 * @return array
 */
  function validate(array $data = []): array {
    $validator = new Validator;
    
    $validation = $validator->validate($_POST + $_FILES, $data);
    if ($validation->fails()) {
      api()->badRequest('VALIDATION', $validation->errors()->all());
    }
    return [];
  }
  
  /**
   * Get Database instance
   * @return PDO
   */
  function db(): PDO
  {
    global $db;
    return $db;
  }
  
  /**
   * Get settings
   * @param string $key
   * @param string|null $default
   * @return string|null
   */
  function settings(string $key, string $default = null): ?string
  {
    global $readSettings;
    if (isset($readSettings[$key])) {
      return $readSettings[$key];
    }
    
    return $default;
  }
	
	/**
	 * Get module settings
	 * @param string $module_slug
	 * @param string $key
	 * @param string|null $default
	 * @return string|null
	 */
	function moduleSettings(string $module_slug, string $key, string $default = null): ?string
	{
		static $settings = null;
		
		if (is_null($settings)) {
			$modules = db()->query("SELECT * FROM Modules");
			$modules = $modules->fetchAll(PDO::FETCH_ASSOC);
			
			$moduleSettings = db()->query("SELECT * FROM ModuleSettings");
			$moduleSettings = $moduleSettings->fetchAll(PDO::FETCH_ASSOC);
			
			// create settings array 'module_slug' => ['name' => 'value']
			$settings = [];
			foreach ($modules as $module) {
				$settings[$module['slug']] = [];
				foreach ($moduleSettings as $setting) {
					if ($setting['moduleID'] == $module['id']) {
						$settings[$module['slug']][$setting['name']] = $setting['value'];
					}
				}
			}
		}
		
		return $settings[$module_slug][$key] ?? $default;
	}

  function updateSetting($name, $value) {
    global $db;
    $updateSettings = $db->prepare("UPDATE Settings SET value = ? WHERE name = ?");
    return $updateSettings->execute(array($value, $name));
  }

  function updateSettings($data = []) {
    global $db;
    foreach ($data as $key => $value) {
      $updateSettings = $db->prepare("UPDATE Settings SET value = ? WHERE name = ?");
      $updateSettings->execute(array($value, $key));
    }
  }
  
  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 checkEmail($email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
      return false;
    }
    else {
      return true;
    }
  }
  
  function moduleIsDisabled($module) {
    global $readModules;
    
    foreach ($readModules as $readModule) {
      if ($readModule["slug"] == $module) {
        return $readModule["isEnabled"] == 0;
      }
    }
    return false;
  }
  
  function checkPassword($type, $password, $hash) {
    if ($type == 1)
      return checkSHA256($password, $hash);
    elseif ($type == 2)
      return md5($password) == $hash;
    elseif ($type == 3)
      return password_verify($password, $hash);
    else
      return false;
  }
	
	function createPassword($type, $password) {
		if ($type == 1)
			return createSHA256($password);
		elseif ($type == 2)
			return md5($password);
		elseif ($type == 3)
			return password_hash($password, PASSWORD_BCRYPT);
		else
			return null;
	}

  function formatMoney($money, $removeZero = false) {
    $formattedMoney = number_format($money, 2, '.', ',');

    if ($removeZero && substr($formattedMoney, -3) == ".00")
      $formattedMoney = substr($formattedMoney, 0, -3);

    return $formattedMoney;
  }

  function money($money, $currency, $force = false) {
    if (moduleSettings('store', 'isCreditRequiredOnPurchase') == 1 && !$force)
      return credits($money);

    $money = formatMoney($money, moduleSettings('store', 'removeMoneyZeroDecimal') == 1);

    return $currency["prefix"].$money.$currency["suffix"];
  }

  function credits($credits) {
    $credits = formatMoney($credits, moduleSettings('store', 'removeMoneyZeroDecimal') == 1);

    if (moduleSettings('credit', 'creditText') != "" && moduleSettings('credit', 'creditText') != null)
      return $credits." ".moduleSettings('credit', 'creditText');

    return "$credits credits";
  }

  function createDuration($duration = 0) {
    return date("Y-m-d H:i:s", (strtotime(date("Y-m-d H:i:s")) + ($duration * 86400)));
  }
  function getDuration($expiryDate = '1000-01-01 00:00:00') {
    return max(round((strtotime($expiryDate) - strtotime(date("Y-m-d H:i:s"))) / 86400), 0);
  }

  function getIP() {
    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 websiteUrl($path = null) {
		return settings('websiteURL') . $path ?? "";
	}
	
	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 datetime() {
		return date("Y-m-d H:i:s");
	}
	
	function validate_username($username): bool
	{
		$regex = settings('usernameRegex');
		return preg_match("/$regex/", $username) === 1;
	}