<?php

namespace Modules\SystemCore\App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\SystemCore\App\Models\CoreProductCategory;

class ProductCategoryController extends Controller
{
    public function index()
    {
        return view('systemcore::product-categories.index');
    }

    public function indexAjax(Request $request)
    {
        $query = CoreProductCategory::with('parent')
            ->select('core_product_categories.*');

        // Search
        if ($request->filled('search.value')) {
            $search = $request->input('search.value');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('code', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Filter by active status
        if ($request->filled('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        return datatables($query)
            ->addColumn('actions', function ($category) {
                return view('components.datatable-actions', [
                    'id' => $category->id,
                    'actions' => [
                        ['label' => __('Edit'), 'icon' => 'bx bx-edit', 'url' => route('systemcore.product-categories.edit', $category->id)],
                        ['label' => __('Delete'), 'icon' => 'bx bx-trash', 'onclick' => "deleteProductCategory({$category->id})"],
                    ],
                ])->render();
            })
            ->editColumn('parent_id', fn ($category) => $category->parent?->name ?? '-')
            ->editColumn('is_active', fn ($category) => $category->is_active ? '<span class="badge bg-success">'.__('Active').'</span>' : '<span class="badge bg-secondary">'.__('Inactive').'</span>')
            ->editColumn('description', fn ($category) => $category->description ?? '-')
            ->rawColumns(['is_active', 'actions'])
            ->make(true);
    }

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

        return view('systemcore::product-categories.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:core_product_categories,code',
            'parent_id' => 'nullable|exists:core_product_categories,id',
            'description' => 'nullable|string',
            'display_order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
        ]);

        CoreProductCategory::create($validated);

        return redirect()->route('systemcore.product-categories.index')
            ->with('success', __('Product category created successfully'));
    }

    public function edit(CoreProductCategory $productCategory)
    {
        $categories = CoreProductCategory::active()
            ->where('id', '!=', $productCategory->id)
            ->orderBy('name')
            ->get(['id', 'name']);

        return view('systemcore::product-categories.edit', compact('productCategory', 'categories'));
    }

    public function update(Request $request, CoreProductCategory $productCategory)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:core_product_categories,code,'.$productCategory->id,
            'parent_id' => 'nullable|exists:core_product_categories,id',
            'description' => 'nullable|string',
            'display_order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
        ]);

        // Prevent circular parent relationship
        if ($validated['parent_id'] == $productCategory->id) {
            return back()->withErrors(['parent_id' => __('A category cannot be its own parent')])->withInput();
        }

        $productCategory->update($validated);

        return redirect()->route('systemcore.product-categories.index')
            ->with('success', __('Product category updated successfully'));
    }

    public function destroy(CoreProductCategory $productCategory)
    {
        // Check if category has children
        $childrenCount = $productCategory->children()->count();
        if ($childrenCount > 0) {
            return response()->json([
                'success' => false,
                'message' => __('Cannot delete category. It has :count sub-category(ies).', [
                    'count' => $childrenCount,
                ]),
            ], 422);
        }

        // Check if category is being used
        $productsCount = $productCategory->products()->count();
        if ($productsCount > 0) {
            return response()->json([
                'success' => false,
                'message' => __('Cannot delete category. It is being used by :count product(s).', [
                    'count' => $productsCount,
                ]),
            ], 422);
        }

        $productCategory->delete();

        return response()->json([
            'success' => true,
            'message' => __('Product category deleted successfully'),
        ]);
    }

    public function search(Request $request)
    {
        $search = $request->get('search', '');

        $categories = CoreProductCategory::where('name', 'like', "%{$search}%")
            ->orWhere('code', 'like', "%{$search}%")
            ->limit(20)
            ->get(['id', 'code', 'name']);

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