<?php

/**
 * Vvveb
 *
 * Copyright (C) 2020  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\System;

class Routes {
	private static $inst = null;

	private static $routes = null;

	private static $urls = null;

	public static function init() {
		self :: $routes = include DIR_ROOT . '/config/routes.php';

		foreach (self :: $routes as $route => $urls) {
			foreach ($urls as $url) {
				//escape / for regex
				$url = str_replace('/', '\/', $url);
				//numeric
				$url = preg_replace('/#(\w+)#/', '(?<$1>\d+)', $url);
				//string
				$url = preg_replace('/{(\w+)}/', '(?<$1>[^$\/]+)', $url);
				//$parameters[0] = $url;
				self :: $urls[$url] = $route;
			}
		}
	}

	public static function match($url) {
		//var_dump($url);
		if (! self :: $routes) {
			self :: init();
		}

		foreach (self :: $urls as $pattern => $route) {
			if ($url == $pattern || preg_match('/^' . $pattern . '$/', $url, $matches)) {
				$parameters = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);

				$parameters['route'] = $route;
				//var_dump($route);
				//var_dump($parameters);
				return $parameters;
			}
		}

		return false;
	}

	public static function get($route) {
	}

	public static function url($route, $parameters) {
		if (! self :: $routes) {
			self :: init();
		}

		if (isset(self :: $routes[$route])) {
			$data    = self :: $routes[$route];
			$pattern = $data[0];

			$missing = false;
			$url     = preg_replace_callback('/{(\w+)}|#(\w+)#/', function ($matches) use ($parameters, &$missing) {
				$var = $matches[1];

				if (isset($parameters[$var])) {
					return $parameters[$var];
				} else {
					$missing = true;
				}

				return '';
			}, $pattern);

			if ($missing) {
				return '/?route=' . $route . '&' . (is_array($parameters) ? http_build_query($parameters) : '');
			} else {
				return $url;
			}
		}
	}
}
