<?php

namespace App\Services;

use App\Models\NavItemModel;
use App\Models\RoleNavItemModel;
use CodeIgniter\Cache\CacheInterface;

class NavbarService
{
    public function __construct(
        protected NavItemModel $navModel = new NavItemModel(),
        protected RoleNavItemModel $mapModel = new RoleNavItemModel(),
        protected ?CacheInterface $cache = null
    ){
        $this->cache ??= cache();
    }

    public function getMenuForRoles(array $roles): array
    {
        $roles = array_map(fn($r)=>strtolower(trim((string)$r)), $roles);
        $cacheKey = 'navbar_' . md5(json_encode($roles));

        if ($menu = $this->cache->get($cacheKey)) {
            return $menu;
        }

        // Which items this user can see
        $allowedIds = $this->mapModel->getNavItemIdsForRoles($roles);
        if (empty($allowedIds)) return [];

        // Load all enabled items, then filter
        $rows = $this->navModel->where('is_enabled', 1)
            ->orderBy('sort_order', 'ASC')
            ->findAll();

        // index by id
        $byId = [];
        foreach ($rows as $r) {
            if (in_array($r['id'], $allowedIds, true)) {
                $r['children'] = [];
                $byId[$r['id']] = $r;
            }
        }

        // Build tree
        $tree = [];
        foreach ($byId as $id => &$node) {
            $pid = $node['menu_parent_id'];
            if ($pid && isset($byId[$pid])) {
                $byId[$pid]['children'][] = &$node;
            } else {
                $tree[] = &$node;
            }
        }

        $this->cache->save($cacheKey, $tree, 300); // 5 minutes
        return $tree;
    }

    public function clearCache(): void
    {
        // simplest: flush; or if you have a tagged cache, clear only keys
        cache()->clean();
    }
}
