<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\News;
use App\Models\Category;
use App\Models\Author;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    // ═══════════════════════════════════════════════════════════════════════════
    // HOME PAGE  — Each section has a distinct purpose matching the Hindu design
    // ═══════════════════════════════════════════════════════════════════════════

    public function index()
    {
        $usedIds = collect();

        // ── Section 0: TOP NEWS (left hero + middle list + right sidebar) ──────
        // The dominant 3-column top section of The Hindu

        // Top-left hero — the single most recent published article with an image
        $topNewsHero = News::with(['category', 'author'])
            ->published()
            ->orderByDesc('news_id')
            ->first();
        if ($topNewsHero) $usedIds->push($topNewsHero->news_id);

        // Top-left sub-items (3 articles below the hero image)
        $topNewsSubItems = News::with(['category', 'author'])
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->take(3)
            ->get();
        $usedIds = $usedIds->merge($topNewsSubItems->pluck('news_id'));

        // Middle column — 5 headline links (category tag + title only)
        $topNewsMiddle = News::with('category')
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->take(5)
            ->get();
        $usedIds = $usedIds->merge($topNewsMiddle->pluck('news_id'));

        // Right sidebar — editorial + latest news feed (time-ago)
        $editorialItems = News::with('category')
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->take(2)
            ->get();

        $latestSidebarFeed = News::with('category')
            ->published()
            ->whereNotIn('news_id', $usedIds->merge($editorialItems->pluck('news_id')))
            ->orderByDesc('news_id')
            ->take(4)
            ->get();

        // ── Section 1: SPOTLIGHT (event/topic strip — like War Coverage) ───────
        // Picks the most-covered category not yet used, highlights it as a topic
        $spotlightCategory = Category::withCount(['news' => function ($q) use ($usedIds) {
            $q->published()->whereNotIn('news_id', $usedIds);
        }])
        ->having('news_count', '>=', 3)
        ->orderByDesc('news_count')
        ->first();

        $spotlightMain    = null;
        $spotlightLeft    = collect();
        $spotlightRight   = collect();
        $spotlightLinks   = collect();

        if ($spotlightCategory) {
            $spotlightPool = News::with(['category', 'author'])
                ->published()
                ->where('category_id', $spotlightCategory->category_id)
                ->whereNotIn('news_id', $usedIds)
                ->orderByDesc('news_id')
                ->take(6)
                ->get();

            $spotlightMain  = $spotlightPool->first();
            $spotlightLeft  = $spotlightPool->skip(1)->take(1);   // one with intro text
            $spotlightRight = $spotlightPool->skip(2)->take(3);   // three thumbnail items
            $spotlightLinks = $spotlightPool->take(3)->map(fn($n) => $n->news_title);

            $usedIds = $usedIds->merge($spotlightPool->pluck('news_id'));
        }

        // ── Section 2: FOR YOU (4-card horizontal grid) ──────────────────────
        // Broad selection — one from each of the 4 most distinct categories
        $availableCats = Category::withCount(['news' => function ($q) use ($usedIds) {
            $q->published()->whereNotIn('news_id', $usedIds);
        }])
        ->having('news_count', '>=', 1)
        ->orderByDesc('news_count')
        ->take(4)
        ->get();

        // FIX: Use a single query + unique() instead of N+1 loop
        $forYouItems = News::with(['category', 'author'])
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->whereIn('category_id', $availableCats->pluck('category_id'))
            ->orderByDesc('news_id')
            ->get()
            ->unique('category_id')
            ->take(4)
            ->values();

        $usedIds = $usedIds->merge($forYouItems->pluck('news_id'));

        // Fill to 4 if needed
        if ($forYouItems->count() < 4) {
            $filler = News::with(['category', 'author'])
                ->published()
                ->whereNotIn('news_id', $usedIds)
                ->orderByDesc('news_id')
                ->take(4 - $forYouItems->count())
                ->get();
            $forYouItems = $forYouItems->merge($filler);
            $usedIds = $usedIds->merge($filler->pluck('news_id'));
        }

        // ── Section 3: EDITOR'S PICK (left big + middle 2-stack + right sidebar) ──
        // Featured editorial: 1 hero, 2 stacked, 2 panel sub-sections
        $editorsPick = News::with(['category', 'author'])
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->first();
        if ($editorsPick) $usedIds->push($editorsPick->news_id);

        $editorsMiddle = News::with(['category', 'author'])
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->take(2)
            ->get();
        $usedIds = $usedIds->merge($editorsMiddle->pluck('news_id'));

        // Cities panel (right sidebar item 1)
        $citiesPanel = News::with('category')
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->take(2)
            ->get();
        $usedIds = $usedIds->merge($citiesPanel->pluck('news_id'));

        // States panel (right sidebar item 2)
        $statesPanel = News::with('category')
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->take(3)
            ->get();
        $usedIds = $usedIds->merge($statesPanel->pluck('news_id'));

        // ── Section 4: SECTION ONE (large featured topic block) ───────────────
        // Picks the 2nd heaviest category (after spotlight), shows main + 4 sub
        $sectionOneCategory = Category::withCount(['news' => function ($q) use ($usedIds) {
            $q->published()->whereNotIn('news_id', $usedIds);
        }])
        ->having('news_count', '>=', 2)
        ->orderByDesc('news_count')
        ->skip(1)->take(1)->first()
        ?? Category::withCount(['news' => function ($q) use ($usedIds) {
            $q->published()->whereNotIn('news_id', $usedIds);
        }])
        ->having('news_count', '>=', 2)
        ->orderByDesc('news_count')
        ->first();

        $sectionOneMain    = null;
        $sectionOneItems   = collect();
        $sectionOneLeft    = collect();
        $sectionOneRight   = collect();

        if ($sectionOneCategory) {
            $sectionOnePool = News::with(['category', 'author'])
                ->published()
                ->where('category_id', $sectionOneCategory->category_id)
                ->whereNotIn('news_id', $usedIds)
                ->orderByDesc('news_id')
                ->take(5)
                ->get();

            $sectionOneMain  = $sectionOnePool->first();
            $sectionOneItems = $sectionOnePool->skip(1);
            $sectionOneLeft  = $sectionOneItems->take(2);
            $sectionOneRight = $sectionOneItems->skip(2)->take(2);
            $usedIds = $usedIds->merge($sectionOnePool->pluck('news_id'));
        }

        // ── Section 5: MOST POPULAR (6 thumbnail items) ──────────────────────
        // In a live site this would be view-count sorted; we use recency for demo
        $mostPopular = News::with(['category', 'author'])
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->take(6)
            ->get();
        $usedIds = $usedIds->merge($mostPopular->pluck('news_id'));

        // ── Section 6: SECTION TWO (4-card grid from another category) ────────
        $sectionTwoCategory = Category::withCount(['news' => function ($q) use ($usedIds) {
            $q->published()->whereNotIn('news_id', $usedIds);
        }])
        ->having('news_count', '>=', 1)
        ->orderByDesc('news_count')
        ->first();

        $sectionTwoItems = collect();
        if ($sectionTwoCategory) {
            $sectionTwoItems = News::with(['category', 'author'])
                ->published()
                ->where('category_id', $sectionTwoCategory->category_id)
                ->whereNotIn('news_id', $usedIds)
                ->orderByDesc('news_id')
                ->take(4)
                ->get();
            $usedIds = $usedIds->merge($sectionTwoItems->pluck('news_id'));
        }

        // ── Section 7: SECTION THREE (Environment / list + 2 images layout) ───
        $sectionThreeCategory = Category::withCount(['news' => function ($q) use ($usedIds) {
            $q->published()->whereNotIn('news_id', $usedIds);
        }])
        ->having('news_count', '>=', 1)
        ->orderByDesc('news_count')
        ->first();

        $sectionThreeItems = collect();
        if ($sectionThreeCategory) {
            $sectionThreeItems = News::with(['category', 'author'])
                ->published()
                ->where('category_id', $sectionThreeCategory->category_id)
                ->whereNotIn('news_id', $usedIds)
                ->orderByDesc('news_id')
                ->take(4)
                ->get();
            $usedIds = $usedIds->merge($sectionThreeItems->pluck('news_id'));
        }

        // ── Section 8: FEATURED SECTIONS (4-column category showcase) ─────────
        // 4 categories, 3 articles each, with image+tag+title+source layout
        $featuredSectionCategories = Category::withCount(['news' => function ($q) use ($usedIds) {
            $q->published()->whereNotIn('news_id', $usedIds);
        }])
        ->having('news_count', '>=', 2)
        ->orderByDesc('news_count')
        ->take(4)
        ->get();

        $featuredSections = [];
        foreach ($featuredSectionCategories as $cat) {
            $items = News::with(['category', 'author'])
                ->published()
                ->where('category_id', $cat->category_id)
                ->whereNotIn('news_id', $usedIds)
                ->orderByDesc('news_id')
                ->take(3)
                ->get();
            if ($items->isNotEmpty()) {
                $usedIds = $usedIds->merge($items->pluck('news_id'));
                $featuredSections[] = [
                    'category' => $cat,
                    'items'    => $items,
                ];
            }
            if (count($featuredSections) >= 4) break;
        }

        // ── Section 9: LATEST FEED (paginated, infinite scroll base) ──────────
        $latestFeed = News::with(['category', 'author'])
            ->published()
            ->whereNotIn('news_id', $usedIds)
            ->orderByDesc('news_id')
            ->paginate(8);

        // ── Top authors for sidebar ────────────────────────────────────────────
        $topWriters = Author::withCount('news')
            ->orderByDesc('news_count')
            ->take(4)
            ->get();

        // ── All categories (used by Life & Style carousel in blade) ───────────
        $allCategories = Category::orderBy('category_name')->get();

        return view('index', compact(
            // Section 0 — Top News
            'topNewsHero',
            'topNewsSubItems',
            'topNewsMiddle',
            'editorialItems',
            'latestSidebarFeed',
            // Section 1 — Spotlight
            'spotlightCategory',
            'spotlightMain',
            'spotlightLeft',
            'spotlightRight',
            'spotlightLinks',
            // Section 2 — For You
            'forYouItems',
            // Section 3 — Editor's Pick
            'editorsPick',
            'editorsMiddle',
            'citiesPanel',
            'statesPanel',
            // Section 4 — Section One
            'sectionOneCategory',
            'sectionOneMain',
            'sectionOneLeft',
            'sectionOneRight',
            // Section 5 — Most Popular
            'mostPopular',
            // Section 6 — Section Two
            'sectionTwoCategory',
            'sectionTwoItems',
            // Section 7 — Section Three
            'sectionThreeCategory',
            'sectionThreeItems',
            // Section 8 — Featured Sections
            'featuredSections',
            // Section 9 — Latest Feed
            'latestFeed',
            // Sidebar
            'topWriters',
            // All categories (Life & Style carousel)
            'allCategories'
        ));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // ARTICLE DETAIL PAGE
    // ═══════════════════════════════════════════════════════════════════════════

    public function show(string $category, string $slug)
    {
        $article = News::with(['category', 'author'])
            ->where('encode_title', $slug)
            ->whereHas('category', fn($q) => $q->where('slug', $category))
            ->firstOrFail();

        // Related articles from same category (exclude current)
        $related = News::with(['category', 'author'])
            ->published()
            ->where('category_id', $article->category_id)
            ->where('news_id', '!=', $article->news_id)
            ->orderByDesc('news_id')
            ->take(4)
            ->get();

        // Latest sidebar feed (across all categories)
        $latestSidebar = News::with('category')
            ->published()
            ->where('news_id', '!=', $article->news_id)
            ->orderByDesc('news_id')
            ->take(6)
            ->get();

        // Most read (same category, different articles)
        $mostRead = News::with('category')
            ->published()
            ->where('category_id', $article->category_id)
            ->where('news_id', '!=', $article->news_id)
            ->orderByDesc('news_id')
            ->take(5)
            ->get();

        return view('newsDetail', [
            'article'       => $article,
            'category'      => $article->category,
            'related'       => $related,
            'latestSidebar' => $latestSidebar,
            'mostRead'      => $mostRead,
        ]);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // SEARCH
    // ═══════════════════════════════════════════════════════════════════════════

    public function search(Request $request)
    {
        $query = trim($request->get('q', ''));

        $results = News::with(['category', 'author'])
            ->published()
            ->where(function ($q) use ($query) {
                $q->where('news_title', 'LIKE', "%{$query}%")
                  ->orWhere('news_content_short', 'LIKE', "%{$query}%")
                  ->orWhere('news_content', 'LIKE', "%{$query}%")
                  ->orWhere('news_title_english', 'LIKE', "%{$query}%")
                  ->orWhere('news_content_english', 'LIKE', "%{$query}%")
                  ->orWhere('news_content_short_english', 'LIKE', "%{$query}%");
            })
            ->orderByDesc('news_id')
            ->paginate(12)
            ->appends(['q' => $query]);

        return response()
            ->view('search', compact('results', 'query'))
            ->header('X-Robots-Tag', 'noindex, follow');
    }
}