<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class SitemapController extends Controller
{
    /**
     * Single clean sitemap — core pages only (no dynamic bulk URLs).
     */
    public function index(Request $request): Response
    {
        $baseUrl = rtrim(config('app.url'), '/');
        $lastmod = now()->toAtomString();

        $pages = [
            ['loc' => $baseUrl . '/', 'priority' => '1.0', 'changefreq' => 'daily'],
            ['loc' => $baseUrl . '/pages/about', 'priority' => '0.9', 'changefreq' => 'weekly'],
            ['loc' => $baseUrl . '/classes', 'priority' => '0.9', 'changefreq' => 'daily'],
            ['loc' => $baseUrl . '/contact', 'priority' => '0.8', 'changefreq' => 'monthly'],
            ['loc' => $baseUrl . '/blog', 'priority' => '0.7', 'changefreq' => 'weekly'],
            ['loc' => $baseUrl . '/pages/privacy_policy', 'priority' => '0.3', 'changefreq' => 'yearly'],
            ['loc' => $baseUrl . '/pages/terms', 'priority' => '0.3', 'changefreq' => 'yearly'],
            ['loc' => $baseUrl . '/pages/refund_policy', '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 .= "\t<url>\n";
            $xml .= "\t\t<loc>" . htmlspecialchars($page['loc'], ENT_XML1) . "</loc>\n";
            $xml .= "\t\t<lastmod>" . $lastmod . "</lastmod>\n";
            $xml .= "\t\t<changefreq>" . $page['changefreq'] . "</changefreq>\n";
            $xml .= "\t\t<priority>" . $page['priority'] . "</priority>\n";
            $xml .= "\t</url>\n";
        }

        $xml .= '</urlset>';

        Log::channel('seo')->info('Sitemap generated by Laravel controller', [
            'route' => $request->path(),
            'base_url' => $baseUrl,
            'url_count' => count($pages),
            'bytes' => strlen($xml),
            'app_url_env' => config('app.url'),
        ]);

        return response($xml, 200, [
            'Content-Type' => 'application/xml; charset=UTF-8',
            'Cache-Control' => 'public, max-age=3600',
            'X-Sitemap-Source' => 'laravel-sitemap-controller',
            'X-Sitemap-Urls' => (string) count($pages),
        ]);
    }
}
