<?php
namespace App\Http\Controllers;

use App\Models\KbArticle;
use App\Models\KbCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class KbAdminController extends Controller
{
    private function authorize(): void {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte','agente']), 403);
    }

    // ── Lista de artículos para gestión ───────────────────────────────────────
    public function index(Request $request)
    {
        $this->authorize();
        $articles = KbArticle::withTrashed()
            ->with(['category','author'])
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->when($request->category, fn($q) => $q->where('category_id', $request->category))
            ->latest()->paginate(20);
        $categories = KbCategory::active()->get();
        return view('kb.admin.index', compact('articles','categories'));
    }

    // ── Formulario crear ──────────────────────────────────────────────────────
    public function create()
    {
        $this->authorize();
        $categories = KbCategory::active()->roots()->with('children')->get();
        return view('kb.admin.create', compact('categories'));
    }

    // ── Guardar artículo ──────────────────────────────────────────────────────
    public function store(Request $request)
    {
        $this->authorize();
        $data = $request->validate([
            'title'       => 'required|string|max:255',
            'content'     => 'required|string',
            'category_id' => 'nullable|exists:kb_categories,id',
            'status'      => 'required|in:draft,published,archived',
            'featured'    => 'boolean',
            'tags'        => 'nullable|string|max:500',
        ]);

        $data['author_id']    = auth()->id();
        $data['published_at'] = $data['status'] === 'published' ? now() : null;
        $data['featured']     = $request->boolean('featured');

        $article = KbArticle::create($data);
        return redirect()->route('kb.admin.edit', $article)
            ->with('success', 'Artículo creado correctamente.');
    }

    // ── Formulario editar ─────────────────────────────────────────────────────
    public function edit(KbArticle $article)
    {
        $this->authorize();
        $categories = KbCategory::active()->roots()->with('children')->get();
        return view('kb.admin.edit', compact('article','categories'));
    }

    // ── Actualizar artículo ───────────────────────────────────────────────────
    public function update(Request $request, KbArticle $article)
    {
        $this->authorize();
        $data = $request->validate([
            'title'       => 'required|string|max:255',
            'content'     => 'required|string',
            'category_id' => 'nullable|exists:kb_categories,id',
            'status'      => 'required|in:draft,published,archived',
            'featured'    => 'boolean',
            'tags'        => 'nullable|string|max:500',
        ]);

        $data['featured'] = $request->boolean('featured');

        // Publicar por primera vez
        if ($data['status'] === 'published' && !$article->published_at) {
            $data['published_at'] = now();
        }

        $article->update($data);
        return redirect()->route('kb.admin.edit', $article)->with('success', 'Artículo actualizado.');
    }

    // ── Eliminar ──────────────────────────────────────────────────────────────
    public function destroy(KbArticle $article)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $article->delete();
        return redirect()->route('kb.admin.index')->with('success', 'Artículo eliminado.');
    }
}
