<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| TechStackBase – System Modules API
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/response.php';
require_once __DIR__ . '/../system/audit.php';

/* =========================
   AUTH
   ========================= */
$actor = require_auth($pdo);

if (!in_array($actor['role_key'], ['super_admin', 'platform_admin'], true)) {
    error_forbidden('Forbidden');
}

$method = $_SERVER['REQUEST_METHOD'];

/* =========================
   GET — LIST MODULES
   ========================= */
if ($method === 'GET') {

    $stmt = $pdo->query("
        SELECT
            id,
            module_key,
            code,
            name,
            description,
            is_core,
            is_reserved,
            icon,
            sort_order,
            active,
            created_at
        FROM modules
        ORDER BY sort_order ASC, id ASC
    ");

    success('Modules loaded', $stmt->fetchAll(PDO::FETCH_ASSOC));
}

/* =========================
   POST — CREATE MODULE
   ========================= */
if ($method === 'POST') {

    $input = json_decode(file_get_contents('php://input'), true);

    if (!is_array($input)) {
        error_bad_request('Invalid JSON');
    }

    $moduleKey = trim((string)($input['module_key'] ?? ''));
    $name      = trim((string)($input['name'] ?? ''));
    $code      = trim((string)($input['code'] ?? $moduleKey));

    if ($moduleKey === '' || $name === '') {
        error_bad_request('module_key and name are required');
    }

    $stmt = $pdo->prepare("
        INSERT INTO modules (
            module_key,
            code,
            name,
            active,
            sort_order,
            created_at
        ) VALUES (
            :module_key,
            :code,
            :name,
            1,
            0,
            NOW()
        )
    ");

    $stmt->execute([
        ':module_key' => $moduleKey,
        ':code'       => $code,
        ':name'       => $name
    ]);

    $moduleId = (int)$pdo->lastInsertId();

    /* ---------- AUDIT ---------- */
    audit_log(
        $pdo,
        $actor,
        'create',
        'module',
        $moduleId,
        [
            'module_key' => $moduleKey,
            'code'       => $code,
            'name'       => $name
        ]
    );

    success('Module created', [
        'module_id' => $moduleId
    ]);
}

/* =========================
   PUT — TOGGLE ACTIVE FLAG
   ========================= */
if ($method === 'PUT') {

    $input = json_decode(file_get_contents('php://input'), true);
    $id = (int)($input['id'] ?? 0);

    if ($id <= 0) {
        error_bad_request('Invalid module id');
    }

    $stmt = $pdo->prepare("
        SELECT active
        FROM modules
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$id]);
    $current = $stmt->fetchColumn();

    if ($current === false) {
        error_not_found('Module not found');
    }

    $newActive = ((int)$current === 1) ? 0 : 1;

    $pdo->prepare("
        UPDATE modules
        SET active = ?
        WHERE id = ?
    ")->execute([$newActive, $id]);

    /* ---------- AUDIT ---------- */
    audit_log(
        $pdo,
        $actor,
        $newActive ? 'enable' : 'disable',
        'module',
        $id,
        [
            'active' => $newActive
        ]
    );

    success('Module updated', [
        'active' => $newActive
    ]);
}

/* =========================
   FALLBACK
   ========================= */
error_bad_request('Method not allowed');
