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

echo "<h2>MRAM API Authentication Method Verification</h2>";

// Get current settings
$stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'non_musking_%'");
$stmt->execute();
$currentSettings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

echo "<h3>Current Settings:</h3>";
foreach ($currentSettings as $key => $value) {
    if (strpos($key, '_key') !== false || strpos($key, '_username') !== false || strpos($key, '_password') !== false || strpos($key, '_url') !== false) {
        echo "$key: " . htmlspecialchars($value) . "<br>";
    }
}

// Based on MRAM API documentation patterns
echo "<br><h3>MRAM API Authentication Analysis:</h3>";
echo "<p>The 401 error suggests that the API Key format may be incorrect.</p>";

echo "<p>Possible issues:</p>";
echo "<ol>";
echo "<li>The API Key 'C30027916974e980709412.23354057' might be incorrect</li>";
echo "<li>Your MRAM account might require using username/password instead of API Key</li>";
echo "<li>The account C3002791 might not have API access enabled</li>";
echo "<li>The API Key might need to be generated separately in your MRAM dashboard</li>";
echo "</ol>";

echo "<br><h3>Suggested Solutions:</h3>";
echo "<ol>";
echo "<li>Login to your MRAM account at https://sms.mram.com.bd</li>";
echo "<li>Check if there's an 'API' or 'Developer' section to generate/get your correct API Key</li>";
echo "<li>If API Key is not available, try using only username/password authentication</li>";
echo "<li>Verify that your account has API access permissions</li>";
echo "</ol>";

echo "<br><h3>Attempting to update authentication to use username/password only:</h3>";

try {
    // Clear the API key and rely on username/password
    $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    
    // Keep username and password, but clear API key
    $stmt->execute(['non_musking_api_key', '', '']);
    $stmt->execute(['sms_api_key', '', '']);
    
    echo "✅ API Key fields cleared<br>";
    echo "✅ Authentication will now use username/password only<br>";
    echo "✅ Please try the test again after this change<br>";
    
} catch (Exception $e) {
    echo "❌ Error updating settings: " . $e->getMessage() . "<br>";
}

echo "<br><h3>Next Steps:</h3>";
echo "<ol>";
echo "<li>Visit Admin Panel → SMS Settings</li>";
echo "<li>Re-enter your credentials if needed</li>";
echo "<li>Test the configuration again</li>";
echo "<li>Alternatively, contact MRAM support to verify your API access</li>";
echo "</ol>";

?>