<?php
declare(strict_types=1);

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

$user = require_auth($pdo);

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $userId = (int)($_GET['user_id'] ?? 0);
    if ($userId <= 0) error_bad_request('Invalid user_id');

    $stmt = $pdo->prepare("
        SELECT module_key, permission_key, granted
        FROM user_module_permissions
        WHERE user_id = ?
    ");
    $stmt->execute([$userId]);

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

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!is_array($input)) error_bad_request('Invalid JSON');

    $userId = (int)($input['user_id'] ?? 0);
    $perms = $input['permissions'] ?? [];

    if ($userId <= 0 || !is_array($perms)) {
        error_bad_request('Invalid input');
    }

    foreach ($perms as $p) {
        $module = strtoupper(trim((string)($p['module'] ?? '')));
        $perm   = trim((string)($p['permission'] ?? ''));
        $grant  = !empty($p['granted']) ? 1 : 0;

        if ($module === '' || $perm === '') continue;

        $pdo->prepare("
            INSERT INTO user_module_permissions
                (user_id, module_key, permission_key, granted, granted_by)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                granted = VALUES(granted),
                granted_by = VALUES(granted_by),
                granted_at = NOW()
        ")->execute([$userId, $module, $perm, $grant, $user['id']]);

        audit_log(
            $pdo,
            $user,
            'update',
            'user_module_permission',
            $userId,
            [
                'module' => $module,
                'permission' => $perm,
                'granted' => $grant
            ]
        );
    }

    success('Permissions updated');
}

error_bad_request('Method not allowed');
