<?php
require_once __DIR__ . '/../admin_middleware.php';

// Only admins/super_admins can manage users (or checking a specific 'manage_users' permission)
verifyAdmin('manage_users'); 

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

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

if (!isset($data['user_id']) || !isset($data['role'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing user_id or role']);
    exit;
}

$target_id = $data['user_id'];
$new_role = $data['role'];
$permissions = isset($data['permissions']) ? json_encode($data['permissions']) : json_encode([]);
$is_verified = isset($data['is_verified']) ? (int)$data['is_verified'] : 0;

// Prevent modifying Super Admin if not Super Admin
// (Simplified check: ideally checking requesting user's role vs target user's role)

try {
    $stmt = $pdo->prepare("UPDATE i_users SET role = ?, permissions = ?, is_verified = ? WHERE iuid = ?");
    $stmt->execute([$new_role, $permissions, $is_verified, $target_id]);

    echo json_encode(['success' => true, 'message' => 'User privileges updated']);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
