<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LibraryCategory;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use Illuminate\Support\Str;

class LibraryCategoryController extends Controller
{
    public function index(): View
    {
        $categories = LibraryCategory::with('parent', 'children')
            ->withCount('contents')
            ->orderBy('order')
            ->get();

        $totalContents = \App\Models\LibraryContent::count();

        return view('admin.library-categories.index', compact('categories', 'totalContents'));
    }

    public function create(): View
    {
        $parentCategories = LibraryCategory::whereNull('parent_id')
            ->orderBy('name')
            ->pluck('name', 'id');

        return view('admin.library-categories.create', compact('parentCategories'));
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name'        => 'required|string|max:255',
            'slug'        => 'nullable|string|max:255|unique:library_categories,slug',
            'description' => 'nullable|string',
            'parent_id'   => 'nullable|exists:library_categories,id',
            'order'       => 'nullable|integer|min:0',
            'icon'        => 'nullable|string|max:50',
            'color'       => 'nullable|string|max:20',
        ]);

        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        LibraryCategory::create($validated);

        return redirect()
            ->route('admin.library-categories.index')
            ->with('success', 'Kütüphane kategorisi oluşturuldu.');
    }

    public function edit(LibraryCategory $libraryCategory): View
    {
        $parentCategories = LibraryCategory::whereNull('parent_id')
            ->where('id', '!=', $libraryCategory->id)
            ->orderBy('name')
            ->pluck('name', 'id');

        return view('admin.library-categories.edit', compact('libraryCategory', 'parentCategories'));
    }

    public function update(Request $request, LibraryCategory $libraryCategory): RedirectResponse
    {
        $validated = $request->validate([
            'name'        => 'required|string|max:255',
            'slug'        => 'nullable|string|max:255|unique:library_categories,slug,' . $libraryCategory->id,
            'description' => 'nullable|string',
            'parent_id'   => 'nullable|exists:library_categories,id',
            'order'       => 'nullable|integer|min:0',
            'icon'        => 'nullable|string|max:50',
            'color'       => 'nullable|string|max:20',
        ]);

        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        $libraryCategory->update($validated);

        return redirect()
            ->route('admin.library-categories.index')
            ->with('success', 'Kütüphane kategorisi güncellendi.');
    }

    public function destroy(LibraryCategory $libraryCategory): RedirectResponse
    {
        if ($libraryCategory->children()->count() > 0) {
            return redirect()
                ->route('admin.library-categories.index')
                ->with('error', 'Bu kategorinin alt kategorileri olduğu için silinemez.');
        }

        if ($libraryCategory->contents()->count() > 0) {
            return redirect()
                ->route('admin.library-categories.index')
                ->with('error', 'Bu kategoride içerikler olduğu için silinemez.');
        }

        $libraryCategory->delete();

        return redirect()
            ->route('admin.library-categories.index')
            ->with('success', 'Kütüphane kategorisi silindi.');
    }
}
