<?php

namespace App\Http\Controllers;

use App\Models\Blog;
use Illuminate\Http\Request;

class BlogController extends Controller
{
    /**
     * Display a listing of blogs.
     */
    public function index(Request $request)
    {
        $query = Blog::with('user');

        // Filter: active
        if ($request->has('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        // Filter: featured
        if ($request->has('is_featured')) {
            $query->where('is_featured', $request->is_featured);
        }

        // Search by title (en/fa)
        if ($request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('en_title', 'like', '%'.$request->search.'%')
                  ->orWhere('fa_title', 'like', '%'.$request->search.'%');
            });
        }

        $blogs = $query->latest()->paginate(20);

        return response()->json([
            'success' => true,
            'data' => $blogs,
        ]);
    }

    /**
     * Display a single blog (by id or slug).
     */
    public function show($identifier)
    {
        $blog = Blog::with('user')
            ->where('id', $identifier)
            ->orWhere('slug', $identifier)
            ->first();

        if (!$blog) {
            return response()->json([
                'success' => false,
                'message' => 'Blog not found.',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $blog,
        ]);
    }
}
