<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        if ($request->has('tree')) {
            $categories = Category::whereNull('parent_id')
                ->with(['children' => function($q) {
                    $q->select('id', 'name', 'parent_id', 'order')->orderBy('order', 'asc');
                }])
                ->select('id', 'name', 'order')
                ->orderBy('order', 'asc')
                ->get();
            
            return response()->json($categories);
        }

        // Flat List for Table
        $query = Category::with('parent');

        if ($search = $request->input('search')) {
            $query->where('name', 'like', "%{$search}%");
        }

        $categories = $query->orderBy('order', 'asc')->orderBy('created_at', 'desc')->get();

        return response()->json($categories);
    }

    // --- Reorder Method ---
    public function reorder(Request $request): JsonResponse
    {
        $request->validate([
            'categories' => 'required|array',
            'categories.*.id' => 'required|exists:categories,id',
            'categories.*.order' => 'required|integer',
            'categories.*.parent_id' => 'nullable|exists:categories,id'
        ]);

        DB::transaction(function () use ($request) {
            foreach ($request->categories as $item) {
                Category::where('id', $item['id'])->update([
                    'order' => $item['order'],
                    'parent_id' => $item['parent_id'] ?? null
                ]);
            }
        });

        return response()->json(['message' => 'Categories reordered successfully']);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'parent_id' => 'nullable|exists:categories,id'
        ]);

        $data['slug'] = Str::slug($data['name']);
        if (Category::where('slug', $data['slug'])->exists()) {
            $data['slug'] = $data['slug'] . '-' . uniqid();
        }
        
        $data['order'] = Category::where('parent_id', $data['parent_id'])->max('order') + 1;

        $category = Category::create($data);
        return response()->json($category, 201);
    }

    public function update(Request $request, Category $category): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'parent_id' => 'nullable|exists:categories,id'
        ]);

        if ($data['parent_id'] == $category->id) {
            return response()->json(['message' => 'Category cannot be its own parent.'], 422);
        }

        $data['slug'] = Str::slug($data['name']);
        if (Category::where('slug', $data['slug'])->where('id', '!=', $category->id)->exists()) {
             $data['slug'] = $data['slug'] . '-' . uniqid();
        }
        $category->update($data);
        return response()->json($category);
    }

    public function destroy(Category $category): JsonResponse
    {
        $category->delete();
        return response()->json(null, 204);
    }
}