<?php

// Prevent direct script access
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

// --- General Utility Functions ---

/**
 * Builds a URL-encoded query string suitable for callback data.
 */
function buildCallbackData(string $action, array $params = []): string {
    // Ensure action is always present
    $data = array_merge(['action' => $action], $params); 
    // Use http_build_query for standard, reliable encoding
    return http_build_query($data); 
}

/**
 * Parses a URL-encoded callback data string into an associative array.
 */
function parseCallbackData(string $data): array {
    $output = []; 
    parse_str($data, $output); // parse_str handles URL decoding
    return $output; 
}

/**
 * Normalizes various phone number formats to the standard Iranian 09xxxxxxxxx format.
 */
function normalizePhoneNumber(string $phone): string {
    // 1. Convert Persian/Arabic digits to English
    $phone = convertPersianToEnglishDigits($phone); // Assumes FormattingHelpers is loaded
    
    // 2. Remove any non-digit characters except an optional '+' at the very beginning
    $phone = preg_replace('/[^\d+]/', '', $phone); 
    if (strpos($phone, '+') > 0) { // Remove '+' if it's not at the start
        $phone = str_replace('+', '', $phone);
    }
    
    // 3. Handle international prefixes +98 or 98
    if (strpos($phone, '+98') === 0) {
        $phone = substr($phone, 3); // Remove +98
    } elseif (strpos($phone, '98') === 0) {
        $phone = substr($phone, 2); // Remove 98
    }
    
    // 4. Remove leading '0' if present (common input format like 0912...)
    if (strpos($phone, '0') === 0) {
        $phone = substr($phone, 1); 
    }

    // 5. Check if the remaining part is a 10-digit number starting with 9
    if (strlen($phone) === 10 && strpos($phone, '9') === 0) {
         return '0' . $phone; // Prepend '0' to get the standard 09xxxxxxxxx format
    }

    // If it doesn't match the expected format after cleaning, log a warning
    $original_phone_for_log = $phone; // Keep original for logging context
    if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Warning: Phone number '{$original_phone_for_log}' could not be reliably normalized to 09xxxxxxxxx format after cleaning.\n", FILE_APPEND); }
    
    // Return the best guess (prepending '0' to the remaining digits)
    return '0' . preg_replace('/\D/', '', $phone); 
}

/**
 * Generates a random alphanumeric code (uppercase letters and digits).
 */
function generateRandomCode(int $length = 10): string {
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
    $charactersLength = strlen($characters); 
    $randomString = ''; 
    for ($i = 0; $i < $length; $i++) {
        try {
            // Use cryptographically secure random number generator if available
            $randomString .= $characters[random_int(0, $charactersLength - 1)]; 
        } catch (Exception $e) {
            // Fallback for environments where random_int is not available (less secure)
            $randomString .= $characters[mt_rand(0, $charactersLength - 1)]; 
        }
    }
    return $randomString; 
}

/**
 * Masks a card number according to common standards (e.g., 603799******1111).
 */
function maskCardNumber(string $cardNumber): string {
    $cardNumber = preg_replace('/\D/', '', $cardNumber); // Remove non-digits
    $len = strlen($cardNumber); 
    if ($len === 16) {
        // Standard 16-digit mask: first 6, 6 stars, last 4
        return substr($cardNumber, 0, 6) . '******' . substr($cardNumber, -4); 
    } elseif ($len >= 10) { // Heuristic for potentially shorter valid numbers
        // Mask middle digits, keeping first 6 and last 4
        return substr($cardNumber, 0, 6) . str_repeat('*', $len - 10) . substr($cardNumber, -4); 
    } elseif ($len > 4) { 
        // Mask all but the last 4 for very short numbers
        return str_repeat('*', $len - 4) . substr($cardNumber, -4); 
    }
    // If 4 digits or less, mask everything (unlikely for valid cards)
    return str_repeat('*', $len); 
}

?>
