<?php
function input_in($data, $option = ''){
	switch ($option){
		case 'bool':
			return filter_var($data, FILTER_VALIDATE_BOOLEAN);
			break;
			
		case 'text':
			return trim(nl2br(strip_tags($data)));
			break;
			
		case 'string':
			return trim(strip_tags($data));
			break;
			
		case 'url':
			return trim(strip_tags(rawurldecode($data)));
			break;
			
		case 'int': 
			if(settype($data, 'integer')) return $data;
			else return 0;
			break;
			
		case 'int+': 
			if(settype($data, 'int')) return abs($data);
			else return 0;
			break;
			
		case 'arr': 
			$arr_new = array();
			foreach ($data AS $key => $value){
				$arr_new[input_in($key)] = input_in($value);	        
			}
			return $arr_new;
			break;
			
		case 'arr_multi': 
			$arr_new = array();
			foreach ($data AS $key => $value){
				if (is_array($value)) $arr_new[input_in($key)]= input_in($value, 'arr_multi');	 
				else $arr_new[input_in($key)]= input_in($value);	        
			}
			return $arr_new;
			break;
			
		case 'arr_int': 
			$arr_new = array();
			foreach ($data AS $key => $value){
				$arr_new[input_in($key)] = input_in($value, 'int');	        
			}
			return $arr_new;
			break;
			
		case 'arr_int+': 
			$arr_new = array();
			foreach ($data AS $key => $value){
				$arr_new[input_in($key)] = input_in($value, 'int+');	     
			}
			return $arr_new;
			break;
			
		case 'float_de':
			if(settype($data, 'float')) return str_replace(',', '.', $data);
			break;
			
		case 'float':
			if(settype($data, 'float')) return $data;
			break;
			
		default: 
			if (!$data) $data = ''; 
			return trim(strip_tags($data));
	}
}

function input_out($data, $option = ''){
	switch ($option){
		case 'text_admin':
			if (!$data) $data = '';
			return $data;
			break;
			
		case 'text':
			if (!$data) $data = '';
			return str_replace('<br />', '', str_replace('<br>', '\n', $data));
			break;
			
		case 'string':
			if (!$data) $data = '';
			return htmlentities($data);
			break;
			
		case 'int': 
			if(settype($data, 'integer')) return $data;
			else return 0;
			break;
			
		case 'float_de':
			if(settype($data, 'float')) return number_format($data, 2, ',', '.');
			break;
			
		case 'float':
			if(settype($data, 'float')) return  number_format($data, 2, '.', '');
			break;
			
		case 'num_float':
			if(settype($data, 'float')) return  number_format($data, 5, '.', '');
			break;
			
		default:
			if (!$data) $data = '';
			return htmlentities($data);
	}
}

function build_url_with(array $overrides): string {
  $qs = $_GET;
  foreach ($overrides AS $k => $v) {
    if ($v === null) unset($qs[$k]);
    else $qs[$k] = $v;
  }
  $base = strtok($_SERVER['REQUEST_URI'], '?');
  return $base.'?'.http_build_query($qs);
}

function setNext(?string $next): void {
  $n = normalizeNext($next);
  if ($n !== null) $_SESSION['next'] = $n;
}

function getNext(): ?string {
  return $_SESSION['next'] ?? null;
}

function clearNext(): void {
  unset($_SESSION['next']);
}

function appendNext(string $url): string {
  $n = getNext();
  if (!$n) return $url;
  $sep = (strpos($url, '?') === false) ? '?' : '&';
  return $url.$sep.'next='.rawurlencode($n);
}

function consumeNextOr(string $fallback): string {
  $n = getNext();
  clearNext();
  return $n ?: $fallback;
}

function normalizeNext(?string $n): ?string {
  $n = (string)$n;
  if ($n === '') return null;
  if (preg_match('~https?://|[\r\n]~i', $n)) return null;
  return $n;
}

function fvalue(string $name, $default = '') {
  $val = $_POST[$name] ?? $default;
  return htmlspecialchars((string)$val, ENT_QUOTES, 'UTF-8');
}

function fvalue_checked(string $name, string $value, bool $default = false): string {
  $current = $_POST[$name] ?? null;
  if ($current === null && $default) return 'checked';
  return ((string)$current === (string)$value) ? 'checked' : '';
}

function fvalue_selected(string $name, string $value, bool $default = false): string {
  $current = $_POST[$name] ?? null;
  if ($current === null && $default) return 'selected';
  return ((string)$current === (string)$value) ? 'selected' : '';
}

function fvalue_checked_multi(string $name, string $value, bool $default = false): string {
  $current = $_POST[$name] ?? [];
  if (!is_array($current)) $current = [$current];
  if (empty($current) && $default) return 'checked';
  return in_array((string)$value, $current, true) ? 'checked' : '';
}

function return_months(): array {
    return [
        1  => defined('LABEL_JANUARY')   ? LABEL_JANUARY   : 'LABEL_JANUARY',
        2  => defined('LABEL_FEBRUARY')  ? LABEL_FEBRUARY  : 'LABEL_FEBRUARY',
        3  => defined('LABEL_MARCH')     ? LABEL_MARCH     : 'LABEL_MARCH',
        4  => defined('LABEL_APRIL')     ? LABEL_APRIL     : 'LABEL_APRIL',
        5  => defined('LABEL_MAY')       ? LABEL_MAY       : 'LABEL_MAY',
        6  => defined('LABEL_JUNE')      ? LABEL_JUNE      : 'LABEL_JUNE',
        7  => defined('LABEL_JULY')      ? LABEL_JULY      : 'LABEL_JULY',
        8  => defined('LABEL_AUGUST')    ? LABEL_AUGUST    : 'LABEL_AUGUST',
        9  => defined('LABEL_SEPTEMBER') ? LABEL_SEPTEMBER : 'LABEL_SEPTEMBER',
        10 => defined('LABEL_OCTOBER')   ? LABEL_OCTOBER   : 'LABEL_OCTOBER',
        11 => defined('LABEL_NOVEMBER')  ? LABEL_NOVEMBER  : 'LABEL_NOVEMBER',
        12 => defined('LABEL_DECEMBER')  ? LABEL_DECEMBER  : 'LABEL_DECEMBER',
    ];
}

function build_timestamp(string $key, array $src): array {
  $day = $src[$key.'_day']   ?? null;
  $month = $src[$key.'_month'] ?? null;
  $year = $src[$key.'_year']  ?? null;

  if ($day !== null || $month !== null || $year !== null) {
    $day = (int)($day ?: 0);
    $month = (int)($month ?: 0);
    $year = (int)($year ?: 0);
    if ($day <= 0 || $month <= 0 || $year <= 0 || $year < 1900 || $year > 2100) {
      return [null, $key.'_invalid'];
    }
    if (!checkdate($month, $day, $year)) return [null, $key.'_invalid'];
    $timestamp = mktime(0, 0, 0, $month, $day, $year);
    return [$timestamp, null];
  }

  if (isset($src[$key]) && $src[$key] !== '') {
    $raw = trim($src[$key]);
    $parts = [
      'Y-m-d', 'd.m.Y', 'm/d/Y', 'd/m/Y', 'Y.m.d',
      DATE_ATOM, DATE_RFC3339, 'Y-m-d H:i:s'
    ];
    foreach ($parts AS $format) {
      $datetime = DateTime::createFromFormat($format, $raw);
      if ($datetime instanceof DateTime) {
        $datetime->setTime(0,0,0);
        return [$datetime->getTimestamp(), null];
      }
    }
    
    $guess = strtotime($raw);
    if ($guess !== false) {
      return [strtotime(date('Y-m-d', $guess)), null];
    }
    return [null, $key.'_invalid'];
  }

  return [null, null];
}

function normalize_timestamp_post(string $key, array &$post, bool $required): ?string {
  [$timestamp, $error] = build_timestamp($key, $post);
  if ($error) return $error;
  if ($timestamp !== null) {
    $post[$key] = $timestamp;
  } else {
    if ($required) return $key.'_required';
    unset($post[$key]);
  }
  unset($post[$key.'_day'], $post[$key.'_month'], $post[$key.'_year']);
  return null;
}

function preprocess_timestamps(array &$post, array $rules): array {
  $errs = [];
  foreach ($rules as $field => $cfg) {
    $dt = $cfg['dtype'] ?? 'string';
    if ($dt !== 'timestamp') continue;
    $required = !empty($cfg['required']);
    $err = normalize_timestamp_post($field, $post, $required);
    if ($err === $field.'_invalid')  $errs[$field] = 'invalid';
    if ($err === $field.'_required') $errs[$field] = 'required';
  }
  return $errs;
}


function print_seo(){
	global $seo_data;
	
	if (!empty($seo_data['title'])) {
		print "<title>".htmlspecialchars($seo_data['title'])."</title>\n";
	}
	if (!empty($seo_data['description'])) {
		print "<meta name='description' content='".htmlspecialchars($seo_data['description'])."'/>\n";
	}
	if (!empty($seo_data['robots'])) {
		print "<meta name='robots' content='".htmlspecialchars($seo_data['robots'])."'/>\n";
	}
	if (!empty($seo_data['canonical'])) {
		print "<link rel='canonical' href='".htmlspecialchars($seo_data['canonical'])."'/>\n";
	}
	if (!empty($seo_data['prev'])) {
		print "<link rel='prev' href='".htmlspecialchars($seo_data['prev'])."' />\n";
	}
	if (!empty($seo_data['next'])) {
		print "<link rel='next' href='".htmlspecialchars($seo_data['next'])."' />\n";
	}
	if (!empty($seo_data['hreflang']) && count(array_filter($seo_data['hreflang'])) > 1) {
		foreach ($seo_data['hreflang'] as $lang => $url) {
			if ($url) {
				print "<link rel='alternate' hreflang='".htmlspecialchars($lang)."' href='".htmlspecialchars($url)."'/>\n";
			}
		}
	}
	
	
	if (!empty($seo_data['title'])) {
		print "<meta property='og:title' content='".htmlspecialchars($seo_data['title'])."'/>\n";
	}
	if (!empty($seo_data['description'])) {
		print "<meta property='og:description' content='".htmlspecialchars($seo_data['description'])."'/>\n";
	}
	if (!empty($seo_data['canonical'])) {
		print "<meta property='og:url' content='".htmlspecialchars($seo_data['canonical'])."'/>\n";
	}
	print "<meta property='og:type' content='website'/>\n";

	if (!empty($seo_data['image'])) {
		print "<meta property='og:image' content='".htmlspecialchars($seo_data['image'])."'/>\n";
	}

	$ld = [
		"@context" => "https://schema.org",
		"@type" => "WebPage"
	];
	
	if (!empty($seo_data['title'])) $ld["name"] = $seo_data['title'];
	if (!empty($seo_data['description'])) $ld["description"] = $seo_data['description'];
	if (!empty($seo_data['canonical'])) $ld["url"] = $seo_data['canonical'];
	if (!empty($seo_data['image'])) $ld["image"] = $seo_data['image'];
	
	print "<script type='application/ld+json'>".json_encode($ld, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."</script>\n";
}