<?php
// Direct database connection to fix API key issue
$host = 'localhost';
$dbname = 'school_management';
$username = 'root';
$password = 'root';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    echo "<h2>Fixing API Key Mismatch</h2>";
    
    // Get current API key from database
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_api_key'");
    $stmt->execute();
    $result = $stmt->fetch();
    
    $current_api_key = $result ? $result['setting_value'] : '';
    $expected_api_key = 'C30027916974e980709412.23354057';
    
    echo "<h3>Current vs Expected:</h3>";
    echo "<p><strong>Current DB Value:</strong> '$current_api_key'</p>";
    echo "<p><strong>Expected Value:</strong> '$expected_api_key'</p>";
    echo "<p><strong>Current Length:</strong> " . strlen($current_api_key) . "</p>";
    echo "<p><strong>Expected Length:</strong> " . strlen($expected_api_key) . "</p>";
    
    // Check for differences
    if ($current_api_key !== $expected_api_key) {
        // Check if it's a whitespace issue
        if (trim($current_api_key) === $expected_api_key) {
            echo "<p style='color:orange;'>⚠️ Issue: Extra whitespace detected in API key!</p>";
            $clean_api_key = trim($current_api_key);
        } else {
            echo "<p style='color:red;'>❌ API key is completely different!</p>";
            $clean_api_key = $expected_api_key;
        }
        
        // Update the database
        $update_stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $update_stmt->execute(['non_musking_api_key', $clean_api_key, $clean_api_key]);
        $update_stmt->execute(['sms_api_key', $clean_api_key, $clean_api_key]);
        
        echo "<p style='color:green; font-size:18px; font-weight:bold;'>✅ API Key fixed in database!</p>";
        
        // Verify the update
        $verify_stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_api_key'");
        $verify_stmt->execute();
        $verify_result = $verify_stmt->fetch();
        $updated_api_key = $verify_result['setting_value'];
        
        echo "<h3>Verification:</h3>";
        echo "<p><strong>Updated DB Value:</strong> '$updated_api_key'</p>";
        echo "<p><strong>New Length:</strong> " . strlen($updated_api_key) . "</p>";
        echo "<p><strong>Match Expected:</strong> " . ($updated_api_key === $expected_api_key ? '✅ YES' : '❌ NO') . "</p>";
    } else {
        echo "<p style='color:green; font-size:18px; font-weight:bold;'>✅ API Key is already correct!</p>";
    }
    
    // Also update other related settings to ensure consistency
    $mram_config = [
        'non_musking_username' => 'C3002791',
        'non_musking_password' => 'hPOWSnw8rf',
        'non_musking_sender_id' => '8809601016579',
        'non_musking_api_url' => 'https://rest.mrmessaging.net/messages',
        'sms_username' => 'C3002791',
        'sms_password' => 'hPOWSnw8rf',
        'sms_sender_id' => '8809601016579',
        'sms_api_url' => 'https://rest.mrmessaging.net/messages'
    ];
    
    echo "<h3>Updating Related Settings:</h3>";
    foreach ($mram_config as $key => $value) {
        $update_stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $update_stmt->execute([$key, $value, $value]);
        echo "<p>Updated $key: <span style='color:green;'>SUCCESS</span></p>";
    }
    
    echo "<h3>Process Complete!</h3>";
    echo "<p>✅ API Key and all related settings have been updated with correct MRAM values.</p>";
    echo "<p>🚀 Try sending an SMS now - the 401 authentication error should be resolved!</p>";

} catch (Exception $e) {
    echo "<p style='color: red;'>Database error: " . $e->getMessage() . "</p>";
}

echo "<h3>Next Steps:</h3>";
echo "<ul>";
echo "<li>Go to Admin Panel → SMS Settings</li>";
echo "<li>Try sending a test SMS</li>";
echo "<li>Visit <a href='simple_test_sms.php'>Simple Test SMS</a> to verify</li>";
echo "</ul>";
?>