<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Category;
use App\Models\User;
use App\Models\CustomPage;
use Illuminate\Http\Request;

class SitemapController extends Controller
{
    /**
     * Main Sitemap Index (sitemap.xml)
     */
    public function index()
    {
        $sitemaps = [
            route('sitemap.pages'),
            route('sitemap.categories'),
            route('sitemap.stores'),
            route('sitemap.products'),
        ];

        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        foreach ($sitemaps as $url) {
            $xml .= '<sitemap>';
            $xml .= '<loc>' . htmlspecialchars($url) . '</loc>';
            $xml .= '<lastmod>' . now()->tz('UTC')->toAtomString() . '</lastmod>';
            $xml .= '</sitemap>';
        }
        
        $xml .= '</sitemapindex>';

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

    /**
     * Products Sitemap
     */
    public function products()
    {
        // Fetch all active products (assuming stock > 0 or just all published)
        $products = Product::latest('updated_at')->get(['id', 'slug', 'updated_at']);

        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        foreach ($products as $product) {
            $xml .= '<url>';
            $xml .= '<loc>' . htmlspecialchars(route('product.view', $product->slug . '_' . $product->id)) . '</loc>';
            $xml .= '<lastmod>' . $product->updated_at->tz('UTC')->toAtomString() . '</lastmod>';
            $xml .= '<changefreq>daily</changefreq>';
            $xml .= '<priority>0.9</priority>';
            $xml .= '</url>';
        }
        
        $xml .= '</urlset>';

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

    /**
     * Categories Sitemap
     */
    public function categories()
    {
        $categories = Category::where('is_active', true)->latest('updated_at')->get(['slug', 'updated_at']);

        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        foreach ($categories as $category) {
            $xml .= '<url>';
            $xml .= '<loc>' . htmlspecialchars(route('category.show', $category->slug)) . '</loc>';
            $xml .= '<lastmod>' . $category->updated_at->tz('UTC')->toAtomString() . '</lastmod>';
            $xml .= '<changefreq>weekly</changefreq>';
            $xml .= '<priority>0.8</priority>';
            $xml .= '</url>';
        }
        
        $xml .= '</urlset>';

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

    /**
     * Stores / Sellers Sitemap
     */
    public function stores()
    {
        // Get all users who are sellers, managers, or admins (store owners)
        $stores = User::whereIn('role', ['seller', 'manager', 'admin'])
            ->latest('updated_at')
            ->get(['username', 'store_slug', 'updated_at']);

        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        foreach ($stores as $store) {
            $slug = $store->store_slug ?: $store->username;
            $xml .= '<url>';
            $xml .= '<loc>' . htmlspecialchars(route('store.view', $slug)) . '</loc>';
            $xml .= '<lastmod>' . $store->updated_at->tz('UTC')->toAtomString() . '</lastmod>';
            $xml .= '<changefreq>weekly</changefreq>';
            $xml .= '<priority>0.7</priority>';
            $xml .= '</url>';
        }
        
        $xml .= '</urlset>';

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

    /**
     * Static Pages & Custom Pages Sitemap
     */
    public function pages()
    {
        $customPages = CustomPage::where('is_active', true)->latest('updated_at')->get(['slug', 'updated_at']);

        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        // 1. Static Core Pages
        $staticPages = [
            ['url' => route('home'), 'priority' => '1.0', 'freq' => 'daily'],
            ['url' => route('search.index'), 'priority' => '0.8', 'freq' => 'daily'],
            ['url' => route('deals.index'), 'priority' => '0.8', 'freq' => 'daily'],
            ['url' => route('login'), 'priority' => '0.5', 'freq' => 'monthly'],
            ['url' => route('register'), 'priority' => '0.5', 'freq' => 'monthly'],
        ];

        foreach ($staticPages as $page) {
            $xml .= '<url>';
            $xml .= '<loc>' . htmlspecialchars($page['url']) . '</loc>';
            $xml .= '<lastmod>' . now()->tz('UTC')->toAtomString() . '</lastmod>';
            $xml .= '<changefreq>' . $page['freq'] . '</changefreq>';
            $xml .= '<priority>' . $page['priority'] . '</priority>';
            $xml .= '</url>';
        }

        // 2. Dynamic Custom Pages (Privacy Policy, About Us, etc)
        foreach ($customPages as $page) {
            $xml .= '<url>';
            $xml .= '<loc>' . htmlspecialchars(route('custom.page', $page->slug)) . '</loc>';
            $xml .= '<lastmod>' . $page->updated_at->tz('UTC')->toAtomString() . '</lastmod>';
            $xml .= '<changefreq>monthly</changefreq>';
            $xml .= '<priority>0.6</priority>';
            $xml .= '</url>';
        }
        
        $xml .= '</urlset>';

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