<?php

namespace App\Http\Controllers;

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

class KbCategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // include articles_count for display
        $categories = KbCategory::withCount('articles')->with('parent')->latest()->paginate(15);
        return view('admin.kb.categories.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $parents = KbCategory::pluck('name','id');
        $products = \App\Models\Product::where('is_active', true)->get();
        return view('admin.kb.categories.create', compact('parents', 'products'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required','string','max:255'],
            'slug' => ['nullable','string','max:255','unique:kb_categories,slug'],
            'description' => ['nullable','string'],
            'parent_id' => ['nullable','exists:kb_categories,id'],
            'product_id' => ['nullable','exists:products,id'],
            'serial' => ['nullable','string','max:255'],
            'requires_serial' => ['sometimes','boolean'],
            'serial_message' => ['nullable','string'],
            'meta_title' => ['nullable','string','max:255'],
            'meta_description' => ['nullable','string','max:500'],
            'meta_keywords' => ['nullable','string','max:255'],
            'icon' => ['nullable','string','max:255'],
            'is_featured' => ['sometimes','boolean'],
            'is_active' => ['sometimes','boolean'],
            'sort_order' => ['nullable','integer','min:0'],
        ]);
        $validated['slug'] = $validated['slug'] ?: Str::slug($validated['name']);
        KbCategory::create($validated);
        return redirect()->route('admin.kb-categories.index')->with('success', 'Category created');
    }

    /**
     * Display the specified resource.
     */
    public function show(KbCategory $kbCategory)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(KbCategory $kbCategory)
    {
        $parents = KbCategory::where('id','!=',$kbCategory->id)->pluck('name','id');
        $products = \App\Models\Product::where('is_active', true)->get();
        return view('admin.kb.categories.edit', ['category'=>$kbCategory, 'parents'=>$parents, 'products'=>$products]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, KbCategory $kbCategory)
    {
        $validated = $request->validate([
            'name' => ['required','string','max:255'],
            'slug' => ['required','string','max:255','unique:kb_categories,slug,'.$kbCategory->id],
            'description' => ['nullable','string'],
            'parent_id' => ['nullable','exists:kb_categories,id'],
            'product_id' => ['nullable','exists:products,id'],
            'serial' => ['nullable','string','max:255'],
            'requires_serial' => ['sometimes','boolean'],
            'serial_message' => ['nullable','string'],
            'meta_title' => ['nullable','string','max:255'],
            'meta_description' => ['nullable','string','max:500'],
            'meta_keywords' => ['nullable','string','max:255'],
            'icon' => ['nullable','string','max:255'],
            'is_featured' => ['sometimes','boolean'],
            'is_active' => ['sometimes','boolean'],
            'sort_order' => ['nullable','integer','min:0'],
        ]);
        $kbCategory->update($validated);
        return back()->with('success', 'Category updated');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(KbCategory $kbCategory)
    {
        // Support two deletion modes via request param 'delete_mode':
        // - with_articles : delete category and all its articles
        // - keep_articles : move articles to 'uncategorized' category (created if missing)
        $mode = request('delete_mode', 'keep_articles');

        if ($mode === 'with_articles') {
            // delete articles and category
            $kbCategory->articles()->delete();
            $kbCategory->delete();
        } else {
            // move articles to uncategorized (create if necessary)
            $uncat = KbCategory::firstOrCreate(
                ['slug' => 'uncategorized'],
                ['name' => 'Uncategorized', 'description' => 'Auto-created category for uncategorized articles']
            );
            $kbCategory->articles()->update(['kb_category_id' => $uncat->id]);
            $kbCategory->delete();
        }

        return redirect()->route('admin.kb-categories.index')->with('success', 'Category deleted');
    }
}
