<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreKbArticleRequest;
use App\Http\Requests\Admin\UpdateKbArticleRequest;
use App\Models\KnowledgeBaseArticle;
use App\Models\KnowledgeBaseCategory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class KnowledgeBaseArticleController extends Controller
{
    public function index(Request $request): Response
    {
        $query = KnowledgeBaseArticle::query()
            ->with(['category:id,name', 'author:id,name']);

        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search): void {
                $q->where('title', 'like', '%'.$search.'%')
                    ->orWhere('excerpt', 'like', '%'.$search.'%');
            });
        }

        if ($request->filled('category') && $request->input('category') !== 'all') {
            $query->where('category_id', $request->input('category'));
        }

        if ($request->filled('status') && $request->input('status') !== 'all') {
            $query->where('status', $request->input('status'));
        }

        $articles = $query
            ->orderByDesc('updated_at')
            ->paginate(25);

        $articles->getCollection()->transform(function (KnowledgeBaseArticle $article) {
            $article->setAttribute('helpful_percentage', $article->helpfulPercentage());

            return $article;
        });

        $categories = KnowledgeBaseCategory::query()
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Admin/KnowledgeBase/Articles/Index', [
            'articles' => $articles,
            'categories' => $categories,
            'filters' => [
                'search' => $request->input('search', ''),
                'category' => $request->input('category', 'all'),
                'status' => $request->input('status', 'all'),
            ],
        ]);
    }

    public function create(): Response
    {
        $categories = KnowledgeBaseCategory::query()
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Admin/KnowledgeBase/Articles/Create', [
            'categories' => $categories,
        ]);
    }

    public function store(StoreKbArticleRequest $request): RedirectResponse
    {
        $article = KnowledgeBaseArticle::query()->create([
            'title' => $request->validated('title'),
            'slug' => $request->validated('slug'),
            'category_id' => $request->validated('category_id'),
            'author_id' => $request->user()->id,
            'content' => $request->validated('content'),
            'excerpt' => $request->validated('excerpt'),
            'status' => $request->validated('status'),
            'is_featured' => $request->boolean('is_featured', false),
            'published_at' => $request->validated('status') === 'published' ? now() : null,
        ]);

        $article->revisions()->create([
            'content' => $request->validated('content'),
            'edited_by' => $request->user()->id,
        ]);

        return redirect()
            ->route('admin.kb.articles.index')
            ->with('success', 'Article created successfully.');
    }

    public function show(KnowledgeBaseArticle $article): Response
    {
        $article->load([
            'category:id,name,slug',
            'author:id,name',
            'revisions' => fn ($q) => $q->with('editor:id,name')->orderByDesc('created_at'),
        ]);

        $article->setAttribute('helpful_percentage', $article->helpfulPercentage());

        return Inertia::render('Admin/KnowledgeBase/Articles/Show', [
            'article' => $article,
        ]);
    }

    public function edit(KnowledgeBaseArticle $article): Response
    {
        $article->load([
            'revisions' => fn ($q) => $q->with('editor:id,name')->orderByDesc('created_at'),
        ]);

        $categories = KnowledgeBaseCategory::query()
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Admin/KnowledgeBase/Articles/Edit', [
            'article' => $article,
            'categories' => $categories,
        ]);
    }

    public function update(UpdateKbArticleRequest $request, KnowledgeBaseArticle $article): RedirectResponse
    {
        $wasPublished = $article->status === 'published';
        $nowPublished = $request->validated('status') === 'published';

        $article->update([
            'title' => $request->validated('title'),
            'slug' => $request->validated('slug'),
            'category_id' => $request->validated('category_id'),
            'content' => $request->validated('content'),
            'excerpt' => $request->validated('excerpt'),
            'status' => $request->validated('status'),
            'is_featured' => $request->boolean('is_featured', false),
            'published_at' => (! $wasPublished && $nowPublished) ? now() : $article->published_at,
        ]);

        $article->revisions()->create([
            'content' => $request->validated('content'),
            'edited_by' => $request->user()->id,
        ]);

        return redirect()
            ->route('admin.kb.articles.index')
            ->with('success', 'Article updated successfully.');
    }

    public function destroy(KnowledgeBaseArticle $article): RedirectResponse
    {
        $article->delete();

        return redirect()
            ->route('admin.kb.articles.index')
            ->with('success', 'Article deleted successfully.');
    }
}
