<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\BlogPost;
use App\Models\Anime;

class BlogController extends Controller
{
    public function index()
    {
        $posts = BlogPost::with('anime')
            ->published()
            ->orderByDesc('published_at')
            ->paginate(12);

        $recent = BlogPost::published()->orderByDesc('published_at')->limit(5)->get();
        $popular = BlogPost::published()->orderByDesc('views')->limit(5)->get();

        return view('frontend.blog.index', compact('posts', 'recent', 'popular'));
    }

    public function show(string $slug)
    {
        $post = BlogPost::with('anime.genres')
            ->where('slug', $slug)
            ->where('status', 'published')
            ->firstOrFail();

        $post->increment('views');

        // İlgili yazılar: aynı anime veya benzer anahtar kelimeler
        $related = BlogPost::published()
            ->where('id', '!=', $post->id)
            ->when($post->anime_id, fn($q) => $q->where('anime_id', $post->anime_id)
                ->orWhere('focus_keyword', 'like', '%' . explode(' ', $post->focus_keyword ?? '')[0] . '%')
            )
            ->orderByDesc('published_at')
            ->limit(4)
            ->get();

        // Linked anime'ler
        $linkedAnimes = collect();
        if (!empty($post->linked_anime_ids)) {
            $linkedAnimes = Anime::whereIn('id', $post->linked_anime_ids)
                ->where('is_published', true)
                ->get();
        }

        return view('frontend.blog.show', compact('post', 'related', 'linkedAnimes'));
    }
}
