<?php
require_once '../../includes/config.php';
require_once '../../includes/dingconnect.php';
requireAdmin();

if (!dingIsConfigured()) {
    jsonResponse(false, '❌ API Key সেট নেই! আগে সেটিংস সেভ করুন।');
}

// Get server IP for whitelist info
$server_ip = $_SERVER['SERVER_ADDR'] ?? gethostbyname(gethostname());

$result = dingGetBalance();

if (isset($result['ResultCode']) && $result['ResultCode'] == 1) {
    $bal = $result['Balance'] ?? ($result['balance'] ?? 'N/A');
    jsonResponse(true, "✅ DingConnect সংযোগ সফল! Balance: " . json_encode($bal));
} elseif (isset($result['ResultCode']) && $result['ResultCode'] == 4) {
    $errCode = $result['ErrorCodes'][0]['Code'] ?? 'Unknown';
    $context = $result['ErrorCodes'][0]['Context'] ?? '';
    
    if ($errCode === 'AuthenticationFailed') {
        $msg = "❌ Authentication Failed!\n\n";
        $msg .= "⚠️ সম্ভাব্য কারণ:\n";
        $msg .= "1. API Key ভুল\n";
        $msg .= "2. Server IP Whitelist এ নেই\n\n";
        $msg .= "🔧 সমাধান:\n";
        $msg .= "DingConnect → Developer → IP Whitelisting → এই IP যোগ করুন: {$server_ip}";
        jsonResponse(false, $msg);
    }
    jsonResponse(false, "❌ Error: {$errCode} - {$context}");
} elseif (isset($result['error'])) {
    jsonResponse(false, '❌ ' . $result['error']);
} else {
    // Show full response for debugging
    jsonResponse(false, '❌ অজানা response: ' . json_encode($result));
}
