<?php
echo "<h2>Comprehensive API Key Verification and Fix</h2>";

// The CORRECT API key from MRAM Developers portal
$correct_api_key = 'C30027916975f051ed0e01.45424521';

echo "<h3>Correct API Key from MRAM Portal:</h3>";
echo "<p><strong>API Key:</strong> $correct_api_key</p>";
echo "<p><strong>Length:</strong> " . strlen($correct_api_key) . "</p>";

// Database connection
$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,
    ]);

    // Get ALL settings that might contain API keys
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE '%api_key%' OR setting_key LIKE '%username%' OR setting_key LIKE '%password%' OR setting_key LIKE '%api_url%' OR setting_key LIKE '%sender%' ORDER BY setting_key");
    $stmt->execute();
    $all_settings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo "<h3>All Current API Settings:</h3>";
    echo "<table border='1' cellpadding='5' cellspacing='0'>";
    echo "<tr><th>Setting Key</th><th>Setting Value</th><th>Status</th></tr>";
    
    $api_keys_found = [];
    $other_settings = [];
    
    foreach ($all_settings as $setting) {
        $key = $setting['setting_key'];
        $value = $setting['setting_value'];
        
        if (strpos($key, 'api_key') !== false) {
            $api_keys_found[] = $setting;
        } else {
            $other_settings[] = $setting;
        }
        
        $status = '';
        if ($key === 'non_musking_api_key' || $key === 'sms_api_key') {
            if ($value === $correct_api_key) {
                $status = '<span style="color:green;">✅ CORRECT</span>';
            } else {
                $status = '<span style="color:red;">❌ INCORRECT</span>';
            }
        }
        
        echo "<tr>";
        echo "<td><strong>$key</strong></td>";
        if (strpos($key, 'password') !== false) {
            echo "<td>******** (hidden)</td>";
        } else {
            echo "<td>$value</td>";
        }
        echo "<td>$status</td>";
        echo "</tr>";
    }
    echo "</table>";

    // Check specifically for the API keys that need to be fixed
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_api_key'");
    $stmt->execute();
    $current_non_musking_key = $stmt->fetchColumn();
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_api_key'");
    $stmt->execute();
    $current_sms_key = $stmt->fetchColumn();
    
    echo "<h3>API Key Analysis:</h3>";
    echo "<p><strong>non_musking_api_key:</strong> ";
    if ($current_non_musking_key === $correct_api_key) {
        echo "<span style='color:green;'>✅ CORRECT</span>";
    } else {
        echo "<span style='color:red;'>❌ INCORRECT - Current: " . substr($current_non_musking_key, 0, 20) . "...</span>";
    }
    echo "</p>";
    
    echo "<p><strong>sms_api_key:</strong> ";
    if ($current_sms_key === $correct_api_key) {
        echo "<span style='color:green;'>✅ CORRECT</span>";
    } else {
        echo "<span style='color:red;'>❌ INCORRECT - Current: " . substr($current_sms_key, 0, 20) . "...</span>";
    }
    echo "</p>";

    // Update both API keys to the correct value
    $update_stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    
    echo "<h3>Updating API Keys:</h3>";
    
    if ($current_non_musking_key !== $correct_api_key) {
        $update_stmt->execute(['non_musking_api_key', $correct_api_key, $correct_api_key]);
        echo "<p>✅ Updated non_musking_api_key</p>";
    } else {
        echo "<p>ℹ️ non_musking_api_key already correct</p>";
    }
    
    if ($current_sms_key !== $correct_api_key) {
        $update_stmt->execute(['sms_api_key', $correct_api_key, $correct_api_key]);
        echo "<p>✅ Updated sms_api_key</p>";
    } else {
        echo "<p>ℹ️ sms_api_key already correct</p>";
    }
    
    // Also update other MRAM settings to ensure consistency
    $mram_settings = [
        'non_musking_username' => 'C3002791',
        'non_musking_password' => 'hPOWSnw8rf',
        'non_musking_sender_id' => '8809601016579',
        'non_musking_api_url' => 'https://sms.mram.com.bd/smsapi',
        'sms_username' => 'C3002791',
        'sms_password' => 'hPOWSnw8rf',
        'sms_sender_id' => '8809601016579',
        'sms_api_url' => 'https://sms.mram.com.bd/smsapi',
        'non_musking_enabled' => '1',
        'sms_enabled' => '1'
    ];
    
    echo "<h3>Updating Other MRAM Settings:</h3>";
    foreach ($mram_settings as $key => $value) {
        $update_stmt->execute([$key, $value, $value]);
        echo "<p>✅ Updated $key</p>";
    }
    
    // Final verification
    echo "<h3>Final Verification:</h3>";
    $verify_stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('non_musking_api_key', 'sms_api_key', 'non_musking_api_url', 'sms_api_url')");
    $verify_stmt->execute();
    $final_results = $verify_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($final_results as $result) {
        $key = $result['setting_key'];
        $value = $result['setting_value'];
        $correct = false;
        
        if ($key === 'non_musking_api_key' || $key === 'sms_api_key') {
            $correct = ($value === $correct_api_key);
        } elseif ($key === 'non_musking_api_url' || $key === 'sms_api_url') {
            $correct = ($value === 'https://sms.mram.com.bd/smsapi');
        }
        
        $status = $correct ? '✅ CORRECT' : '❌ STILL WRONG';
        echo "<p><strong>$key:</strong> $status</p>";
    }
    
    echo "<h3 style='color:green;'>✅ Process Complete - All settings updated with correct MRAM values!</h3>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Database error: " . $e->getMessage() . "</p>";
}

echo "<h3>Next Steps:</h3>";
echo "<ul>";
echo "<li>Clear any cached settings in your application</li>";
echo "<li>Restart your web server if necessary</li>";
echo "<li>Test SMS sending again</li>";
echo "<li>Visit <a href='simple_test_sms.php'>Simple Test SMS</a> to verify</li>";
echo "</ul>";
?>