<?php

/**
 * Vvveb
 *
 * Copyright (C) 2022  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Vvveb;



/**
 * Generate a URL from a route name or array of parameters.
 *
 * @param string|array<string,mixed> $parameters      Route name or URL parameters
 * @param array<string,mixed>|bool   $mergeParameters Parameters to merge with existing URL parameters
 * @param bool                       $useCurrentUrl   Whether to use the current URL as base
 *
 * @return string The generated URL
 */

function url(string|array $parameters, array|bool $mergeParameters = false, bool $useCurrentUrl = true): string {
	if (is_string($parameters) && $parameters) {
		$result = '';

		if (isset($mergeParameters['scheme'])) {
			$result .= $mergeParameters['scheme'] . ':';
			unset($mergeParameters['scheme']);
		}

		if (isset($mergeParameters['host'])) {
			$result .= '//' . \Vvveb\System\Sites::url($mergeParameters['host']);
			unset($mergeParameters['host']);

			if (isset($mergeParameters['scheme'])) {
				$result = $mergeParameters['scheme'] . ":$result";
				unset($mergeParameters['scheme']);
			}
		}

		$path = $mergeParameters['path'] ?? SITE_PATH;

		$url = System\Routes::url($parameters, $mergeParameters);
		$result .= (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . $path . ($url ?? '');
	} else {
		static $url       = '';
		static $urlParams = [];

		if ($useCurrentUrl && ! $url) {
			$url = parse_url($_SERVER['REQUEST_URI'] ?? '');

			if (isset($url['query'])) {
				parse_str($url['query'], $urlParams);
			}
		}

		if (! is_array($parameters)) {
			$parameters = [];
		}

		if ($mergeParameters) {
			if (is_array($mergeParameters)) {
				$mergeParameters = array_merge($urlParams, $mergeParameters);
			} else {
				$mergeParameters = $urlParams;
			}

			if (is_array($mergeParameters)) {
				$parameters = array_merge($mergeParameters, $parameters);
			}
		}

		$result = '';
		$path = $parameters['path'] ?? SITE_PATH;

		if (isset($parameters['host'])) {
			$result .= '//' . \Vvveb\System\Sites::url($parameters['host']);
			unset($parameters['host']);

			if (isset($parameters['scheme'])) {
				$result = $parameters['scheme'] . ":$result";
				unset($parameters['scheme']);
			}
		} else {
			if (! $useCurrentUrl) {
				$result .= (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . $path;
			}
		}

		$result .= ($useCurrentUrl ? $url['path'] ?? '' : '') . ($parameters ? '?' . urldecode(http_build_query($parameters)) : '');
	}

	return $result;
}



/**
 * Get the current template name.
 *
 * @return string|false|null Template name, or false/null if not set
 */

function getCurrentTemplate(): string|false|null {
	return System\Core\View :: getInstance()->template();
}



/**
 * Get route data for a given URL.
 *
 * @param string $url The URL to look up
 *
 * @return array|false Route data array, or false if not found
 */

function getUrlRoute(string $url): array|false {
	$urlData = \Vvveb\System\Routes::getUrlData($url);

	return $urlData;
}



/**
 * Get the current request URI.
 *
 * @return string Current request URI
 */

function getCurrentUrl(): string {
	return $_SERVER['REQUEST_URI'] ?? '';
}



/**
 * Get the admin path URL.
 *
 * @return string Admin path with leading and trailing slashes
 */

function adminPath(): string {
	return (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . '/' . \Vvveb\config('admin.path', 'admin') . '/';
}



/**
 * Get the public URL path.
 *
 * @return string Public URL path
 */

function publicUrlPath(): string {
	$public_path = PUBLIC_PATH;

	if (V_SUBDIR_INSTALL) {
		$public_path = str_replace(V_SUBDIR_INSTALL, '', $public_path);
	}

	if ($public_path == '/public/' || $public_path == '/public/admin/') {
		return PUBLIC_PATH;
	} else {
		return '/';
	}
}



/**
 * Get the current theme URL path.
 *
 * @return string Theme URL path
 */

function themeUrlPath(): string {
	$theme = \Vvveb\System\Core\View::getInstance()->getTheme();
	//$theme = 'landing';
	if (APP == 'app') {
		$path = PUBLIC_THEME_PATH . 'themes/' . $theme . '/';
	} else {
		$path = PUBLIC_THEME_PATH . $theme . '/';
	}

	return $path;
}



/**
 * Return current module name.
 *
 * @return string
 */

function getModuleName(): string {
	return strtolower(\Vvveb\System\Core\FrontController::getModuleName());
}



/**
 * Return current action name.
 *
 * @return string
 */

function getActionName(): string {
	return strtolower(\Vvveb\System\Core\FrontController::getActionName());
}



/**
 * Check if the page is loaded in the editor.
 *
 * @return boolean
 */

function isEditor(): bool {
	return isset($_GET['r']);
}


/**
 * Checks if the current user is an admin.
 *
 * @return bool True if the current user is an admin, false otherwise.
 */

function isAdmin(): bool {
	return System\User\Admin::current() ? true : false;
}



/**
 * Get a request parameter value.
 *
 * @param string $key The request parameter key.
 *
 * @return mixed The parameter value, or false if not set.
 */

function get(string $key): mixed {
	return System\Core\Request::getInstance()->get[$key] ?? false;
}



/**
 * Get an environment variable value.
 *
 * @param string $key     Environment variable name
 * @param mixed  $default Default value if variable is not set
 *
 * @return mixed Environment variable value or default
 */

function env(string $key, mixed $default = null): mixed {
	$env = getenv($key);

	if ($env === false) {
		return $default;
	} else {
		return $env;
	}
}

