<?php
// DEBUG v2 - tests all HTTP methods
// Upload to ajax/smsman_debug.php, visit in browser while logged in, then DELETE

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: text/plain; charset=utf-8');

$config_path = dirname(__DIR__) . '/include/config.php';
if (!file_exists($config_path)) $config_path = dirname(__DIR__) . '/include/config.php';
if (file_exists($config_path)) include($config_path);

$token    = $site_data['smsman_api_token'] ?? '';
$base_url = rtrim($site_data['smsman_api_url'] ?? 'https://api.sms-man.com/control', '/');
$url      = $base_url . '/get-balance?token=' . urlencode($token);

echo "Token set: " . (!empty($token) ? 'YES (len=' . strlen($token) . ')' : 'NO') . "\n";
echo "URL: $url\n\n";

// Method 1: cURL
echo "=== METHOD 1: cURL ===\n";
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 15, CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_FOLLOWLOCATION => true, CURLOPT_USERAGENT => 'Mozilla/5.0',
]);
$raw = curl_exec($ch);
$err = curl_error($ch);
$t   = round(curl_getinfo($ch, CURLINFO_TOTAL_TIME), 2);
curl_close($ch);
echo "Time: {$t}s | Error: " . ($err ?: 'none') . " | Response: " . ($raw ?: '(empty)') . "\n\n";

// Method 2: file_get_contents
echo "=== METHOD 2: file_get_contents ===\n";
echo "allow_url_fopen: " . (ini_get('allow_url_fopen') ? 'ON' : 'OFF') . "\n";
$ctx = stream_context_create([
    'http' => ['method'=>'GET','header'=>"User-Agent: Mozilla/5.0\r\n",'timeout'=>15,'ignore_errors'=>true],
    'ssl'  => ['verify_peer'=>false,'verify_peer_name'=>false],
]);
$t0   = microtime(true);
$raw2 = @file_get_contents($url, false, $ctx);
$t2   = round(microtime(true) - $t0, 2);
echo "Time: {$t2}s | Response: " . ($raw2 !== false ? $raw2 : '(failed/empty)') . "\n\n";

// Method 3: fsockopen
echo "=== METHOD 3: fsockopen ===\n";
$t0 = microtime(true);
$fp = @fsockopen('ssl://api.sms-man.com', 443, $errno, $errstr, 10);
$t3 = round(microtime(true) - $t0, 2);
if ($fp) {
    $path = '/control/get-balance?token=' . urlencode($token);
    fwrite($fp, "GET {$path} HTTP/1.1\r\nHost: api.sms-man.com\r\nUser-Agent: Mozilla/5.0\r\nConnection: close\r\n\r\n");
    $resp = '';
    while (!feof($fp)) $resp .= fgets($fp, 4096);
    fclose($fp);
    $body = preg_replace('/^.*?\r\n\r\n/s', '', $resp);
    echo "Time: {$t3}s | Response: " . trim($body) . "\n\n";
} else {
    echo "Time: {$t3}s | Failed: [$errno] $errstr\n\n";
}

echo "=== DONE - DELETE THIS FILE ===\n";