<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\KbArticleResource;
use App\Models\KbArticle;
use App\Models\KbCategory;
use Illuminate\Http\Request;
class KbApiController extends Controller
{
    public function index(Request $request) {
        $query = KbArticle::published()->with(['category','author']);
        if ($request->q) $query = KbArticle::search($request->q)->with(['category','author']);
        if ($request->category) $query->where('category_id',$request->category);
        if ($request->featured)  $query->featured();
        $query->orderByDesc($request->sort==='views'?'views':'published_at');
        return KbArticleResource::collection($query->paginate(min((int)($request->per_page??15),50)))->additional(['success'=>true]);
    }
    public function show(string $slug) {
        $article = KbArticle::published()->where('slug',$slug)->with(['category','author'])->firstOrFail();
        $article->incrementViews();
        return response()->json(['success'=>true,'data'=>new KbArticleResource($article)]);
    }
    public function categories() {
        $cats = KbCategory::active()->withCount(['articles'=>fn($q)=>$q->published()])->orderBy('order')->get()
            ->map(fn($c)=>['id'=>$c->id,'name'=>$c->name,'slug'=>$c->slug,'color'=>$c->color,'articles_count'=>$c->articles_count]);
        return response()->json(['success'=>true,'data'=>$cats]);
    }
    public function search(Request $request) {
        $request->validate(['q'=>'required|string|min:2']);
        $articles = KbArticle::search($request->q)->with('category')->limit(10)->get();
        return response()->json(['success'=>true,'data'=>KbArticleResource::collection($articles)]);
    }
}
