<?php
$request_url = $_SERVER['REQUEST_URI'];
$language = NULL;
$content = NULL;
$id_url = NULL;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csrf_token']) && isset($_POST['filter'])) {
	$step_index = (int)($_POST['step_index'] ?? 0);
	$direction = $_POST['direction'] ?? null;

	if ($direction === 'next') {
		$step_index++;
	} elseif ($direction === 'back' && $step_index > 0) {
		$step_index--;
	}

	$query_params = [];
	foreach ($_POST as $key => $value) {
		if (str_starts_with($key, 'tags_') || str_starts_with($key, 'properties_')) {
			if (is_array($value)) {
				$sanitized = array_map(fn($v) => str_replace(',', '', trim($v)), $value);
				$query_params[$key] = implode(',', $sanitized);
			} else {
				$query_params[$key] = str_replace(',', '', trim($value));
			}
		}
	}
	
  if ($direction === 'back' && isset($_POST['step_keys'])) {
    $step_keys = explode(',', $_POST['step_keys']);
    foreach ($step_keys as $key) {
      unset($query_params[$key]);
    }
  }

	$redirect_url = strtok($_SERVER['REQUEST_URI'], '?');

	if (!empty($query_params)) {
		$query_string = implode('&', array_map(fn($k, $v) => $k.'='.$v, array_keys($query_params), $query_params));
		$redirect_url .= '?'.$query_string;
	}

	if ($step_index > 0) {
		$redirect_url .= (strpos($redirect_url, '?') === false ? '?' : '&') . 'step_index='.$step_index.'&direction='.$direction;
	}

	header("Location: ".$redirect_url);
	exit;
}


$regex_sub_filters = array();

#prüfen ob andere Sprache
preg_match("/\/([a-z-_0-9]*)\//", $request_url, $uri_parts);
if (isset($uri_parts[1]) && $uri_parts[1]){
	$sql_lang = "SELECT id FROM languages WHERE iso = :iso ";
	$result_lang = $conn->prepare($sql_lang);
	$result_lang->bindValue(':iso', $uri_parts[1], PDO::PARAM_STR);
	$result_lang->execute();
	if ($result_lang->rowCount()) {
		$language = $uri_parts[1];
		$request_url = str_replace_first("/".$uri_parts[1], '', $request_url);
	}
}

if ($c_languages && !$language && isset($default_language) && $default_language) {
	header("Location: /".$default_language."/", true, 301);
	exit;
}

if (!isset($language) OR !$language) {
	if (isset($default_language) && $default_language) $language = $default_language;
	else $language = 'de';
}

#Prüfen ob Content mit .html endet
preg_match("/\/([a-z-_0-9]*)?(\.html)/", $request_url, $uri_parts);
if (isset($uri_parts[1]) && $uri_parts[1]) {
	$id_url = $uri_parts[1];
	$request_url = str_replace_first($uri_parts[1].".html", '', $request_url);
	preg_match("/\/([a-z-_0-9]*)\/(.*)/", $request_url, $uri_parts);
	if (isset($uri_parts[1]) && $uri_parts[1]) $content = $uri_parts[1];
} else {
	#Prüfen ob Content mit / endet
	preg_match("/\/([a-z-_0-9]*)\/(.*)/", $request_url, $uri_parts);
	if (isset($uri_parts[1]) && $uri_parts[1]) $content = $uri_parts[1];
}

if (!empty($c_languages) && !empty($content)) {
	#Prüfen ob Content in der Sprache vorhanden
	$system_routes = [
		'newsletter',
		'cart',
		'checkout',
		'login',
		'overview',
		'register',
	];

	if (!in_array($content, $system_routes, true)) {
		$sql_tmp = "SELECT id FROM content_levels WHERE url = :url AND c_active = '1' AND language = :language ORDER BY sortorder LIMIT 1";
		$result_tmp = $conn->prepare($sql_tmp);
		$result_tmp->bindValue(':url', $content, PDO::PARAM_STR);
		$result_tmp->bindValue(':language', $language, PDO::PARAM_STR);
		$result_tmp->execute();
		if (!$result_tmp->rowCount()){
			if (isset($c_languages) && $c_languages){
				header("location: /".$language."/");
			} else {
				header("location: /");				
			}
		}
	}
}

if (!isset($content) || !$content) {
  if (isset($default_guidv4)) {
    $sql_tmp = "SELECT url FROM content_levels WHERE guidv4 = :guidv4";
    if ($c_languages) $sql_tmp.= " AND language = :language";
    $sql_tmp.= " LIMIT 1";

    $result_tmp = $conn->prepare($sql_tmp);
    $result_tmp->bindValue(':guidv4', $default_guidv4, PDO::PARAM_STR);
    if ($c_languages) $result_tmp->bindValue(':language', $language, PDO::PARAM_STR);
    $result_tmp->execute();

    if ($result_tmp->rowCount()) {
      $arr_tmp = $result_tmp->fetch();
      $content = $arr_tmp['url'];
    } else $content = 'home';
  } else $content = 'home';
}

#Auslesen von Typ-IDs oder ID
if (isset($content)){
	$content_data = array();
	$content_guidv4 = NULL;
	$sql_tmp = "SELECT guidv4 FROM content_levels WHERE url = :url AND c_active = '1' ORDER BY sortorder LIMIT 1";
	$result_tmp = $conn->prepare($sql_tmp);
	$result_tmp->bindValue(':url', $content, PDO::PARAM_STR);
	$result_tmp->execute();
	if ($result_tmp->rowCount()){
		$arr_tmp = $result_tmp->fetch();
		$content_guidv4 = $arr_tmp['guidv4'];
		$content_data = get_parent_levels('content_levels', $arr_tmp['guidv4']);
	}
}

if (isset($id_url) && isset($content)){
	if ($content === 'products') {
    $sql_tmp = "SELECT id_module AS id FROM products_content WHERE url = :url AND language = :language LIMIT 1";
    $result_tmp = $conn->prepare($sql_tmp);
    $result_tmp->bindValue(':url', $id_url, PDO::PARAM_STR);
    $result_tmp->bindValue(':language', $language, PDO::PARAM_STR);
    $result_tmp->execute();
    if ($result_tmp->rowCount()) {
      $arr_tmp = $result_tmp->fetch();
      $id = $arr_tmp['id'];
    }
  } else if (check_table($content)){
		$sql_tmp = "SELECT id FROM ".$content." WHERE url = :url AND language = :language LIMIT 1";
		$result_tmp = $conn->prepare($sql_tmp);
		$result_tmp->bindValue(':url', $id_url, PDO::PARAM_STR);
		$result_tmp->bindValue(':language', $language, PDO::PARAM_STR);
		$result_tmp->execute();
		if ($result_tmp->rowCount()){
			$arr_tmp = $result_tmp->fetch();
			$id = $arr_tmp['id'];
		}
	}
}