<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Services\AuditLogService;
use App\Services\ProductTranslationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CategoryController extends Controller
{
    protected AuditLogService $audit;
    protected ProductTranslationService $translator;

    public function __construct(AuditLogService $audit, ProductTranslationService $translator)
    {
        $this->audit      = $audit;
        $this->translator = $translator;
    }

    public function index()
    {
        $categories = Category::with('parent')
            ->orderBy('name_en')
            ->paginate(50);
        return view('categories.index', compact('categories'));
    }

    public function create()
    {
        $parents = Category::where('status', 'active')->orderBy('name_en')->get();
        return view('categories.create', compact('parents'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'code'           => 'nullable|string|max:50|unique:categories,code',
            'name_en'        => 'required|string|max:200',
            'name_ar'        => 'required|string|max:200',
            'parent_id'      => 'nullable|exists:categories,id',
            'description_en' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'status'         => 'required|in:active,inactive',
        ]);

        // Auto-generate code if empty
        if (empty($validated['code'])) {
            $validated['code'] = strtoupper(substr(preg_replace('/\s+/', '', $validated['name_en']), 0, 6)) . rand(10, 99);
        }

        $category = Category::create($validated);
        $this->audit->log('CATEGORY_CREATED', 'categories', $category->id, null, $validated);

        return redirect()->route('categories.index')
            ->with('success', 'Category created successfully.');
    }

    public function edit(Category $category)
    {
        $parents = Category::where('status', 'active')
            ->where('id', '!=', $category->id)
            ->orderBy('name_en')
            ->get();
        return view('categories.edit', compact('category', 'parents'));
    }

    public function update(Request $request, Category $category)
    {
        $validated = $request->validate([
            'code'           => 'nullable|string|max:50|unique:categories,code,' . $category->id,
            'name_en'        => 'required|string|max:200',
            'name_ar'        => 'required|string|max:200',
            'parent_id'      => 'nullable|exists:categories,id',
            'description_en' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'status'         => 'required|in:active,inactive',
        ]);

        $old = $category->toArray();
        $category->update($validated);
        $this->audit->log('CATEGORY_UPDATED', 'categories', $category->id, $old, $validated);

        return redirect()->route('categories.index')
            ->with('success', 'Category updated successfully.');
    }

    /**
     * AJAX endpoint: auto-suggest Arabic translation for a category name.
     */
    public function translateSuggest(Request $request)
    {
        $english = $request->input('text', '');
        $arabic  = $this->translator->suggest($english);
        return response()->json(['arabic' => $arabic]);
    }

    /**
     * AJAX endpoint: return nested categories for select.
     */
    public function apiList(Request $request)
    {
        $categories = Category::where('status', 'active')
            ->when($request->parent_id, fn($q) => $q->where('parent_id', $request->parent_id))
            ->orderBy('name_en')
            ->get(['id', 'name_en', 'name_ar', 'parent_id']);
        return response()->json($categories);
    }
}
