<?php

namespace App\Http\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Models\BlogPost;

/**
 * ITSWEBER CMS – RSS 2.0 Feed
 *
 * Generates an RSS 2.0 XML feed for published blog posts.
 */
class RssController extends Controller
{
    public function blogFeed(Request $request, array $params = []): void
    {
        $baseUrl = rtrim(setting('site_url', $this->detectBaseUrl()), '/');
        $siteName = setting('site_name', 'ITSWEBER CMS');
        $siteDesc = setting('site_description', '');
        $lang     = setting('system_language', 'de');

        $posts = BlogPost::published(20, 0);

        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">' . "\n";
        $xml .= '<channel>' . "\n";
        $xml .= '  <title>' . $this->esc($siteName) . '</title>' . "\n";
        $xml .= '  <link>' . $this->esc($baseUrl) . '</link>' . "\n";
        $xml .= '  <description>' . $this->esc($siteDesc) . '</description>' . "\n";
        $xml .= '  <language>' . $this->esc($lang) . '</language>' . "\n";
        $xml .= '  <atom:link href="' . $this->esc($baseUrl . '/rss') . '" rel="self" type="application/rss+xml"/>' . "\n";

        if (!empty($posts)) {
            $xml .= '  <lastBuildDate>' . $this->rfc822($posts[0]['published_at'] ?? $posts[0]['created_at']) . '</lastBuildDate>' . "\n";
        }

        foreach ($posts as $post) {
            $link = $baseUrl . '/blog/' . $post['slug'];
            $desc = $this->truncateHtml($post['content'] ?? '', 300);
            $date = $this->rfc822($post['published_at'] ?? $post['created_at']);

            $xml .= '  <item>' . "\n";
            $xml .= '    <title>' . $this->esc($post['title']) . '</title>' . "\n";
            $xml .= '    <link>' . $this->esc($link) . '</link>' . "\n";
            $xml .= '    <guid isPermaLink="true">' . $this->esc($link) . '</guid>' . "\n";
            $xml .= '    <description>' . $this->esc($desc) . '</description>' . "\n";
            $xml .= '    <pubDate>' . $date . '</pubDate>' . "\n";

            if (!empty($post['category_name'])) {
                $xml .= '    <category>' . $this->esc($post['category_name']) . '</category>' . "\n";
            }
            if (!empty($post['author_name'])) {
                $xml .= '    <author>' . $this->esc($post['author_name']) . '</author>' . "\n";
            }

            $xml .= '  </item>' . "\n";
        }

        $xml .= '</channel>' . "\n";
        $xml .= '</rss>';

        header('Content-Type: application/rss+xml; charset=UTF-8');
        echo $xml;
        exit;
    }

    private function esc(string $text): string
    {
        return htmlspecialchars($text, ENT_XML1 | ENT_QUOTES, 'UTF-8');
    }

    private function rfc822(string $datetime): string
    {
        $ts = strtotime($datetime);
        return $ts ? date(\DateTimeInterface::RSS, $ts) : '';
    }

    private function truncateHtml(string $html, int $maxLen): string
    {
        $text = strip_tags($html);
        if (mb_strlen($text) <= $maxLen) {
            return $text;
        }
        return mb_substr($text, 0, $maxLen) . '…';
    }

    private function detectBaseUrl(): string
    {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
        return $scheme . '://' . $host;
    }
}
