<?php

namespace App\Http\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Page;
use App\Models\BlogPost;
use App\Models\BlogCategory;
use App\Models\GalleryAlbum;
use App\Models\Event;
use App\Models\Download;

/**
 * ITSWEBER CMS – XML Sitemap Generator
 *
 * Generates a sitemap.xml with all published content for search engine indexing.
 */
class SitemapController extends Controller
{
    public function index(Request $request, array $params = []): void
    {
        $baseUrl = $this->getBaseUrl();

        $urls = [];

        // Homepage
        $urls[] = ['loc' => $baseUrl . '/', 'priority' => '1.0', 'changefreq' => 'daily'];

        // Published pages
        $pages = Page::published();
        foreach ($pages as $page) {
            if (!empty($page['is_homepage'])) {
                continue; // Already added as /
            }
            $urls[] = [
                'loc'        => $baseUrl . '/' . $page['slug'],
                'lastmod'    => $this->formatDate($page['updated_at'] ?? $page['created_at'] ?? ''),
                'priority'   => '0.8',
                'changefreq' => 'weekly',
            ];
        }

        // Blog listing
        $urls[] = ['loc' => $baseUrl . '/blog', 'priority' => '0.7', 'changefreq' => 'daily'];

        // Blog posts
        try {
            $posts = $this->app->db()->fetchAll(
                "SELECT slug, updated_at, published_at FROM iw_blog_posts WHERE status = 'published' ORDER BY published_at DESC"
            );
            foreach ($posts as $post) {
                $urls[] = [
                    'loc'        => $baseUrl . '/blog/' . $post['slug'],
                    'lastmod'    => $this->formatDate($post['updated_at'] ?? $post['published_at'] ?? ''),
                    'priority'   => '0.6',
                    'changefreq' => 'monthly',
                ];
            }
        } catch (\Exception $e) {
            // Blog table may not exist
        }

        // Gallery listing
        $urls[] = ['loc' => $baseUrl . '/gallery', 'priority' => '0.6', 'changefreq' => 'weekly'];

        // Gallery albums
        try {
            $albums = GalleryAlbum::visible();
            foreach ($albums as $album) {
                $urls[] = [
                    'loc'        => $baseUrl . '/gallery/' . $album['slug'],
                    'lastmod'    => $this->formatDate($album['updated_at'] ?? $album['created_at'] ?? ''),
                    'priority'   => '0.5',
                    'changefreq' => 'monthly',
                ];
            }
        } catch (\Exception $e) {
            // Gallery table may not exist
        }

        // Events listing
        $urls[] = ['loc' => $baseUrl . '/events', 'priority' => '0.6', 'changefreq' => 'weekly'];

        // Published events
        try {
            $events = $this->app->db()->fetchAll(
                "SELECT slug, updated_at FROM iw_events WHERE publish_status = 'published' ORDER BY start_date DESC"
            );
            foreach ($events as $event) {
                $urls[] = [
                    'loc'        => $baseUrl . '/events/' . $event['slug'],
                    'lastmod'    => $this->formatDate($event['updated_at'] ?? ''),
                    'priority'   => '0.5',
                    'changefreq' => 'monthly',
                ];
            }
        } catch (\Exception $e) {
            // Events table may not exist
        }

        // Downloads listing
        $urls[] = ['loc' => $baseUrl . '/download', 'priority' => '0.5', 'changefreq' => 'weekly'];

        // Published downloads
        try {
            $downloads = $this->app->db()->fetchAll(
                "SELECT slug, updated_at FROM iw_downloads WHERE status = 'published' ORDER BY created_at DESC"
            );
            foreach ($downloads as $dl) {
                $urls[] = [
                    'loc'        => $baseUrl . '/download/' . $dl['slug'],
                    'lastmod'    => $this->formatDate($dl['updated_at'] ?? ''),
                    'priority'   => '0.4',
                    'changefreq' => 'monthly',
                ];
            }
        } catch (\Exception $e) {
            // Downloads table may not exist
        }

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

        foreach ($urls as $url) {
            $xml .= "  <url>\n";
            $xml .= "    <loc>" . htmlspecialchars($url['loc'], ENT_XML1, 'UTF-8') . "</loc>\n";
            if (!empty($url['lastmod'])) {
                $xml .= "    <lastmod>" . $url['lastmod'] . "</lastmod>\n";
            }
            if (!empty($url['changefreq'])) {
                $xml .= "    <changefreq>" . $url['changefreq'] . "</changefreq>\n";
            }
            if (!empty($url['priority'])) {
                $xml .= "    <priority>" . $url['priority'] . "</priority>\n";
            }
            $xml .= "  </url>\n";
        }

        $xml .= "</urlset>\n";

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

    private function getBaseUrl(): string
    {
        $base = rtrim(config('base_url', ''), '/');
        if ($base === '') {
            $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
            $base   = $scheme . '://' . $host;
        }
        return $base;
    }

    private function formatDate(string $datetime): string
    {
        if (empty($datetime)) {
            return '';
        }
        try {
            return (new \DateTime($datetime))->format('Y-m-d');
        } catch (\Exception $e) {
            return '';
        }
    }
}
