<?php

namespace App\Http\Controllers;

use App\Models\InventoryCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class InventoryCategoryController extends Controller
{
    /**
     * Display a listing of the inventory categories.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $parentCategories = InventoryCategory::whereNull('parent_id')
            ->with('children')
            ->withCount('items as inventory_count')
            ->orderBy('name')
            ->get();
            
        return view('admin.inventory.categories.index', compact('parentCategories'));
    }

    /**
     * Show the form for creating a new inventory category.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $parentCategories = InventoryCategory::whereNull('parent_id')
            ->orderBy('name')
            ->get();
            
        return view('admin.inventory.categories.create', compact('parentCategories'));
    }

    /**
     * Store a newly created inventory category in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'parent_id' => 'nullable|exists:inventory_categories,id',
            'icon' => 'nullable|string|max:50',
            'is_active' => 'boolean',
        ]);
        
        // Verificación adicional para evitar categorías duplicadas
        $existingCategory = InventoryCategory::where('name', $request->name)->whereNull('deleted_at')->exists();
        if ($existingCategory) {
            return back()->withErrors(['name' => __('inventory.error.category_duplicate')])->withInput();
        }
        
        // Valores por defecto
        $validatedData['is_active'] = $request->has('is_active') ? 1 : 0;
        
        // Crear la categoría
        $category = InventoryCategory::create($validatedData);
        
        return redirect()->route('inventory.categories.index')
            ->with('success', __('inventory.success.category_created'));
    }

    /**
     * Display the specified inventory category.
     *
     * @param  \App\Models\InventoryCategory  $category
     * @return \Illuminate\Http\Response
     */
    public function show(InventoryCategory $category)
    {
        $category->load('parent', 'children', 'items');
        
        return view('admin.inventory.categories.show', compact('category'));
    }

    /**
     * Show the form for editing the specified inventory category.
     *
     * @param  \App\Models\InventoryCategory  $category
     * @return \Illuminate\Http\Response
     */
    public function edit(InventoryCategory $category)
    {
        $parentCategories = InventoryCategory::whereNull('parent_id')
            ->where('id', '!=', $category->id)
            ->orderBy('name')
            ->get();
            
        return view('admin.inventory.categories.edit', compact('category', 'parentCategories'));
    }

    /**
     * Update the specified inventory category in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\InventoryCategory  $category
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, InventoryCategory $category)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'parent_id' => 'nullable|exists:inventory_categories,id',
            'icon' => 'nullable|string|max:50',
            'is_active' => 'boolean',
        ]);
        
        // Verificación adicional para evitar categorías duplicadas
        $existingCategory = InventoryCategory::where('name', $request->name)
            ->where('id', '!=', $category->id)
            ->whereNull('deleted_at')
            ->exists();
            
        if ($existingCategory) {
            return back()->withErrors(['name' => __('inventory.error.category_duplicate_update')])->withInput();
        }
        
        // Validar que no se establezca a sí misma como padre
        if ($request->parent_id == $category->id) {
            return back()->withErrors(['parent_id' => __('inventory.error.category_self_parent')])
                        ->withInput();
        }
        
        // Validar que no se establezca como padre a una de sus hijas (evitar ciclos)
        $childrenIds = $category->children()->pluck('id')->toArray();
        if (in_array($request->parent_id, $childrenIds)) {
            return back()->withErrors(['parent_id' => __('inventory.error.category_subcategory_parent')])
                        ->withInput();
        }
        
        // Valores por defecto
        $validatedData['is_active'] = $request->has('is_active') ? 1 : 0;
        
        // Actualizar la categoría
        $category->update($validatedData);
        
        return redirect()->route('inventory.categories.index')
            ->with('success', __('inventory.success.category_updated'));
    }

    /**
     * Remove the specified inventory category from storage.
     *
     * @param  \App\Models\InventoryCategory  $category
     * @return \Illuminate\Http\Response
     */
    public function destroy(InventoryCategory $category)
    {
        // Verificar si la categoría tiene ítems asociados
        if ($category->items()->count() > 0) {
            return back()->with('error', __('inventory.error.category_has_items'));
        }
        
        // Verificar si la categoría tiene subcategorías
        if ($category->children()->count() > 0) {
            return back()->with('error', __('inventory.error.category_has_children'));
        }
        
        // Eliminar la categoría
        $category->delete();
        
        return redirect()->route('inventory.categories.index')
            ->with('success', __('inventory.success.category_deleted'));
    }
} 