<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class RssFeedService
{
    public function parseAndRender($htmlWithShortcodes): string
    {
        return preg_replace_callback(
            '/\[RSSFEEDURL:\s*(.*?)\s+RSSFEEDCOUNT:(\d+)\]/i',
            function ($matches) {
                $url = trim($matches[1]);
                $count = (int)$matches[2];
                return $this->fetchFeedAsHtml($url, $count);
            },
            $htmlWithShortcodes
        );
    }

    private function fetchFeedAsHtml($feedUrl, $limit = 5): string
    {
        try {
            $response = Http::timeout(5)->get($feedUrl);
            if (!$response->ok()) return '<p>Unable to fetch RSS feed.</p>';

            $xml = simplexml_load_string($response->body(), "SimpleXMLElement", LIBXML_NOCDATA);
            $json = json_decode(json_encode($xml), true);
            $items = $json['channel']['item'] ?? [];

            $html = '<div style="margin-top:20px;">';

            foreach (array_slice($items, 0, $limit) as $item) {
                $title = $item['title'] ?? '';
                $link = $item['link'] ?? '#';
                $summary = strip_tags($item['description'] ?? '');
                $date = $item['pubDate'] ?? '';
                $image = $this->extractImage($item);

                $html .= "<div style='margin-bottom:20px;'>";
                if ($image) {
                    $html .= "<img src='{$image}' style='max-width:100%; height:auto; margin-bottom:10px;'/>";
                }
                $html .= "<h3 style='margin:5px 0;'><a href='{$link}' target='_blank' style='color:#333; text-decoration:none;'>{$title}</a></h3>";
                $html .= "<small style='color:#666;'>{$date}</small>";
                $html .= "<p style='color:#444;'>{$summary}</p>";
                $html .= "</div><hr>";
            }

            $html .= '</div>';
            return $html;
        } catch (\Exception $e) {
            \Log::error('RSS Feed Error: ' . $e->getMessage());
            return '<p>Feed load failed.</p>';
        }
    }

    private function extractImage($item): ?string
    {
        if (!empty($item['description']) && preg_match('/<img.*?src=["\'](.*?)["\']/', $item['description'], $matches)) {
            return $matches[1];
        }

        if (!empty($item['media:content']['@attributes']['url'])) {
            return $item['media:content']['@attributes']['url'];
        }

        if (!empty($item['enclosure']['@attributes']['url'])) {
            return $item['enclosure']['@attributes']['url'];
        }

        return null;
    }
}
