<?php

namespace Modules\MedRegistry\Http\Controllers;

use App\Utils\ModuleUtil;
use Modules\MedRegistry\Entities\MedregModule;

/**
 * Module catalog list — category filter, host-presence + install badges,
 * version, spec_key (P1-T2 registry UI).
 */
class RegistryController extends MedRegistryBaseController
{
    public function index()
    {
        $this->guard('medreg.registry.view');
        $this->guardSubscription();

        $category = request()->input('category');
        if (! in_array($category, MedregModule::CATEGORIES, true)) {
            $category = null;
        }

        $modules = MedregModule::when($category, function ($q) use ($category) {
                $q->where('category', $category);
            })
            ->orderBy('category')
            ->orderBy('sort_order')
            ->orderBy('module_key')
            ->get();

        // Install state (system.{module}_version) via the core util — never reimplemented.
        $moduleUtil = new ModuleUtil();
        $installed = [];
        foreach ($modules as $module) {
            $installed[$module->module_key] = $module->is_present
                && $moduleUtil->isModuleInstalled($module->module_key);
        }

        return view('medregistry::registry.index', [
            'modules'    => $modules,
            'installed'  => $installed,
            'categories' => MedregModule::CATEGORIES,
            'category'   => $category,
        ]);
    }
}
