<?php

namespace AleshaCMS\Http\Controllers\Admin;

use AleshaCMS\Http\Controllers\Controller;
use AleshaCMS\Models\CMS\Taxonomy;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class TaxonomyController extends Controller
{
    public function index(Request $request, string $type = 'category')
    {
        $terms = Taxonomy::where('type', $type)
            ->with('parent')
            ->withCount('posts')
            ->when($request->search, fn($q) => $q->where('name', 'like', "%{$request->search}%"))
            ->latest()
            ->paginate(20);

        if ($request->wantsJson()) {
            return response()->json([
                'data' => $terms->map(fn($t) => [
                    'id'          => $t->id,
                    'name'        => $t->name,
                    'slug'        => $t->slug,
                    'description' => $t->description,
                    'parent'      => $t->parent?->name,
                    'posts_count' => $t->posts_count,
                    'edit_url'    => route('admin.taxonomies.edit', [$type, $t->id]),
                ]),
                'meta' => [
                    'current_page' => $terms->currentPage(),
                    'last_page'    => $terms->lastPage(),
                    'total'        => $terms->total(),
                ],
            ]);
        }

        $parents = Taxonomy::where('type', $type)->whereNull('parent_id')->get();
        return view('admin.taxonomies.index', compact('type', 'terms', 'parents'));
    }

    public function store(Request $request, string $type = 'category')
    {
        $data = $request->validate([
            'name'        => 'required|string|max:100',
            'slug'        => 'nullable|string|max:100|unique:taxonomies',
            'description' => 'nullable|string',
            'parent_id'   => 'nullable|exists:taxonomies,id',
        ]);

        $data['slug']  = $data['slug'] ?? Str::slug($data['name']);
        $data['type']  = $type;

        $term = Taxonomy::create($data);

        if ($request->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => ucfirst($type) . ' created.',
                'term'    => [
                    'id'          => $term->id,
                    'name'        => $term->name,
                    'slug'        => $term->slug,
                    'description' => $term->description,
                    'parent'      => null,
                    'posts_count' => 0,
                    'edit_url'    => route('admin.taxonomies.edit', [$type, $term->id]),
                ],
            ]);
        }

        return back()->with('success', ucfirst($type) . ' created.');
    }

    public function edit(string $type, Taxonomy $taxonomy)
    {
        $parents = Taxonomy::where('type', $type)
            ->where('id', '!=', $taxonomy->id)
            ->whereNull('parent_id')
            ->get();

        return view('admin.taxonomies.edit', compact('type', 'taxonomy', 'parents'));
    }

    public function update(Request $request, string $type, Taxonomy $taxonomy)
    {
        $data = $request->validate([
            'name'        => 'required|string|max:100',
            'slug'        => 'nullable|string|max:100|unique:taxonomies,slug,' . $taxonomy->id,
            'description' => 'nullable|string',
            'parent_id'   => 'nullable|exists:taxonomies,id',
        ]);

        $data['slug'] = $data['slug'] ?? Str::slug($data['name']);
        $taxonomy->update($data);

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'message' => ucfirst($type) . ' updated.']);
        }

        return back()->with('success', ucfirst($type) . ' updated.');
    }

    public function destroy(string $type, Taxonomy $taxonomy)
    {
        $taxonomy->delete();

        if (request()->wantsJson()) {
            return response()->json(['success' => true, 'message' => ucfirst($type) . ' deleted.']);
        }

        return redirect()->route('admin.taxonomies.index', $type)->with('success', ucfirst($type) . ' deleted.');
    }
}
