<?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;
use Illuminate\Support\Str;

class HomeController extends Controller
{
    public function index()
    {
        $usedIds = collect();

        /*OPINION*/
        $opinionId = Category::where('category_name', 'Opinion')->value('category_id');

        $allOpinions = News::with(['category', 'author'])
            ->where('category_id', $opinionId)
            ->latest('news_id')
            ->take(4)
            ->get();

        $opinionsLeft = $allOpinions->take(2);
        $opinionsRight = $allOpinions->slice(2, 2);
        $usedIds = $usedIds->merge($allOpinions->pluck('news_id'));


        /*FEATURED*/
        $featured = News::with(['category', 'author'])
            ->whereNotIn('news_id', $usedIds)
            ->latest('news_id')
            ->first();

        if ($featured) {
            $usedIds->push($featured->news_id);
        }
        $heroNews = News::with(['category', 'author'])
            ->orderBy('published_at', 'desc')
            ->orderBy('news_id', 'desc')
            ->first();

        /* SPOTLIGHT */
        $spotlightCategoryId = Category::where('category_name', 'Politics')->value('category_id');

        $spotlightPosts = News::with(['category', 'author'])
            ->where('category_id', $spotlightCategoryId)
            ->whereNotIn('news_id', $usedIds)
            ->latest('news_id')
            ->take(4)
            ->get();

        $spotlightMain = $spotlightPosts->first();
        $spotlightSide = $spotlightPosts->slice(1, 3);


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


        /* HEADLINES*/
        $headlines = collect();

        $categories = Category::pluck('category_id')->shuffle();

        foreach ($categories as $catId) {

            if ($catId == $opinionId) {
                continue;
            }

            $article = News::with(['category', 'author'])
                ->where('category_id', $catId)
                ->whereNotIn('news_id', $usedIds)
                ->latest('news_id')
                ->first();

            if ($article) {
                $headlines->push($article);
                $usedIds->push($article->news_id);
            }

            if ($headlines->count() == 4) {
                break;
            }
        }



        /*JUST FOR YOU*/
        $recommended = News::with(['category', 'author'])
            ->whereNotIn('news_id', $usedIds)
            ->orderBy('published_at', 'desc')
            ->orderBy('news_id', 'desc')
            ->take(4)
            ->get();

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

        $secondRecommended = News::with(['category', 'author'])
            ->whereNotIn('news_id', $usedIds)
            ->latest('news_id')
            ->take(4)
            ->get();

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


        /* TECHNOLOGY*/
        $techId = Category::where('category_name', 'Technology')->value('category_id');

        $techNews = News::with(['category', 'author'])
            ->where('category_id', $techId)
            ->whereNotIn('news_id', $usedIds)
            ->latest('news_id')
            ->take(3)
            ->get();

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


        /* WORLD*/
        $worldId = Category::where('category_name', 'World')->value('category_id');

        $worldNews = News::with(['category', 'author'])
            ->where('category_id', $worldId)
            ->whereNotIn('news_id', $usedIds)
            ->latest('news_id')
            ->take(3)
            ->get();

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


        /* HEALTH*/
        $healthId = Category::where('category_name', 'Finance')->value('category_id');

        $healthNews = News::with(['category', 'author'])
            ->where('category_id', $healthId)
            ->whereNotIn('news_id', $usedIds)
            ->latest('news_id')
            ->take(5)
            ->get();

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


        /* TRAVEL*/
        $travelId = Category::where('category_name', 'Politics')->value('category_id');

        $travelNews = News::with(['category', 'author'])
            ->where('category_id', $travelId)
            ->whereNotIn('news_id', $usedIds)
            ->latest('news_id')
            ->take(5)
            ->get();

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


        $excludeIds = $usedIds->unique()->values();
        /*NAV CIRCLES*/
        $navCircles = Category::orderBy('category_name')->take(6)->get();



        /*SCROLL FEED*/
        $latestFeed = News::with(['category', 'author'])
            ->whereNotIn('news_id', $excludeIds)
            ->latest('news_id')
            ->paginate(8);

        $sidebarFeed = News::with(['category', 'author'])
            ->whereNotIn('news_id', $excludeIds)
            ->latest('news_id')
            ->skip(8)
            ->take(3)
            ->get();

        $topWriters = Author::withCount('news')
            ->orderByDesc('news_count')
            ->take(4)
            ->get();

        $homeCircleCategories = Category::withCount('news')
            ->orderBy('category_name')
            ->get();

        return view('index', compact(
            'featured',
            'headlines',
            'recommended',
            'secondRecommended',
            'spotlightMain',
            'spotlightSide',
            'opinionsLeft',
            'opinionsRight',
            'techNews',
            'worldNews',
            'healthNews',
            'travelNews',
            'latestFeed',
            'navCircles',
            'sidebarFeed',
            'topWriters',
            'heroNews',
            'homeCircleCategories'
        ));
    }
   public function show($category, $slug)
    {
        $newsDetail = News::with(['category', 'author'])
            ->where('encode_title', $slug)
            ->whereHas('category', function ($q) use ($category) {
                $q->where('slug', $category);
            })
            ->firstOrFail();

        $recommended = News::with(['category', 'author'])
            ->where('news_id', '!=', $newsDetail->news_id)
            ->where('category_id', $newsDetail->category_id)
            ->latest('news_id')
            ->take(4)
            ->get();

        return view('newsDetail', [
            'newsDetail' => $newsDetail,
            'category' => $newsDetail->category,
            'recommended' => $recommended
        ]);
    }
    public function search(Request $request)
    {
        $query = trim($request->q);

        $results = News::with(['category', 'author'])
            ->where(function ($q) use ($query) {

                $q->where('news_title', 'LIKE', "%{$query}%")

                    ->orWhere('news_content', 'LIKE', "%{$query}%")

                    ->orWhere('news_content_short', 'LIKE', "%{$query}%");

            })
            ->orderByDesc('news_id')
            ->paginate(12)
            ->appends(['q' => $query]);

        return view('search', compact('results', 'query'));
    }
    public function myfeed()
    {
        $baseQuery = News::with(['category', 'author'])
            ->orderBy('published_at', 'desc')
            ->orderBy('news_id', 'desc');

        // top 2 big cards
        $featuredLeft = (clone $baseQuery)->first();
        $featuredRight = (clone $baseQuery)->skip(1)->first();

        // 4 cards row 1
        $rowOne = (clone $baseQuery)
            ->skip(2)
            ->take(4)
            ->get();

        // 4 cards row 2
        $rowTwo = (clone $baseQuery)
            ->skip(6)
            ->take(4)
            ->get();

        return view('myfeed', compact(
            'featuredLeft',
            'featuredRight',
            'rowOne',
            'rowTwo'
        ));
    }
}
