<?php
// Direct database check for MRAM credentials
$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>MRAM Credentials Database Check</h2>";
    
    // Get all SMS related settings
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE '%non_musking%' OR setting_key LIKE '%sms%' ORDER BY setting_key");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<h3>Current Database Values:</h3>";
    echo "<table border='1' cellpadding='5'>";
    echo "<tr><th>Setting Key</th><th>Setting Value</th><th>Status</th></tr>";
    
    $critical_values = [
        'non_musking_enabled' => '1',
        'non_musking_api_url' => 'https://rest.mrmessaging.net/messages',
        'non_musking_api_key' => 'C30027916974e980709412.23354057',
        'non_musking_username' => 'C3002791',
        'non_musking_password' => 'hPOWSnw8rf',
        'non_musking_sender_id' => '8809601016579'
    ];
    
    foreach ($settings as $setting) {
        $key = $setting['setting_key'];
        $value = $setting['setting_value'];
        
        // Mask sensitive values for display
        $display_value = '';
        if (strpos($key, 'password') !== false || strpos($key, 'api_key') !== false) {
            $display_value = substr($value, 0, 10) . str_repeat('*', max(0, strlen($value) - 10)) . ' (length: ' . strlen($value) . ')';
        } else {
            $display_value = htmlspecialchars($value);
        }
        
        $status = '';
        if (isset($critical_values[$key])) {
            if ($value === $critical_values[$key]) {
                $status = '<span style="color: green;">✓ CORRECT</span>';
            } else {
                $status = '<span style="color: red;">✗ INCORRECT</span> (Expected: ' . substr($critical_values[$key], 0, 15) . '...)';
            }
        } else {
            $status = 'OK';
        }
        
        echo "<tr><td>$key</td><td>$display_value</td><td>$status</td></tr>";
    }
    echo "</table>";
    
    // Check specific critical values
    echo "<h3>Critical Values Check:</h3>";
    foreach ($critical_values as $key => $expected) {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        
        $actual = $result ? $result['setting_value'] : 'NOT FOUND';
        $match = $actual === $expected;
        
        echo "<p><strong>$key:</strong> ";
        if ($match) {
            echo "<span style='color: green;'>✓ MATCHES</span>";
        } else {
            echo "<span style='color: red;'>✗ DOES NOT MATCH</span>";
            echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;Expected: '$expected'";
            echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;Actual: '$actual'";
            echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;Length - Expected: " . strlen($expected) . ", Actual: " . strlen($actual);
            
            // Check for whitespace issues
            if (trim($actual) === $expected) {
                echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;<strong>⚠️ ISSUE: Extra whitespace detected!</strong>";
            }
        }
        echo "</p>";
    }
    
    // If there are mismatches, provide update SQL
    echo "<h3>Fix SQL Commands:</h3>";
    echo "<pre>";
    foreach ($critical_values as $key => $expected) {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        
        $actual = $result ? $result['setting_value'] : 'NOT FOUND';
        if ($actual !== $expected) {
            echo "UPDATE settings SET setting_value = '" . addslashes($expected) . "' WHERE setting_key = '$key';\n";
        }
    }
    echo "</pre>";
    
    // Force update with correct values
    echo "<h3>Force Update to Correct Values:</h3>";
    $update_count = 0;
    foreach ($critical_values as $key => $expected) {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        
        $actual = $result ? $result['setting_value'] : 'NOT FOUND';
        if ($actual !== $expected) {
            $update_stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $update_stmt->execute([$key, $expected, $expected]);
            echo "<p>Updated $key: <span style='color: orange;'>CHANGED</span></p>";
            $update_count++;
        } else {
            echo "<p>$key: <span style='color: green;'>ALREADY CORRECT</span></p>";
        }
    }
    
    if ($update_count > 0) {
        echo "<p><strong>🔄 $update_count settings were updated. Please try sending SMS again.</strong></p>";
    } else {
        echo "<p><strong>✅ All critical settings are already correct.</strong></p>";
    }

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

echo "<h3>Next Steps:</h3>";
echo "<ol>";
echo "<li>Run the force update above (if needed)</li>";
echo "<li>Try sending test SMS again</li>";
echo "<li>If still failing, contact MRAM support to verify your account status</li>";
echo "</ol>";
?>