<?php
require_once 'config/database.php';
require_once 'includes/sms_helper.php';

echo "<h2>MRAM API Authentication Debug</h2>";

// Get current configuration
$config = non_musking_config();

echo "<h3>Current Configuration:</h3>";
echo "<ul>";
echo "<li>Enabled: " . ($config['enabled'] ? 'Yes' : 'No') . "</li>";
echo "<li>API URL: " . htmlspecialchars($config['api_url'] ?? 'Not set') . "</li>";
echo "<li>Username: " . htmlspecialchars($config['username'] ?? 'Not set') . "</li>";
echo "<li>API Key: " . (!empty($config['api_key']) ? substr(htmlspecialchars($config['api_key']), 0, 10) . '...' : 'Not set') . "</li>";
echo "<li>Sender ID: " . htmlspecialchars($config['sender_id'] ?? 'Not set') . "</li>";
echo "</ul>";

// Manually test the API call with debugging
echo "<h3>Manual API Call Debug:</h3>";

if (!empty($config['api_url'])) {
    $apiUrl = $config['api_url'];
    
    // Payload for test
    $payload = [
        'mobile_number' => '+8801717861762',
        'sms' => 'Test message from debug',
        'sender_id' => $config['sender_id'] ?? 'TEST'
    ];
    
    echo "<p>Payload: " . json_encode($payload, JSON_UNESCAPED_UNICODE) . "</p>";
    
    // Create cURL request manually to test
    $ch = curl_init($apiUrl);
    
    // Determine authentication method
    $authHeader = '';
    if (!empty($config['api_key'])) {
        $authHeader = 'Authorization: App ' . $config['api_key'];
        echo "<p>Using API Key auth: Authorization: App " . substr($config['api_key'], 0, 15) . "...</p>";
    } else {
        // Fallback to Basic Auth
        $username = $config['username'] ?? '';
        $password = $config['password'] ?? '';
        $authHeader = 'Authorization: Basic ' . base64_encode($username . ':' . $password);
        echo "<p>Using Basic auth: Authorization: Basic " . substr(base64_encode($username . ':' . $password), 0, 15) . "...</p>";
    }
    
    echo "<p>Full Auth Header: " . htmlspecialchars($authHeader) . "</p>";
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Accept: application/json',
        $authHeader
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    // Enable verbose output to see the actual request
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    $verbose = fopen('php://temp', 'w+');
    curl_setopt($ch, CURLOPT_STDERR, $verbose);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    
    // Get verbose output
    rewind($verbose);
    $verboseLog = stream_get_contents($verbose);
    fclose($verbose);
    
    curl_close($ch);
    
    echo "<p>HTTP Code: $httpCode</p>";
    if ($curlError) {
        echo "<p style='color:red;'>cURL Error: " . htmlspecialchars($curlError) . "</p>";
    }
    echo "<p>Response: " . htmlspecialchars($response) . "</p>";
    echo "<p>Verbose Log: " . htmlspecialchars($verboseLog) . "</p>";
    
    if ($httpCode == 401) {
        echo "<h3>401 Error Analysis:</h3>";
        echo "<p>The API is rejecting your credentials. Possible causes:</p>";
        echo "<ol>";
        echo "<li>API Key might have extra spaces or characters</li>";
        echo "<li>API Key might be expired or revoked</li>";
        echo "<li>Account might not have API access enabled</li>";
        echo "<li>Account might have insufficient balance</li>";
        echo "<li>MRAM server might be experiencing issues</li>";
        echo "</ol>";
        
        // Test with trimmed API key
        echo "<h4>Testing with trimmed credentials:</h4>";
        $trimmedApiKey = trim($config['api_key'] ?? '');
        $trimmedUsername = trim($config['username'] ?? '');
        $trimmedPassword = trim($config['password'] ?? '');
        
        echo "<p>Original API Key length: " . strlen($config['api_key'] ?? '') . "</p>";
        echo "<p>Trimmed API Key length: " . strlen($trimmedApiKey) . "</p>";
        echo "<p>Original API Key: '" . htmlspecialchars($config['api_key']) . "'</p>";
        echo "<p>Trimmed API Key: '" . htmlspecialchars($trimmedApiKey) . "'</p>";
        
        if ($trimmedApiKey !== ($config['api_key'] ?? '')) {
            echo "<p style='color:orange;'>⚠️ API Key has extra spaces/characters that need trimming!</p>";
            
            // Update the database with trimmed values
            try {
                $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'non_musking_api_key'");
                $stmt->execute([trim($config['api_key'])]);
                
                $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'non_musking_username'");
                $stmt->execute([trim($config['username'])]);
                
                $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'non_musking_password'");
                $stmt->execute([trim($config['password'])]);
                
                echo "<p style='color:green;'>✅ Credentials have been trimmed and updated in database</p>";
                echo "<p>Please try sending the SMS again.</p>";
            } catch (Exception $e) {
                echo "<p style='color:red;'>❌ Could not update database: " . $e->getMessage() . "</p>";
            }
        }
    }
} else {
    echo "<p style='color:red;'>No API URL configured</p>";
}

?>