<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class SitemapParserService
{
    public function parse(string $xmlContent): array
    {
        $urls = [];
        $this->extractUrls($xmlContent, $urls);

        return array_values(array_unique($urls));
    }

    public function fetchAndParse(string $url): array
    {
        $xmlContent = $this->fetchUrl($url);

        return $this->parse($xmlContent);
    }

    public function fetchUrl(string $url): string
    {
        $response = Http::timeout(30)->get($url);

        if (!$response->successful()) {
            throw new \RuntimeException("Failed to fetch sitemap from {$url}: HTTP {$response->status()}");
        }

        return $response->body();
    }

    private function extractUrls(string $xmlContent, array &$urls): void
    {
        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($xmlContent);

        if ($xml === false) {
            throw new \RuntimeException('Failed to parse XML: ' . libxml_get_last_error()?->message);
        }

        $xml->registerXPathNamespace('sm', 'http://www.sitemaps.org/schemas/sitemap/0.9');

        // Check if this is a sitemap index
        $sitemaps = $xml->xpath('//sm:sitemap/sm:loc');
        if (!empty($sitemaps)) {
            foreach ($sitemaps as $loc) {
                $childUrl = trim((string) $loc);
                if (empty($childUrl)) {
                    continue;
                }

                try {
                    $childXml = $this->fetchUrl($childUrl);
                    $this->extractUrls($childXml, $urls);
                } catch (\Exception $e) {
                    // Skip unreadable child sitemaps
                    continue;
                }
            }

            return;
        }

        // Standard sitemap - extract <url><loc> entries
        $entries = $xml->xpath('//sm:url/sm:loc');
        foreach ($entries as $loc) {
            $url = trim((string) $loc);
            if (!empty($url)) {
                $urls[] = $url;
            }
        }
    }
}
