<?php

namespace App\Http\Controllers\Api\PublicApi;

use App\Http\Controllers\Controller;
use App\Http\Resources\BlogPostDetailResource;
use App\Http\Resources\BlogPostResource;
use App\Models\BlogPost;
use Illuminate\Http\Request;

class BlogPostController extends Controller
{
    public function index(Request $request)
    {
        

        $query = BlogPost::query()
            ->published()
            ->with('author')
            ->latest('published_at');

        if ($request->boolean('featured')) {
            $query->featured();
        }

        if ($request->filled('category')) {
            $query->where('category', $request->query('category'));
        }

        if ($request->filled('search')) {
            $locale = app()->getLocale();
            $like = '%' . $request->query('search') . '%';

           
            $query->where(function ($searchQuery) use ($locale, $like) {
                $searchQuery
                    ->whereRaw("COALESCE(JSON_UNQUOTE(JSON_EXTRACT(title, CONCAT('$.', ?))), JSON_UNQUOTE(JSON_EXTRACT(title, '$.en'))) LIKE ?", [$locale, $like])
                    ->orWhereRaw("COALESCE(JSON_UNQUOTE(JSON_EXTRACT(excerpt, CONCAT('$.', ?))), JSON_UNQUOTE(JSON_EXTRACT(excerpt, '$.en'))) LIKE ?", [$locale, $like])
                    ->orWhereRaw("COALESCE(JSON_UNQUOTE(JSON_EXTRACT(content, CONCAT('$.', ?))), JSON_UNQUOTE(JSON_EXTRACT(content, '$.en'))) LIKE ?", [$locale, $like])
                    ->orWhere('category', 'like', $like);
            });
        }

        $posts = $query->get();

        return BlogPostResource::collection($posts);
    }

    public function show(string $slug)
    {
        $post = BlogPost::query()
            ->published()
            ->with('author')
            ->where('slug', $slug)
            ->firstOrFail();

        $post->increment('view_count');

        return new BlogPostDetailResource($post);
    }
}