<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use App\Services\SkySportsService;

class AssetController extends Controller
{
    public function __construct(private SkySportsService $skySportsService) {}

    public function robots()
    {
        $content = "User-agent: *\n";
        $content .= "Allow: /\n";
        $content .= "Disallow: /admin/\n";
        $content .= "Sitemap: " . url('/sitemap.xml');
        
        return response($content, 200, [
            'Content-Type' => 'text/plain',
            'Cache-Control' => 'public, max-age=86400',
        ]);
    }

    public function index()
    {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        // Main Sitemap
        $xml .= '<sitemap>';
        $xml .= '<loc>' . url('/sitemap-main.xml') . '</loc>';
        $xml .= '<lastmod>' . date('Y-m-d') . '</lastmod>';
        $xml .= '</sitemap>';

        // Matches Sitemap
        $xml .= '<sitemap>';
        $xml .= '<loc>' . url('/sitemap-matches.xml') . '</loc>';
        $xml .= '<lastmod>' . date('Y-m-d') . '</lastmod>';
        $xml .= '</sitemap>';

        // Sports Articles Sitemap
        $xml .= '<sitemap>';
        $xml .= '<loc>' . url('/sitemap-sports-articles.xml') . '</loc>';
        $xml .= '<lastmod>' . date('Y-m-d') . '</lastmod>';
        $xml .= '</sitemap>';

        // Posts Sitemaps (Paginated)
        $totalPosts = \App\Models\Post::published()->count();
        $perPage = 1000;
        $totalPages = ceil($totalPosts / $perPage);

        for ($i = 1; $i <= $totalPages; $i++) {
            $xml .= '<sitemap>';
            $xml .= '<loc>' . url('/sitemap-posts-' . $i . '.xml') . '</loc>';
            $xml .= '<lastmod>' . date('Y-m-d') . '</lastmod>';
            $xml .= '</sitemap>';
        }

        // Keywords Sitemaps
        $keywordsDir = public_path('keywords');
        if (is_dir($keywordsDir)) {
            $files = glob($keywordsDir . '/*.txt');
            foreach ($files as $file) {
                $filename = pathinfo($file, PATHINFO_FILENAME);
                $xml .= '<sitemap>';
                $xml .= '<loc>' . url('/sitemap-keywords-' . $filename . '.xml') . '</loc>';
                $xml .= '<lastmod>' . date('Y-m-d', filemtime($file)) . '</lastmod>';
                $xml .= '</sitemap>';
            }
        }

        $xml .= '</sitemapindex>';

        return response($xml, 200, ['Content-Type' => 'application/xml']);
    }
    
    // ... main() and matches() and posts() methods follow (omitted for brevity in replacement chunk but preserved in file logic)
    
    public function sportsArticles()
    {
        // Cache this sitemap for 3 hours as fetching from API is heavy
        $xml = Cache::remember('sitemap_sports_articles', 10800, function () {
            $xml = '<?xml version="1.0" encoding="UTF-8"?>';
            $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
            
            // Limit categories to checking just page 1 
            // We use the constants from SkySportsService
            $categories = SkySportsService::CATEGORIES;
            
            foreach ($categories as $sport => $id) {
                // Fetch only page 1
                try {
                    $listing = $this->skySportsService->getSportsCategories($sport, $id, 1, 20); // 20 items per sport
                    
                    if (!empty($listing['items'])) {
                        foreach ($listing['items'] as $item) {
                            if (empty($item['link'])) continue;
                            
                            // Reconstruct the URL as generated in SportsController
                            // Expected format from parseSportsData:
                            // Link components derived from: $item['link']
                            
                            // The parseSportsData actually parses the components into $item['sports'], $item['type'], etc.
                            // We construct the internal route for 'sports.article'
                            // Route: /sports/{sport}/{type}/{idsport}/{id}/{term}
                            
                            if (!empty($item['sports']) && !empty($item['type']) && !empty($item['idsport']) && !empty($item['id'])) {
                                
                                $routeParams = [
                                    'sport' => $item['sports'],
                                    'type' => $item['type'],
                                    'idsport' => $item['idsport'],
                                    'id' => $item['id'],
                                    'term' => $item['news'] ?: 'article'
                                ];

                                // Handle special "more-sports" case
                                if (isset($item['more']) && $item['more'] === 'more-sports') {
                                    $url = route('sports.article.more', $routeParams);
                                } else {
                                    $url = route('sports.article', $routeParams);
                                }

                                $xml .= '<url>';
                                $xml .= '<loc>' . $url . '</loc>';
                                $xml .= '<lastmod>' . date('Y-m-d') . '</lastmod>'; // Since we don't have exact time, use today
                                $xml .= '<changefreq>daily</changefreq>';
                                $xml .= '<priority>0.7</priority>';
                                $xml .= '</url>';
                            }
                        }
                    }
                } catch (\Exception $e) {
                    // Continue to next category if one fails
                    continue;
                }
            }
            
            $xml .= '</urlset>';
            return $xml;
        });

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

    public function main()
    {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        // Homepage
        $xml .= '<url><loc>' . url('/') . '</loc><changefreq>daily</changefreq><priority>1.0</priority></url>';
        
        // Categories
        $categories = \App\Models\Category::all();
        foreach ($categories as $category) {
            $xml .= '<url><loc>' . url('/category/' . $category->slug) . '</loc><changefreq>daily</changefreq><priority>0.8</priority></url>';
        }

        // Sports Page
        $xml .= '<url><loc>' . url('/sports') . '</loc><changefreq>daily</changefreq><priority>0.8</priority></url>';

        // Sports Categories (from SkySports list)
        $sportsCategories = array_keys(SkySportsService::CATEGORIES);

        foreach ($sportsCategories as $sport) {
            $xml .= '<url><loc>' . url('/sports/' . $sport) . '</loc><changefreq>daily</changefreq><priority>0.8</priority></url>';
        }
        
        $xml .= '</urlset>';
        return response($xml, 200, ['Content-Type' => 'application/xml']);
    }

    public function matches()
    {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        $matches = \App\Models\Matches::latest()->take(1000)->get();
        foreach ($matches as $match) {
            $xml .= '<url>';
            $xml .= '<loc>' . route('play', $match->match_id) . '</loc>';
            $xml .= '<lastmod>' . ($match->updated_at ? $match->updated_at->format('Y-m-d') : date('Y-m-d')) . '</lastmod>';
            $xml .= '<changefreq>hourly</changefreq>';
            $xml .= '<priority>0.9</priority>';
            $xml .= '</url>';
        }
        
        $xml .= '</urlset>';
        return response($xml, 200, ['Content-Type' => 'application/xml']);
    }

    public function posts($page)
    {
        $perPage = 1000;
        $offset = ($page - 1) * $perPage;
        
        $posts = \App\Models\Post::published()->latest()->skip($offset)->take($perPage)->get();

        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        foreach ($posts as $post) {
            $xml .= '<url>';
            $xml .= '<loc>' . url('/post/' . $post->slug) . '</loc>';
            $xml .= '<lastmod>' . ($post->updated_at ? $post->updated_at->format('Y-m-d') : date('Y-m-d')) . '</lastmod>';
            $xml .= '<changefreq>weekly</changefreq>';
            $xml .= '<priority>0.6</priority>';
            $xml .= '</url>';
        }
        
        $xml .= '</urlset>';
        return response($xml, 200, ['Content-Type' => 'application/xml']);
    }

    public function keywords(string $filename)
    {
        $filePath = public_path('keywords/' . $filename . '.txt');

        if (!file_exists($filePath)) {
            abort(404);
        }

        // Cache the response to avoid reading file on every hit
        $xml = Cache::remember('sitemap_keywords_' . $filename, 86400, function () use ($filePath) {
            $xml = '<?xml version="1.0" encoding="UTF-8"?>';
            $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
            
            $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            
            foreach ($lines as $line) {
                $keyword = trim($line);
                if (empty($keyword)) continue;
                
                // Convert keyword to slug
                $slug = \Illuminate\Support\Str::slug($keyword);
                
                $xml .= '<url>';
                $xml .= '<loc>' . url('/news/' . $slug) . '</loc>';
                $xml .= '<changefreq>monthly</changefreq>';
                $xml .= '<priority>0.5</priority>';
                $xml .= '</url>';
            }
            
            $xml .= '</urlset>';
            return $xml;
        });

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