<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MenuItem;
use Illuminate\Http\Request;

class MenuItemController extends Controller
{
    public function index()
    {
        $items = MenuItem::orderBy('orden')->get();
        return view('admin.menu.index', compact('items'));
    }

    public function create()
    {
        return view('admin.menu.create');
    }

    public function store(Request $request)
    {
        // Normalizar campo orden: convertir string vacío a null
        $request->merge(['orden' => $request->filled('orden') ? (int)$request->orden : null]);

        $data = $request->validate([
            'label'  => 'required|string|max:100',
            'url'    => 'required|string|max:500',
            'icono'  => 'nullable|string|max:80',
            'orden'  => 'nullable|integer|min:0',
            'target' => 'required|in:_self,_blank',
        ]);

        $data['activo'] = $request->has('activo') ? 1 : 0;
        $data['orden']  = $data['orden'] ?? (MenuItem::max('orden') + 1);

        MenuItem::create($data);
        return redirect()->route('admin.menu-items.index')->with('success', 'Ítem de menú creado correctamente.');
    }

    public function edit(MenuItem $menuItem)
    {
        return view('admin.menu.edit', compact('menuItem'));
    }

    public function update(Request $request, MenuItem $menuItem)
    {
        // Normalizar campo orden
        $request->merge(['orden' => $request->filled('orden') ? (int)$request->orden : null]);

        $data = $request->validate([
            'label'  => 'required|string|max:100',
            'url'    => 'required|string|max:500',
            'icono'  => 'nullable|string|max:80',
            'orden'  => 'nullable|integer|min:0',
            'target' => 'required|in:_self,_blank',
        ]);

        $data['activo'] = $request->has('activo') ? 1 : 0;

        $menuItem->update($data);
        return redirect()->route('admin.menu-items.index')->with('success', 'Ítem de menú actualizado correctamente.');
    }

    public function destroy(MenuItem $menuItem)
    {
        $menuItem->delete();
        return redirect()->route('admin.menu-items.index')->with('success', 'Ítem de menú eliminado correctamente.');
    }

    /**
     * Reordenar ítems vía AJAX (drag-and-drop).
     * Espera JSON: { "order": [3, 1, 5, 2, ...] }
     */
    public function reorder(Request $request)
    {
        $request->validate(['order' => 'required|array']);

        foreach ($request->order as $position => $id) {
            MenuItem::where('id', $id)->update(['orden' => $position + 1]);
        }

        return response()->json(['ok' => true]);
    }
}
