<?php
if (!defined('access') || !access) die();

try {
	loadModuleConfigs('news');
	if (!mconfig('active')) throw new Exception(lang('error_47', true));

	$News = new News();
	$cachedNews = loadCache('news.cache');
	if (!is_array($cachedNews)) throw new Exception(lang('error_61'));

	if (config('language_switch_active', true) && !empty($_SESSION['language_display'])) {
		$News->setLanguage($_SESSION['language_display']);
	}

	$requestedId = isset($_REQUEST['subpage']) ? (int) $_REQUEST['subpage'] : 0;
	$single = $requestedId > 0 && $News->newsIdExists($requestedId);
	$typeLabels = array('anuncio'=>'Anuncio','actualizacion'=>'Actualización','evento'=>'Evento','mantenimiento'=>'Mantenimiento','comunidad'=>'Comunidad');
	$realmLabels = array('both'=>'Legado + Seasonal','legacy'=>'Legado','seasonal'=>'Seasonal');
	$items = array();

	foreach ($cachedNews as $article) {
		if (!is_array($article) || empty($article['news_id'])) continue;
		if ($single && (int)$article['news_id'] !== $requestedId) continue;
		$items[] = $article;
		if (!$single && count($items) >= max(1, (int)mconfig('news_list_limit'))) break;
	}

	echo '<section class="nex-news-studio-page">';
	echo '<header class="nex-news-public-hero"><span>CRÓNICAS DE NEXORA</span><h1>'.($single ? 'Detalle de la noticia' : 'Noticias del reino').'</h1><p>Actualizaciones, eventos y anuncios oficiales para avanzar con información clara.</p></header>';

	if ($single) {
		foreach ($items as $article) {
			$id = (int)$article['news_id'];
			$News->setId($id);
			$meta = function_exists('nexoraNewsStudioGet') ? nexoraNewsStudioGet($id) : array();
			$title = base64_decode($article['news_title'], true);
			if ($title === false) $title = $article['news_title'];
			$cover = trim((string)($meta['cover'] ?? ''));
			if ($cover !== '' && !filter_var($cover, FILTER_VALIDATE_URL)) $cover = __PATH_TEMPLATE_IMG__.ltrim($cover, '/');
			$type = $meta['type'] ?? 'anuncio';
			$realm = $meta['realm'] ?? 'both';
			echo '<article class="nex-news-public-article">';
			if ($cover !== '') echo '<div class="nex-news-public-article__cover"><img src="'.htmlspecialchars($cover, ENT_QUOTES, 'UTF-8').'" alt="'.htmlspecialchars($title, ENT_QUOTES, 'UTF-8').'"></div>';
			echo '<div class="nex-news-public-article__body"><div class="nex-news-public-tags"><span class="is-type">'.htmlspecialchars($typeLabels[$type] ?? 'Noticia', ENT_QUOTES, 'UTF-8').'</span><span>'.htmlspecialchars($realmLabels[$realm] ?? 'Nexora', ENT_QUOTES, 'UTF-8').'</span></div>';
			echo '<h2>'.htmlspecialchars($title, ENT_QUOTES, 'UTF-8').'</h2><p class="nex-news-public-meta">'.htmlspecialchars($article['news_author'], ENT_QUOTES, 'UTF-8').' · '.date('d/m/Y', $article['news_date']).'</p>';
			echo '<div class="nex-news-public-content">'.$News->LoadCachedNews().'</div><a class="nex-news-public-back" href="'.__BASE_URL__.'news/">← Volver a noticias</a></div></article>';
		}
	} else {
		echo '<div class="nex-news-public-grid">';
		foreach ($items as $article) {
			$id = (int)$article['news_id'];
			$News->setId($id);
			$meta = function_exists('nexoraNewsStudioGet') ? nexoraNewsStudioGet($id) : array();
			$title = base64_decode($article['news_title'], true);
			if ($title === false) $title = $article['news_title'];
			$content = trim(strip_tags($News->LoadCachedNews()));
			$excerpt = trim((string)($meta['excerpt'] ?? ''));
			if ($excerpt === '') $excerpt = function_exists('mb_substr') ? mb_substr($content, 0, 180, 'UTF-8') : substr($content, 0, 180);
			$cover = trim((string)($meta['cover'] ?? ''));
			if ($cover !== '' && !filter_var($cover, FILTER_VALIDATE_URL)) $cover = __PATH_TEMPLATE_IMG__.ltrim($cover, '/');
			$type = $meta['type'] ?? 'anuncio';
			$realm = $meta['realm'] ?? 'both';
			$url = __BASE_URL__.'news/'.$id.'/';
			echo '<article class="nex-news-public-card'.(!empty($meta['featured']) ? ' is-featured' : '').'">';
			if ($cover !== '') echo '<a class="nex-news-public-card__cover" href="'.htmlspecialchars($url, ENT_QUOTES, 'UTF-8').'"><img src="'.htmlspecialchars($cover, ENT_QUOTES, 'UTF-8').'" alt=""></a>';
			echo '<div class="nex-news-public-card__body"><div class="nex-news-public-tags"><span class="is-type">'.htmlspecialchars($typeLabels[$type] ?? 'Noticia', ENT_QUOTES, 'UTF-8').'</span><span>'.htmlspecialchars($realmLabels[$realm] ?? 'Nexora', ENT_QUOTES, 'UTF-8').'</span></div>';
			echo '<h2><a href="'.htmlspecialchars($url, ENT_QUOTES, 'UTF-8').'">'.htmlspecialchars($title, ENT_QUOTES, 'UTF-8').'</a></h2><p>'.htmlspecialchars($excerpt, ENT_QUOTES, 'UTF-8').'</p><footer><span>'.date('d/m/Y', $article['news_date']).'</span><a href="'.htmlspecialchars($url, ENT_QUOTES, 'UTF-8').'">Leer noticia →</a></footer></div></article>';
		}
		echo '</div>';
	}
	echo '</section>';
} catch (Exception $ex) {
	message('warning', $ex->getMessage());
}
