<?php

namespace App\Http\Controllers;

use App\Services\SkySportsService;
use Illuminate\Http\Request;

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

    /**
     * Display sports listing page (equivalent to get/sports.php)
     */
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $term = $request->get('term', 'sports');
        $id = $request->get('id', '29876');
        $limit = 20;

        // Fetch sports data from Sky Sports
        $sportsData = $this->skySportsService->getSportsCategories('sports', $id, $page, $limit);

        // Get categories for navigation
        $categories = \App\Models\Category::all();

        return view('sports.index', [
            'sportsData' => $sportsData,
            'categories' => $categories,
            'pagename' => ucwords(strtolower(str_replace('-', ' ', $term))),
            'page' => $page,
            'term' => $term,
            'id' => $id,
        ]);
    }

    /**
     * Display individual sports article (equivalent to do/news.php)
     */
    public function article(Request $request, string $sport, string $type, string $idsport, string $id, string $term)
    {
        $more = $request->get('more', '');

        // Validate required parameters
        if (empty($idsport) || empty($id)) {
            return redirect()->route('sports.index')->with('error', 'Invalid article parameters');
        }

        // 1. Check if post exists in database using the external ID stored in tags
        $post = \App\Models\Post::where('tags', 'LIKE', '%id:' . $id . '%')->first();

        if ($post) {
            // Use data from database
            $articleData = [
                'title' => $post->title,
                'article' => [$post->content], // Wrap in array to match view expectation
                'images' => $post->image,
                'date' => $post->published_at ? $post->published_at->toIso8601String() : now()->toIso8601String(),
            ];
        } else {
            // 2. Fetch article data from SkySports
            $params = [
                'sport' => $sport,
                'id' => $id,
                'idsport' => $idsport,
                'term' => $term,
                'more' => $more,
                'type' => $type,
            ];
            $articleData = $this->skySportsService->parseSkySportsArticle($params, false);

            // 3. Save to Database if valid data
            if (!empty($articleData) && isset($articleData['title'])  && isset($articleData['article'])) {
                // Determine slug
                $slug = $term;
                // Check if slug exists, if so, generate from title
                if (\App\Models\Post::where('slug', $slug)->exists()) {
                    $slug = \Illuminate\Support\Str::slug($articleData['title']);
                    // If still exists, append ID
                    if (\App\Models\Post::where('slug', $slug)->exists()) {
                        $slug .= '-' . $id;
                    }
                }

                // Find or create category based on sport
                $categorySlug = \Illuminate\Support\Str::slug($sport);
                $category = \App\Models\Category::where('slug', $categorySlug)->first();
                
                if (!$category) {
                    $category = \App\Models\Category::create([
                        'name' => ucwords(str_replace('-', ' ', $sport)),
                        'slug' => $categorySlug,
                    ]);
                }

                // Process content to HTML string
                $contentHtml = '';
                if (isset($articleData['article']) && is_array($articleData['article'])) {
                    foreach ($articleData['article'] as $item) {
                        if (is_array($item)) {
                            // Handle structured content (e.g. live blog)
                            $entryTitle = $item['title'] ?? '';
                            $entryContent = $item['content'] ?? '';
                            $contentHtml .= "<div class='live-blog-entry mb-4'>";
                            if ($entryTitle) $contentHtml .= "<h4 class='font-bold'>{$entryTitle}</h4>";
                            $contentHtml .= "<div>{$entryContent}</div></div>";
                        } else {
                            $contentHtml .= "<p class='mb-4'>{$item}</p>";
                        }
                    }
                } elseif (isset($articleData['article']) && is_string($articleData['article'])) {
                    $contentHtml = $articleData['article'];
                }

                if($contentHtml && $articleData['title']) {
                // Create new Post
                \App\Models\Post::create([
                    'title' => $articleData['title'],
                    'slug' => $slug,
                    'content' => $contentHtml,
                    'excerpt' => \Illuminate\Support\Str::limit(strip_tags($contentHtml), 150),
                    'image' => $articleData['images'] ?? null,
                    'category_id' => $category->id,
                    'tags' => $sport . ',' . $type , // Store ID in tags for future lookups
                    'is_published' => true,
                    'published_at' => !empty($articleData['date']) ? \Carbon\Carbon::parse($articleData['date']) : now(),
                    'meta_title' => $articleData['title'],
                    'meta_description' => \Illuminate\Support\Str::limit(strip_tags($contentHtml), 160),
                ]);
            }
            }
        }

        // Get categories for navigation
        $categories = \App\Models\Category::all();

        return view('sports.article', [
            'articleData' => $articleData,
            'categories' => $categories,
            'sport' => $sport,
            'type' => $type,
        ]);
    }

    /**
     * Handle search functionality (equivalent to search in functions.php)
     */
    public function search(Request $request)
    {
        $query = $request->get('s', '');
        $page = $request->get('page', 1);

        if (empty($query)) {
            return redirect()->route('home');
        }

        // For search, we'll use the same sports data but filter by search term
        $sportsData = $this->skySportsService->getSportsCategories('search', '29876', $page);

        // Filter results based on search query
        if (isset($sportsData['total_results'])) {
            $filteredResults = array_filter($sportsData, function ($item) use ($query) {
                return isset($item['title']) && stripos($item['title'], $query) !== false;
            });
            $sportsData = array_values($filteredResults);
            $sportsData['total_results'] = count($filteredResults);
        }

        $categories = \App\Models\Category::all();

        return view('sports.search', [
            'sportsData' => $sportsData,
            'categories' => $categories,
            'query' => $query,
            'page' => $page,
        ]);
    }

    /**
     * Display sports category page (equivalent to get/sports.php with category filter)
     */
    public function category(Request $request, string $category)
    {
        $page = $request->get('page', 1);
        $term = $request->get('term', $category);
        
        // Fetch category ID from database if available
        $categoryModel = \App\Models\Category::where('slug', strtolower($term))->first();
        $id = $categoryModel ? $categoryModel->code : '11095'; // Fallback to default ID if not found

        // Fetch sports data filtered by category
        $sportsData = $this->skySportsService->getSportsCategories($category, $id, $page);

        // Filter results to only show items from the specified category
        if (isset($sportsData['items']) && is_array($sportsData['items'])) {
            $filteredResults = array_filter($sportsData['items'], function ($item) use ($category) {
                return isset($item['sports']) &&
                    (strtolower($item['sports']) === strtolower($category) ||
                        stripos($item['sports'], $category) !== false);
            });
            $filteredResults = array_values($filteredResults);
            $sportsData['items'] = $filteredResults;
        }

        $categories = \App\Models\Category::all();

        return view('sports.index', [
            'sportsData' => $sportsData,
            'categories' => $categories,
            'pagename' => ucwords(strtolower(str_replace('-', ' ', $category))),
            'page' => $page,
            'term' => $term,
            'id' => $id,
        ]);
    }
}
