<?php

namespace App\Http\Controllers;

use App\Models\News;
use App\Models\Category;
use App\Models\Author;
use Illuminate\Support\Carbon;

class SitemapController extends Controller
{
    private string $base = '';

    public function __construct()
    {
        $this->base = rtrim(config('app.url', 'https://thehindu.com'), '/');
    }

    // ─── Sitemap Index ───────────────────────────────────────────────────────

    public function index()
    {
        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        $xml .= "  <sitemap><loc>{$this->base}/sitemap-pages.xml</loc></sitemap>\n";
        $xml .= "  <sitemap><loc>{$this->base}/sitemap-news.xml</loc></sitemap>\n";
        $xml .= "  <sitemap><loc>{$this->base}/sitemap-articles.xml</loc></sitemap>\n";
        $xml .= "  <sitemap><loc>{$this->base}/sitemap-categories.xml</loc></sitemap>\n";
        $xml .= "  <sitemap><loc>{$this->base}/sitemap-authors.xml</loc></sitemap>\n";
        $xml .= '</sitemapindex>';

        return response($xml, 200)->header('Content-Type', 'application/xml');
    }

    // ─── Google News Sitemap (last 2 days only) ──────────────────────────────

    public function news()
    {
        $articles = News::with('category')
            ->where('published_at', '>=', Carbon::now()->subDays(2))
            ->orderByDesc('published_at')
            ->get();

        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
        $xml .= '        xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">' . "\n";

        foreach ($articles as $article) {
            $catSlug = $article->category->slug ?? 'news';
            $url     = "{$this->base}/{$catSlug}/{$article->encode_title}";
            $pubDate = Carbon::parse($article->published_at)->toAtomString();
            $title   = htmlspecialchars($article->news_title, ENT_XML1, 'UTF-8');
            $lastmod = Carbon::parse($article->published_at)->toDateString();

            $xml .= "  <url>\n";
            $xml .= "    <loc>{$url}</loc>\n";
            $xml .= "    <news:news>\n";
            $xml .= "      <news:publication>\n";
            $xml .= "        <news:name>The Hindu</news:name>\n";
            $xml .= "        <news:language>en</news:language>\n";
            $xml .= "      </news:publication>\n";
            $xml .= "      <news:publication_date>{$pubDate}</news:publication_date>\n";
            $xml .= "      <news:title>{$title}</news:title>\n";
            $xml .= "    </news:news>\n";
            $xml .= "    <lastmod>{$lastmod}</lastmod>\n";
            $xml .= "  </url>\n";
        }

        $xml .= '</urlset>';

        return response($xml, 200)->header('Content-Type', 'application/xml');
    }

    // ─── Full Articles Sitemap ───────────────────────────────────────────────

    public function articles()
    {
        $articles = News::with('category')->orderByDesc('published_at')->get();

        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

        foreach ($articles as $article) {
            $catSlug = $article->category->slug ?? 'news';
            $url     = "{$this->base}/{$catSlug}/{$article->encode_title}";
            $lastmod = $article->published_at
                       ? Carbon::parse($article->published_at)->toDateString()
                       : Carbon::today()->toDateString();

            $xml .= "  <url>\n";
            $xml .= "    <loc>{$url}</loc>\n";
            $xml .= "    <lastmod>{$lastmod}</lastmod>\n";
            $xml .= "    <changefreq>monthly</changefreq>\n";
            $xml .= "    <priority>0.7</priority>\n";
            $xml .= "  </url>\n";
        }

        $xml .= '</urlset>';

        return response($xml, 200)->header('Content-Type', 'application/xml');
    }

    // ─── Static Pages Sitemap ────────────────────────────────────────────────

    public function pages()
    {
        $today = Carbon::today()->toDateString();

        $pages = [
            ['url' => $this->base,                     'lastmod' => $today,       'priority' => '1.0', 'changefreq' => 'daily'],
            ['url' => "{$this->base}/about",            'lastmod' => '2026-01-01', 'priority' => '0.5', 'changefreq' => 'yearly'],
            ['url' => "{$this->base}/privacy-policy",   'lastmod' => '2026-01-01', 'priority' => '0.3', 'changefreq' => 'yearly'],
        ];

        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

        foreach ($pages as $page) {
            $xml .= "  <url>\n";
            $xml .= "    <loc>{$page['url']}</loc>\n";
            $xml .= "    <lastmod>{$page['lastmod']}</lastmod>\n";
            $xml .= "    <changefreq>{$page['changefreq']}</changefreq>\n";
            $xml .= "    <priority>{$page['priority']}</priority>\n";
            $xml .= "  </url>\n";
        }

        $xml .= '</urlset>';

        return response($xml, 200)->header('Content-Type', 'application/xml');
    }

    // ─── Categories Sitemap ──────────────────────────────────────────────────

    public function categories()
    {
        $categories = Category::orderBy('category_name')->get();

        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

        foreach ($categories as $cat) {
            $xml .= "  <url>\n";
            $xml .= "    <loc>{$this->base}/category/{$cat->slug}</loc>\n";
            $xml .= "    <changefreq>daily</changefreq>\n";
            $xml .= "    <priority>0.8</priority>\n";
            $xml .= "  </url>\n";
        }

        $xml .= '</urlset>';

        return response($xml, 200)->header('Content-Type', 'application/xml');
    }

    // ─── Authors Sitemap ─────────────────────────────────────────────────────

    public function authors()
    {
        $authors = Author::all();

        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

        foreach ($authors as $author) {
            $xml .= "  <url>\n";
            $xml .= "    <loc>{$this->base}/author/{$author->slug}</loc>\n";
            $xml .= "    <changefreq>weekly</changefreq>\n";
            $xml .= "    <priority>0.6</priority>\n";
            $xml .= "  </url>\n";
        }

        $xml .= '</urlset>';

        return response($xml, 200)->header('Content-Type', 'application/xml');
    }
}
