<?php
namespace App\Http\Controllers\Api;

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

class PostController extends Controller
{
    // GET /api/posts
    public function index(Request $request)
    {
        $posts = Post::published()
            ->with(['continent', 'country', 'category', 'tags'])
            ->when($request->continent, fn($q) => $q->forContinent($request->continent))
            ->when($request->country,   fn($q) => $q->forCountry($request->country))
            ->when($request->category,  fn($q) => $q->forCategory($request->category))
            ->when($request->search,    fn($q) => $q->whereFullText(['title', 'excerpt'], $request->search))
            ->when($request->tag,       fn($q) => $q->whereHas('tags', fn($t) => $t->where('slug', $request->tag)))
            ->orderByDesc('created_at')
            ->paginate($request->per_page ?? 12);

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

    // GET /api/posts/featured
    public function featured()
    {
        $posts = Post::published()->featured()
            ->with(['continent', 'country', 'category'])
            ->orderByDesc('created_at')
            ->limit(5)
            ->get();

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

    // GET /api/posts/breaking
    public function breaking()
    {
        $posts = Post::published()->breaking()
            ->with(['category'])
            ->orderByDesc('published_at')
            ->limit(10)
            ->get();

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

    // GET /api/posts/trending  (most views in last 7 days)
    public function trending()
    {
        $posts = Post::published()
            ->with(['continent', 'country', 'category'])
            ->orderByDesc('views_count')
            ->limit(10)
            ->get();

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

    // GET /api/posts/{slug}
    public function show(string $slug)
    {
        $post = Post::published()
            ->with(['continent', 'country', 'category', 'tags', 'author', 'source'])
            ->where('slug', $slug)
            ->firstOrFail();

        // Increment view count
        $post->increment('views_count');

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

    // GET /api/posts/{slug}/related
    public function related(string $slug)
    {
        $post = Post::where('slug', $slug)->firstOrFail();

        $related = Post::published()
            ->with(['country', 'category'])
            ->where('id', '!=', $post->id)
            ->where(fn($q) => $q
                ->where('category_id', $post->category_id)
                ->orWhere('country_id', $post->country_id)
            )
            ->orderByDesc('created_at')
            ->limit(6)
            ->get();

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