<?php

namespace App\Repositories\Website;

use App\Models\Blog;
use App\Repositories\Interfaces\Website\BlogRepositoryInterface;
use Illuminate\Http\Request;

class BlogRepository implements BlogRepositoryInterface
{
   public function getBlogs(Request $request): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $query = Blog::with('category')->latest();

        // Search
        if ($request->filled('search')) {
            $query->where('title', 'like', '%' . $request->search . '%');
        }

        // Category filter
        if ($request->has('category_filter')) {
            $query->whereIn('category_id', $request->category_filter);
        }

        // Year filter
        if ($request->has('year_filter')) {
            $query->whereYear('created_at', $request->year_filter);
        }

        return $query->paginate(20); // You can make this dynamic if needed
    }

    public function getTopBlogs(int $limit = 5)
    {
        return Blog::latest()->take($limit)->get();
    }

    public function getBlogDetails($slug)
{
    $blog = Blog::where('slug', $slug)->first();

    if (!$blog) {
        return null;
    }

    $relatedBlogs = Blog::where('category_id', $blog->category_id)
                        ->where('id', '!=', $blog->id)
                        ->limit(5)
                        ->get();

    return [
        'blog' => $blog,
        'related_blogs' => $relatedBlogs,
    ];
}
    
}
