<?php

namespace App\Models;

use CodeIgniter\Model;

class MenuItemModel extends Model
{
    protected $table         = 'menu_items';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $allowedFields = ['parent_id', 'title', 'url', 'target', 'icon', 'section_key', 'sort_order', 'status', 'type', 'page_id'];
    protected $useTimestamps = true;

    public function getActiveTree()
    {
        $items = $this->where('status', 1)->orderBy('sort_order', 'ASC')->findAll();
        return $this->buildTree($items);
    }

    public function buildTree(array $items, $parentId = null)
    {
        $branch = [];
        foreach ($items as $item) {
            if ($item['parent_id'] === $parentId) {
                $children = $this->buildTree($items, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $branch[] = $item;
            }
        }
        return $branch;
    }

    public function getFlatTree()
    {
        $items = $this->orderBy('sort_order', 'ASC')->findAll();
        $tree  = $this->buildTree($items);
        $flat  = [];
        $this->flattenTree($tree, $flat);
        return $flat;
    }

    private function flattenTree(array $tree, array &$flat)
    {
        foreach ($tree as $item) {
            $children = $item['children'] ?? [];
            unset($item['children']);
            $flat[] = $item;
            if (!empty($children)) {
                $this->flattenTree($children, $flat);
            }
        }
    }

    public function getDescendantIds($id)
    {
        $ids = [];
        $children = $this->where('parent_id', $id)->findAll();
        foreach ($children as $child) {
            $ids[] = $child['id'];
            $ids = array_merge($ids, $this->getDescendantIds($child['id']));
        }
        return $ids;
    }
}
