<?php

namespace App\Models;

use App\Core\Model;

class Menu extends Model
{
    protected static string $table = 'iw_menus';

    /**
     * Get visible menu items as a flat list (legacy, backwards-compatible).
     */
    public static function getItems(string $location): array
    {
        $menu = static::findWhere(['location' => $location]);
        if (!$menu) {
            return [];
        }

        return static::db()->fetchAll(
            "SELECT * FROM iw_menu_items WHERE menu_id = :menu_id AND is_visible = 1 ORDER BY sort_order ASC",
            ['menu_id' => $menu['id']]
        );
    }

    /**
     * Get visible menu items as a hierarchical tree.
     * Each item with children gets a 'children' array.
     */
    public static function getItemsTree(string $location): array
    {
        $items = static::getItems($location);
        return self::buildTree($items, null);
    }

    /**
     * Build a nested tree from a flat list of items.
     */
    private static function buildTree(array $items, ?int $parentId): array
    {
        $branch = [];
        foreach ($items as $item) {
            $itemParent = $item['parent_id'] !== null ? (int) $item['parent_id'] : null;
            if ($itemParent === $parentId) {
                $item['children'] = self::buildTree($items, (int) $item['id']);
                $branch[] = $item;
            }
        }
        return $branch;
    }
}
