<?php
declare(strict_types=1);

/**
 * Central module entitlement authority
 */

function getCompanyModules(PDO $pdo, int $companyId): array
{
    // Default allow for known modules
    $modules = [
        'USERS' => true,
        'AUDIT' => true
    ];

    // Apply admin overrides
    $stmt = $pdo->prepare("
        SELECT m.module_key, cm.status
        FROM company_modules cm
        JOIN modules m ON m.id = cm.module_id
        WHERE cm.company_id = ?
    ");
    $stmt->execute([$companyId]);

    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        if ($row['status'] === 'inactive') {
            $modules[$row['module_key']] = false;
        }
        if ($row['status'] === 'active') {
            $modules[$row['module_key']] = true;
        }
    }

    return $modules;
}

function isModuleEnabled(PDO $pdo, int $companyId, string $moduleKey): bool
{
    $modules = getCompanyModules($pdo, $companyId);
    return $modules[$moduleKey] ?? true; // opt-out
}
