<?php
// ─────────────────────────────────────────────────────────────
//  api/admin/modules.php — GET / POST module toggle state
//
//  Routed via api/index.php:
//    GET  /api/admin/modules   → list all toggles
//    POST /api/admin/modules   → { key, is_enabled: 0|1 }
// ─────────────────────────────────────────────────────────────
// lib.php, session, cors, api_require_admin, and init_booking_db
// are already called by api/index.php before this file is included.
// Do not duplicate those calls here.

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    json_out(['ok' => true, 'modules' => ModuleToggle::all()]);
    exit;
}

if ($method === 'POST') {
    // Use lib.php's cached body() so we don't re-read the already-consumed input stream
    $b       = body();
    $key     = trim($b['key'] ?? '');
    $enabled = isset($b['is_enabled']) ? (bool)(int)$b['is_enabled'] : null;

    if (!$key || $enabled === null) {
        json_out(['ok' => false, 'error' => 'key and is_enabled required'], 400);
    }

    $updated = ModuleToggle::set($key, $enabled);
    if (!$updated) {
        json_out(['ok' => false, 'error' => 'Unknown module key'], 404);
    }

    json_out(['ok' => true, 'key' => $key, 'is_enabled' => (int)$enabled]);
    exit;
}

json_out(['ok' => false, 'error' => 'Method not allowed'], 405);
