<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class MenuController extends Controller
{
    public function index()
    {
        // 🔐 Obtener rol (con fallback para pruebas)
        // $rol = session('rol_id') ?? 1;
        $user = Auth::user();

        $rol = $user->rol_id;
        // 📊 Consulta
        $menus = DB::select("
            SELECT m.*
            FROM menus m
            INNER JOIN role_menu rm ON rm.menu_id = m.id
            WHERE rm.rol_id = ?
            AND m.estado = 1
            ORDER BY m.parent_id, m.orden
        ", [$rol]);

        // 🧩 Separar padres e hijos
        $padres = [];
        $hijos = [];

        foreach ($menus as $menu) {
            if ($menu->parent_id == null) {
                $padres[] = $menu;
            } else {
                $hijos[$menu->parent_id][] = $menu;
            }
        }

        // 📤 Retornar vista principal (ejemplo dashboard)
        return view('dashboard', compact('padres', 'hijos'));
    }
}
