<?php
namespace App\Http\Controllers;

use App\Models\KbArticle;
use App\Models\KbCategory;
use App\Models\KbVote;
use Illuminate\Http\Request;

class KbController extends Controller
{
    // ── Portada de la base de conocimiento ───────────────────────────────────
    public function index(Request $request)
    {
        $query    = $request->input('q');
        $featured = KbArticle::published()->featured()->with('category')->latest()->limit(4)->get();
        $categories = KbCategory::active()->roots()
            ->with(['children', 'articles' => fn($q) => $q->published()])
            ->withCount(['articles' => fn($q) => $q->published()])
            ->orderBy('order')->get();

        $articles = null;
        if ($query) {
            $articles = KbArticle::search($query)->with('category')->paginate(10)->withQueryString();
        }

        $recent = KbArticle::published()->with('category')->latest('published_at')->limit(5)->get();

        return view('kb.index', compact('featured','categories','articles','query','recent'));
    }

    // ── Artículo individual ───────────────────────────────────────────────────
    public function show(string $slug)
    {
        $article = KbArticle::published()->where('slug', $slug)
            ->with(['category','author'])->firstOrFail();

        $article->incrementViews();

        // Artículos relacionados por categoría
        $related = KbArticle::published()
            ->where('id', '!=', $article->id)
            ->where('category_id', $article->category_id)
            ->latest()->limit(4)->get();

        return view('kb.show', compact('article', 'related'));
    }

    // ── Categoría ─────────────────────────────────────────────────────────────
    public function category(string $slug)
    {
        $category = KbCategory::active()->where('slug', $slug)
            ->with(['parent','children'])->firstOrFail();

        $articles = KbArticle::published()
            ->where('category_id', $category->id)
            ->with('author')
            ->orderByDesc('views')
            ->paginate(12);

        return view('kb.category', compact('category', 'articles'));
    }

    // ── Votar utilidad ────────────────────────────────────────────────────────
    public function vote(Request $request, KbArticle $article)
    {
        $request->validate(['helpful' => 'required|boolean']);
        $helpful = $request->boolean('helpful');

        $vote = KbVote::where('article_id', $article->id)
            ->where('user_id', auth()->id())->first();

        if ($vote) {
            // Cambiar voto
            if ($vote->helpful !== $helpful) {
                if ($helpful) {
                    $article->increment('helpful_yes');
                    $article->decrement('helpful_no');
                } else {
                    $article->increment('helpful_no');
                    $article->decrement('helpful_yes');
                }
                $vote->update(['helpful' => $helpful]);
            }
        } else {
            KbVote::create(['article_id'=>$article->id,'user_id'=>auth()->id(),'helpful'=>$helpful]);
            $helpful ? $article->increment('helpful_yes') : $article->increment('helpful_no');
        }

        return back()->with('success', '¡Gracias por tu valoración!');
    }

    // ── API: sugerencias al crear ticket ─────────────────────────────────────
    public function suggest(Request $request)
    {
        $q = $request->input('q', '');
        if (strlen($q) < 3) return response()->json([]);

        $articles = KbArticle::search($q)
            ->select(['id','title','slug','excerpt'])
            ->limit(5)
            ->get()
            ->map(fn($a) => [
                'id'      => $a->id,
                'title'   => $a->title,
                'excerpt' => $a->excerpt,
                'url'     => route('kb.show', $a->slug),
            ]);

        return response()->json($articles);
    }
}
