<?php
// pages/components/toggle_module_status.php
// HTMX endpoint to toggle a module's _STATUS configuration (session-backed demo)

if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

if (!defined('BEEZUI_ROOT')) {
    define('BEEZUI_ROOT', dirname(__DIR__, 2)); // pages/components => root
}

require_once BEEZUI_ROOT . '/vendor/autoload.php';
require_once BEEZUI_ROOT . '/components/Autoload.php';
require_once BEEZUI_ROOT . '/components/index.php';

use Components\ModuleLoader;
use Components\Base;
use Components\ConfigStore;

$module = mh_get('module', '', 'key');
if ($module === '') {
    http_response_code(400);
    echo '<div class="text-sm text-red-600">Missing module key</div>';
    return;
}

// Determine desired state from POST: checkbox named "status"
$on = mh_post('status', null) !== null;
ConfigStore::setModuleStatus($module, $on);

// Load module data and render the full card so the client can swap the entire module container
$all = ModuleLoader::all();
$m = $all[$module] ?? null;
if (!$m) {
    http_response_code(404);
    echo '<div class="text-sm text-red-600">Unknown module: ' . Base::h($module) . '</div>';
    return;
}

include __DIR__ . '/trigger_module.php';
