<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PublicPostController extends Controller
{
    public function getRelated(Post $post): JsonResponse
    {
        $related = Post::with(['user:id,name,username,avatar', 'category:id,name,slug', 'images', 'rssFeed'])
            ->withCount('comments')
            ->where('category_id', $post->category_id)
            ->where('id', '!=', $post->id)
            ->where('status', 'published')
            ->latest()
            ->paginate(2); 

        $related->getCollection()->transform(function ($item) {
            $item->fetched_inline_related = Post::select('id', 'title', 'slug', 'image_path', 'created_at', 'category_id')
                ->where('category_id', $item->category_id)
                ->where('id', '!=', $item->id)
                ->where('status', 'published')
                ->inRandomOrder() 
                ->take(3) 
                ->get();
            
            return $item;
        });

        return response()->json($related);
    }

    public function getSidebarData(Post $post): JsonResponse
    {
        $trending = Post::select('id', 'title', 'slug', 'image_path', 'created_at', 'views_count', 'category_id')
            ->with('category:id,name')
            ->where('status', 'published')
            ->where('id', '!=', $post->id) 
            ->where('created_at', '>=', now()->subDays(7))
            ->orderBy('views_count', 'desc')
            ->take(3) 
            ->get();

        if ($trending->isEmpty()) {
            $trending = Post::select('id', 'title', 'slug', 'image_path', 'created_at', 'views_count', 'category_id')
                ->with('category:id,name')
                ->where('status', 'published')
                ->where('id', '!=', $post->id)
                ->orderBy('views_count', 'desc')
                ->take(3) 
                ->get();
        }

        $sameCategory =[];
        if ($post->category_id) {
            $sameCategory = Post::select('id', 'title', 'slug', 'image_path', 'created_at')
                ->where('status', 'published')
                ->where('category_id', $post->category_id)
                ->where('id', '!=', $post->id)
                ->latest()
                ->take(3)
                ->get();
        } else {
            $sameCategory = Post::select('id', 'title', 'slug', 'image_path', 'created_at')
                ->where('status', 'published')
                ->where('id', '!=', $post->id)
                ->latest()
                ->take(3)
                ->get();
        }

        return response()->json([
            'you_may_like' => $trending,
            'same_category' => $sameCategory
        ]);
    }

    public function getHomeData(): JsonResponse
    {
        $trending = Post::select('id', 'title', 'slug', 'views_count')
            ->where('status', 'published')
            ->orderBy('views_count', 'desc')
            ->take(5)
            ->get();

        // Get counts for tabs to dynamically hide empty tabs on the frontend
        $tabCounts =[
            'featured' => Post::where('status', 'published')->where('is_featured', true)->count(),
            'editor_picks' => Post::where('status', 'published')->where('is_editor_pick', true)->count(),
            'hot_news' => Post::where('status', 'published')->where('is_hot', true)->count(),
        ];

        // 1st page of Latest Tab
        $latest = Post::with(['user:id,name,username,avatar', 'category:id,name', 'rssFeed'])
            ->withCount('comments') 
            ->where('status', 'published')
            ->latest()
            ->paginate(10); 

        if (auth()->check()) {
            $userId = auth()->id();
            $postIds = $latest->getCollection()->pluck('id')->toArray();
            
            $votes = \App\Models\Vote::whereIn('post_id', $postIds)
                ->where('user_id', $userId)
                ->pluck('type', 'post_id');

            $latest->getCollection()->transform(function ($post) use ($votes) {
                $post->setAttribute('user_vote', $votes[$post->id] ?? null);
                return $post;
            });
        }

        return response()->json([
            'trending' => $trending,
            'latest' => $latest,
            'tab_counts' => $tabCounts // <--- NEW: Send tab counts
        ]);
    }

    // Dynamic Pagination for ALL tabs
    public function getLatestFeed(Request $request): JsonResponse
    {
        $tab = $request->query('tab', 'latest');
        $perPage = 10;

        $query = Post::with(['user:id,name,username,avatar', 'category:id,name', 'rssFeed'])
            ->withCount('comments') 
            ->where('status', 'published');

        if ($tab === 'featured') {
            $query->where('is_featured', true);
        } elseif ($tab === 'editor_picks') {
            $query->where('is_editor_pick', true);
        } elseif ($tab === 'hot_news') {
            $query->where('is_hot', true);
        }

        $posts = $query->latest()->paginate($perPage); 

        if (auth()->check()) {
            $userId = auth()->id();
            $postIds = $posts->getCollection()->pluck('id')->toArray();
            
            $votes = \App\Models\Vote::whereIn('post_id', $postIds)
                ->where('user_id', $userId)
                ->pluck('type', 'post_id');

            $posts->getCollection()->transform(function ($post) use ($votes) {
                $post->setAttribute('user_vote', $votes[$post->id] ?? null);
                return $post;
            });
        }

        return response()->json($posts);
    }
}