<?php
/**
 * validate_wallet_address.php
 * 
 * Endpoint to validate cryptocurrency wallet addresses
 * This improves the withdrawal UX by providing real-time validation
 */

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require user authentication
requireLogin(true);

require_once 'config.php';
require_once 'db.php';

// Get the address and cryptocurrency type from the request
$data = json_decode(file_get_contents('php://input'), true);
$wallet_address = $data['wallet_address'] ?? '';
$crypto_type = $data['crypto_type'] ?? '';
$payment_method_id = isset($data['payment_method_id']) ? (int)$data['payment_method_id'] : 0;

if (empty($wallet_address)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Wallet address is required'
    ]);
    exit;
}

try {
    // If payment method ID is provided, get the crypto type from the database
    if ($payment_method_id > 0) {
        $stmt = $pdo->prepare("SELECT * FROM payment_methods WHERE id = ? AND type = 'crypto'");
        $stmt->execute([$payment_method_id]);
        $payment_method = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($payment_method) {
            $crypto_type = $payment_method['name'];
        }
    }

    // Validate the wallet address format
    $validation_result = validateWalletAddress($wallet_address, $crypto_type);
    
    // Return the validation result
    echo json_encode([
        'success' => true,
        'is_valid' => $validation_result['is_valid'],
        'message' => $validation_result['message'],
        'address' => $wallet_address,
        'crypto_type' => $crypto_type
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    error_log('Error validating wallet address: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while validating the wallet address'
    ]);
}

/**
 * Validate a cryptocurrency wallet address
 * 
 * @param string $address The wallet address to validate
 * @param string $crypto_type The cryptocurrency type (e.g. 'bitcoin', 'ethereum')
 * @return array Validation result with 'is_valid' and 'message' keys
 */
function validateWalletAddress($address, $crypto_type) {
    $crypto_type = strtolower($crypto_type);
    $result = ['is_valid' => false, 'message' => 'Invalid address format'];
    
    // Remove whitespace
    $address = trim($address);
    
    // Check for empty address
    if (empty($address)) {
        $result['message'] = 'Address cannot be empty';
        return $result;
    }
    
    switch ($crypto_type) {
        case 'bitcoin':
        case 'btc':
            // Bitcoin address validation (basic format check)
            // Legacy: 1... (26-34 chars)
            // Segwit: 3... (26-34 chars)
            // Bech32: bc1... (42 chars)
            if (preg_match('/^(1|3)[a-zA-Z0-9]{25,33}$/', $address) || preg_match('/^(bc1)[a-zA-Z0-9]{39,59}$/', $address)) {
                $result['is_valid'] = true;
                $result['message'] = 'Valid Bitcoin address';
            }
            break;
            
        case 'ethereum':
        case 'eth':
            // Ethereum address validation (0x followed by 40 hex chars)
            if (preg_match('/^0x[a-fA-F0-9]{40}$/', $address)) {
                $result['is_valid'] = true;
                $result['message'] = 'Valid Ethereum address';
            }
            break;
            
        case 'ton':
            // TON address validation (basic format check - starts with EQ, UQ or similar)
            if (preg_match('/^(EQ|UQ)[a-zA-Z0-9_-]{43,48}$/', $address)) {
                $result['is_valid'] = true;
                $result['message'] = 'Valid TON address';
            }
            break;
            
        case 'sui':
            // SUI address validation (0x followed by 30-64 hex chars)
            if (preg_match('/^0x[a-fA-F0-9]{30,64}$/', $address)) {
                $result['is_valid'] = true;
                $result['message'] = 'Valid SUI address';
            }
            break;
            
        case 'tether':
        case 'usdt':
            // USDT can be on multiple chains, so we check for Ethereum, Tron, etc.
            if (preg_match('/^0x[a-fA-F0-9]{40}$/', $address) || // Ethereum
                preg_match('/^T[a-zA-Z0-9]{33}$/', $address)) {   // Tron
                $result['is_valid'] = true;
                $result['message'] = 'Valid USDT address';
            }
            break;
            
        default:
            // Generic cryptocurrency address validation
            // At least check it's not completely invalid
            if (strlen($address) >= 26 && !preg_match('/[^a-zA-Z0-9_\-.]/', $address)) {
                $result['is_valid'] = true;
                $result['message'] = 'Address format appears valid';
            } else {
                $result['message'] = 'Unknown cryptocurrency or invalid format';
            }
    }
    
    return $result;
}
