<?php

namespace App\Http\Controllers\Api\Admin;

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

class CategoryController extends Controller
{
    /**
     * List all categories (admin).
     */
    public function index(Request $request)
    {
        $query = Category::withCount(['products', 'children']);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name_ar', 'like', "%{$search}%")
                    ->orWhere('name_en', 'like', "%{$search}%");
            });
        }

        if ($request->filled('parent_id')) {
            $query->where('parent_id', $request->parent_id);
        }

        if ($request->boolean('root_only')) {
            $query->whereNull('parent_id');
        }

        $categories = $query->orderBy('sort_order', 'asc')
            ->orderBy('name_ar', 'asc')
            ->get();

        return response()->json(['data' => $categories]);
    }

    /**
     * Create a new category.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name_ar' => 'required|string|max:255',
            'name_en' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:categories,slug',
            'description_ar' => 'nullable|string',
            'description_en' => 'nullable|string',
            'image' => 'nullable|image|max:2048',
            'parent_id' => 'nullable|exists:categories,id',
            'sort_order' => 'integer|min:0',
            'is_active' => 'boolean',
            'discount_percentage' => 'nullable|numeric|min:0|max:100',
        ]);

        $slug = $request->slug ?? Str::slug($request->name_en ?: $request->name_ar);

        // Ensure unique slug
        $originalSlug = $slug;
        $counter = 1;
        while (Category::where('slug', $slug)->exists()) {
            $slug = $originalSlug . '-' . $counter++;
        }

        $imagePath = null;
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('categories', 'public');
        }

        $category = Category::create([
            'name_ar' => $request->name_ar,
            'name_en' => $request->name_en,
            'slug' => $slug,
            'description_ar' => $request->description_ar,
            'description_en' => $request->description_en,
            'image' => $imagePath,
            'parent_id' => $request->parent_id,
            'sort_order' => $request->get('sort_order', 0),
            'is_active' => $request->boolean('is_active', true),
            'discount_percentage' => $request->get('discount_percentage', 0),
        ]);

        return response()->json([
            'message' => 'تم إنشاء التصنيف بنجاح',
            'data' => $category,
        ], 201);
    }

    /**
     * Show single category.
     */
    public function show(Category $category)
    {
        $category->load(['parent', 'children']);
        $category->loadCount(['products']);

        return response()->json(['data' => $category]);
    }

    /**
     * Update category.
     */
    public function update(Request $request, Category $category)
    {
        $request->validate([
            'name_ar' => 'sometimes|required|string|max:255',
            'name_en' => 'sometimes|required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:categories,slug,' . $category->id,
            'description_ar' => 'nullable|string',
            'description_en' => 'nullable|string',
            'image' => 'nullable|image|max:2048',
            'parent_id' => 'nullable|exists:categories,id',
            'sort_order' => 'integer|min:0',
            'is_active' => 'boolean',
            'discount_percentage' => 'nullable|numeric|min:0|max:100',
        ]);

        // Prevent self-referencing
        if ($request->parent_id == $category->id) {
            return response()->json(['message' => 'لا يمكن جعل التصنيف أباً لنفسه'], 422);
        }

        if ($request->hasFile('image')) {
            if ($category->image) {
                Storage::disk('public')->delete($category->image);
            }
            $category->image = $request->file('image')->store('categories', 'public');
        }

        $category->update(array_merge(
            $request->only([
                'name_ar', 'name_en', 'slug', 'description_ar', 'description_en',
                'parent_id', 'sort_order', 'is_active', 'discount_percentage',
            ]),
            ['image' => $category->image]
        ));

        return response()->json([
            'message' => 'تم تحديث التصنيف بنجاح',
            'data' => $category,
        ]);
    }

    /**
     * Delete category.
     */
    public function destroy(Category $category)
    {
        if ($category->products()->count() > 0) {
            return response()->json([
                'message' => 'لا يمكن حذف تصنيف يحتوي على منتجات',
            ], 422);
        }

        if ($category->children()->count() > 0) {
            return response()->json([
                'message' => 'لا يمكن حذف تصنيف يحتوي على تصنيفات فرعية',
            ], 422);
        }

        if ($category->image) {
            Storage::disk('public')->delete($category->image);
        }

        $category->delete();

        return response()->json([
            'message' => 'تم حذف التصنيف بنجاح',
        ]);
    }

    /**
     * Reorder categories.
     */
    public function reorder(Request $request)
    {
        $request->validate([
            'categories' => 'required|array',
            'categories.*.id' => 'required|exists:categories,id',
            'categories.*.sort_order' => 'required|integer|min:0',
        ]);

        foreach ($request->categories as $item) {
            Category::where('id', $item['id'])->update(['sort_order' => $item['sort_order']]);
        }

        return response()->json([
            'message' => 'تم إعادة ترتيب التصنيفات بنجاح',
        ]);
    }
}
