<?php

/**
 * @package     Joomla.Site
 * @subpackage  com_formea
 *
 * @copyright   Copyright (C) 2010-2025 Feseur Sdn Bhd. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @version     1.3.0
 */

namespace Joomla\Component\Formea\Site\Service;

defined('_JEXEC') or die;

use Joomla\CMS\Component\Router\RouterView;
use Joomla\CMS\Component\Router\Rules\NomenuRules;
use function call_user_func_array;
use function is_callable;

class FormeaNoMenuRules extends NomenuRules
{
	/**
	 * Router this rule belongs to
	 *
	 * @var RouterView
	 * @since 3.4
	 */
	protected $router;

	/**
	 * Class constructor.
	 *
	 * @param   RouterView  $router  Router this rule belongs to
	 *
	 * @since   3.4
	 */
	public function __construct(RouterView $router)
	{
		$this->router = $router;
	}

	/**
	 * Parse a menu-less URL
	 *
	 * @param   array  &$segments  The URL segments to parse
	 * @param   array  &$vars      The vars that result from the segments
	 *
	 * @return  void
	 *
	 * @since   3.4
	 */
	public function parse(&$segments, &$vars)
	{

		$vars = array();

		return $vars;
	}

	/**
	 * Build a menu-less URL
	 *
	 * @param   array  &$query     The vars that should be converted
	 * @param   array  &$segments  The URL segments to create
	 *
	 * @return  void
	 *
	 * @since   3.4
	 */
	public function build(&$query, &$segments)
	{
		$menu_found = false;

		if (isset($query['Itemid'])) {
			$item = $this->router->menu->getItem($query['Itemid']);

			if (
				!isset($query['option'])
				|| ($item && isset($item->query['option']) && $item->query['option'] === $query['option'])
			) {
				$menu_found = true;
			}
		}


		if (!$menu_found && isset($query['view'])) {
			$views = $this->router->getViews();
			if (isset($views[$query['view']])) {
				$view       = $views[$query['view']];
				$segments[] = $query['view'];

				if ($view->key && isset($query[$view->key])) {
					if (is_callable([$this->router, 'get' . ucfirst($view->name) . 'Segment'])) {
						$result = call_user_func_array([$this->router, 'get' . ucfirst($view->name) . 'Segment'], [$query[$view->key], $query]);

						if ($view->nestable) {
							array_pop($result);

							while (count($result)) {
								$segments[] = str_replace(':', '-', array_pop($result));
							}
						} else {
							$segments[] = str_replace(':', '-', array_pop($result));
						}
					} else {
						$segments[] = str_replace(':', '-', $query[$view->key]);
					}

					unset($query[$views[$query['view']]->key]);
				}

				unset($query['view']);
			}
		}
		if (isset($query['alias'])) {
			unset($query['alias']);
		}
		if (isset($query['categories'])) {
			//var_dump();
			unset($query['categories']);
			//var_dump($segments);die;
		}
	}
}
