<?php
declare(strict_types=1);

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

$actor = require_auth($pdo);

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

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

$companyId = (int)($input['company_id'] ?? 0);
$moduleKey = trim((string)($input['module_key'] ?? ''));
$enabled   = (bool)($input['enabled'] ?? true);

if ($companyId <= 0 || $moduleKey === '') {
    error_bad_request('Invalid input');
}

/* Resolve module ID */
$stmt = $pdo->prepare("
    SELECT id
    FROM modules
    WHERE module_key = ?
    LIMIT 1
");
$stmt->execute([$moduleKey]);
$moduleId = $stmt->fetchColumn();

if (!$moduleId) {
    error_not_found('Module not found');
}

/* Upsert override */
if ($enabled) {
    $pdo->prepare("
        INSERT INTO company_modules (company_id, module_id, status, activated_at)
        VALUES (?, ?, 'active', NOW())
        ON DUPLICATE KEY UPDATE
            status = 'active',
            activated_at = NOW(),
            deactivated_at = NULL
    ")->execute([$companyId, $moduleId]);
} else {
    $pdo->prepare("
        INSERT INTO company_modules (company_id, module_id, status, deactivated_at)
        VALUES (?, ?, 'inactive', NOW())
        ON DUPLICATE KEY UPDATE
            status = 'inactive',
            deactivated_at = NOW()
    ")->execute([$companyId, $moduleId]);
}

success('Module updated', [
    'company_id' => $companyId,
    'module_key' => $moduleKey,
    'enabled'    => $enabled
]);
