<?php
// =============================================================================
// modules.php — Module loader.
//
// Each module lives at `modules/<id>/module.php` and returns a manifest:
//
//   return [
//       'id'      => 'iboultra',            // url-safe, unique
//       'label'   => 'IBO Ultra',
//       'enabled' => true,                  // disable without deleting the folder
//       'sort'    => 10,                    // smaller = earlier
//       'sidebar' => [
//           [
//               'section' => 'OTT Applications',           // header above the group
//               'parent'  => [                             // optional collapsible parent
//                   'label' => 'IBO Ultra',
//                   'icon'  => 'ph-television',            // phosphor class
//                   'image' => 'iboultra.png',             // panel/assets/images/<file>
//               ],
//               'pages' => [
//                   ['key' => 'services_clients', 'href' => 'services_clients.php', 'label' => 'Services & Clients'],
//                   ...
//               ],
//           ],
//           // More sidebar groups in this same module are allowed.
//       ],
//   ];
//
// Pages whose `href` starts with `modules/<id>/` resolve relative to the panel
// root (because `<base href>` already points there). Pages with bare filenames
// resolve to the panel root too. Modules that put their files inside their own
// folder should write the full `modules/<id>/<file>.php` path.
// =============================================================================

function panel_modules() {
    static $cache = null;
    if ($cache !== null) return $cache;

    $dir = realpath(__DIR__ . '/../modules');
    $out = [];
    if ($dir !== false && is_dir($dir)) {
        foreach (glob($dir . '/*/module.php') as $manifest_path) {
            $manifest = @include $manifest_path;
            if (!is_array($manifest) || empty($manifest['id'])) continue;
            if (array_key_exists('enabled', $manifest) && !$manifest['enabled']) continue;
            $manifest['_dir']  = dirname($manifest_path);
            $manifest['_path'] = 'modules/' . basename(dirname($manifest_path));
            $out[$manifest['id']] = $manifest;
        }
    }
    uasort($out, function ($a, $b) {
        $sa = isset($a['sort']) ? (int)$a['sort'] : 100;
        $sb = isset($b['sort']) ? (int)$b['sort'] : 100;
        if ($sa === $sb) return strcmp((string)$a['label'], (string)$b['label']);
        return $sa - $sb;
    });
    return $cache = $out;
}

// Build the sidebar in the shape the renderer wants:
//   [
//     'OTT Applications' => [
//        ['kind' => 'flat',      'page' => ['key'=>..,'href'=>..,'label'=>..,'image'=>..]],
//        ['kind' => 'group',     'parent' => [...], 'pages' => [...]],
//     ],
//     'Android WebViews' => [...],
//   ]
function panel_sidebar() {
    $sections = [];
    foreach (panel_modules() as $mod) {
        $sidebars = $mod['sidebar'] ?? [];
        foreach ($sidebars as $sb) {
            $section = (string)($sb['section'] ?? 'Other');
            $pages   = is_array($sb['pages'] ?? null) ? $sb['pages'] : [];
            if (!isset($sections[$section])) $sections[$section] = [];
            if (!empty($sb['parent'])) {
                $sections[$section][] = [
                    'kind'   => 'group',
                    'parent' => $sb['parent'],
                    'pages'  => $pages,
                ];
            } else {
                foreach ($pages as $p) {
                    $sections[$section][] = ['kind' => 'flat', 'page' => $p];
                }
            }
        }
    }
    return $sections;
}

// All page keys across the whole sidebar — used by the header to figure out
// which section to auto-expand based on the current active page.
function panel_sidebar_keys_in_section($sidebar_section_entries) {
    $keys = [];
    foreach ($sidebar_section_entries as $entry) {
        if ($entry['kind'] === 'flat') {
            if (!empty($entry['page']['key'])) $keys[] = $entry['page']['key'];
        } else { // group
            foreach ($entry['pages'] as $p) {
                if (!empty($p['key'])) $keys[] = $p['key'];
            }
        }
    }
    return $keys;
}
