<?php

/**
 * Generates a secure random invite code.
 * Requirements: lowercase, uppercase, digits, special characters.
 * Length: 10 to 12 characters.
 */
function generateInviteCode($length = null) {
    if ($length === null) {
        $length = rand(10, 12);
    }
    
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+';
    $code = '';
    $max = strlen($chars) - 1;
    
    // Ensure at least one of each required type if possible, 
    // but a simple random selection from the full set is usually sufficient 
    // if the set is diverse enough and the length is 10-12.
    // However, to be strictly compliant with "must have...", let's ensure it.
    
    $sets = [
        'abcdefghijklmnopqrstuvwxyz',
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        '0123456789',
        '!@#$%^&*()-_=+'
    ];
    
    // Pick one from each set
    foreach ($sets as $set) {
        $code .= $set[random_int(0, strlen($set) - 1)];
    }
    
    // Fill the rest
    while (strlen($code) < $length) {
        $code .= $chars[random_int(0, $max)];
    }
    
    // Shuffle to avoid predictable pattern
    $codeArray = str_split($code);
    shuffle($codeArray);
    
    return implode('', $codeArray);
}
