<?php
// Simple MRAM sync script without complex includes
$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 Developers Portal Sync</h2>";
    echo "<p><strong>Reference URL:</strong> <a href='https://sms.mram.com.bd/Developers' target='_blank'>https://sms.mram.com.bd/Developers</a></p>";

    // MRAM Developers Portal Configuration
    $mram_config = [
        'username' => 'C3002791',
        'password' => 'hPOWSnw8rf',
        'api_key' => 'C30027916974e980709412.23354057',
        'sender_id' => '8809601016579',
        'api_url' => 'https://rest.mrmessaging.net/messages',
    ];

    echo "<h3>MRAM Developers Portal Credentials:</h3>";
    echo "<ul>";
    echo "<li><strong>Username:</strong> {$mram_config['username']}</li>";
    echo "<li><strong>API Key:</strong> {$mram_config['api_key']}</li>";
    echo "<li><strong>Sender ID:</strong> {$mram_config['sender_id']}</li>";
    echo "<li><strong>API URL:</strong> {$mram_config['api_url']}</li>";
    echo "</ul>";

    // Get current settings from database
    $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();
    $db_settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Convert to associative array
    $current_config = [];
    foreach ($db_settings as $setting) {
        $current_config[$setting['setting_key']] = $setting['setting_value'];
    }

    echo "<h3>Current Database Values:</h3>";
    echo "<ul>";
    echo "<li><strong>Enabled:</strong> " . ($current_config['non_musking_enabled'] ?? '0') . "</li>";
    echo "<li><strong>API URL:</strong> " . ($current_config['non_musking_api_url'] ?? 'Not set') . "</li>";
    echo "<li><strong>Username:</strong> " . ($current_config['non_musking_username'] ?? 'Not set') . "</li>";
    echo "<li><strong>API Key:</strong> " . (!empty($current_config['non_musking_api_key']) ? substr($current_config['non_musking_api_key'], 0, 10) . '...' : 'Not set') . "</li>";
    echo "<li><strong>Sender ID:</strong> " . ($current_config['non_musking_sender_id'] ?? 'Not set') . "</li>";
    echo "</ul>";

    // Check for mismatches
    echo "<h3>Comparison Result:</h3>";
    $needs_update = false;
    
    if (($current_config['non_musking_username'] ?? '') !== $mram_config['username']) {
        echo "<p style='color:red;'>❌ Username mismatch: DB='" . ($current_config['non_musking_username'] ?? 'NOT SET') . "', MRAM='{$mram_config['username']}'</p>";
        $needs_update = true;
    } else {
        echo "<p style='color:green;'>✅ Username matched</p>";
    }

    if (($current_config['non_musking_api_key'] ?? '') !== $mram_config['api_key']) {
        echo "<p style='color:red;'>❌ API Key mismatch: DB='" . (!empty($current_config['non_musking_api_key']) ? substr($current_config['non_musking_api_key'], 0, 10) . '...' : 'NOT SET') . "', MRAM='" . substr($mram_config['api_key'], 0, 10) . "...'</p>";
        $needs_update = true;
    } else {
        echo "<p style='color:green;'>✅ API Key matched</p>";
    }

    if (($current_config['non_musking_sender_id'] ?? '') !== $mram_config['sender_id']) {
        echo "<p style='color:red;'>❌ Sender ID mismatch: DB='" . ($current_config['non_musking_sender_id'] ?? 'NOT SET') . "', MRAM='{$mram_config['sender_id']}'</p>";
        $needs_update = true;
    } else {
        echo "<p style='color:green;'>✅ Sender ID matched</p>";
    }

    if (($current_config['non_musking_api_url'] ?? '') !== $mram_config['api_url']) {
        echo "<p style='color:red;'>❌ API URL mismatch: DB='" . ($current_config['non_musking_api_url'] ?? 'NOT SET') . "', MRAM='{$mram_config['api_url']}'</p>";
        $needs_update = true;
    } else {
        echo "<p style='color:green;'>✅ API URL matched</p>";
    }

    if (($current_config['non_musking_password'] ?? '') !== $mram_config['password']) {
        echo "<p style='color:orange;'>ℹ️ Password not checked (hidden for security)</p>";
    }

    // Update database with MRAM credentials if mismatches exist
    if ($needs_update) {
        echo "<h3>Synchronization Process:</h3>";
        echo "<p>Updating database with MRAM portal values...</p>";
        
        try {
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            
            // Update non-masking settings with MRAM values
            $stmt->execute(['non_musking_enabled', '1', '1']);
            $stmt->execute(['non_musking_api_url', $mram_config['api_url'], $mram_config['api_url']]);
            $stmt->execute(['non_musking_api_key', $mram_config['api_key'], $mram_config['api_key']]);
            $stmt->execute(['non_musking_username', $mram_config['username'], $mram_config['username']]);
            $stmt->execute(['non_musking_password', $mram_config['password'], $mram_config['password']]);
            $stmt->execute(['non_musking_sender_id', $mram_config['sender_id'], $mram_config['sender_id']]);
            
            // Also update general SMS settings
            $stmt->execute(['sms_enabled', '1', '1']);
            $stmt->execute(['sms_api_url', $mram_config['api_url'], $mram_config['api_url']]);
            $stmt->execute(['sms_api_key', $mram_config['api_key'], $mram_config['api_key']]);
            $stmt->execute(['sms_username', $mram_config['username'], $mram_config['username']]);
            $stmt->execute(['sms_password', $mram_config['password'], $mram_config['password']]);
            $stmt->execute(['sms_sender_id', $mram_config['sender_id'], $mram_config['sender_id']]);
            
            echo "<p style='color:green; font-size:18px; font-weight:bold;'>✅ All settings synchronized with MRAM Developers Portal!</p>";
            
            // Show updated configuration
            $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('non_musking_enabled', 'non_musking_api_url', 'non_musking_username', 'non_musking_api_key', 'non_musking_sender_id')");
            $stmt->execute();
            $updated_settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $updated_config = [];
            foreach ($updated_settings as $setting) {
                $updated_config[$setting['setting_key']] = $setting['setting_value'];
            }
            
            echo "<h4>Updated Configuration:</h4>";
            echo "<ul>";
            echo "<li><strong>Enabled:</strong> " . ($updated_config['non_musking_enabled'] ?? '0') . "</li>";
            echo "<li><strong>API URL:</strong> " . ($updated_config['non_musking_api_url'] ?? 'Not set') . "</li>";
            echo "<li><strong>Username:</strong> " . ($updated_config['non_musking_username'] ?? 'Not set') . "</li>";
            echo "<li><strong>API Key:</strong> " . (!empty($updated_config['non_musking_api_key']) ? substr($updated_config['non_musking_api_key'], 0, 10) . '...' : 'Not set') . "</li>";
            echo "<li><strong>Sender ID:</strong> " . ($updated_config['non_musking_sender_id'] ?? 'Not set') . "</li>";
            echo "</ul>";
            
        } catch (Exception $e) {
            echo "<p style='color:red;'>❌ Synchronization error: " . $e->getMessage() . "</p>";
        }
    } else {
        echo "<p style='color:green; font-size:18px; font-weight:bold;'>✅ All settings already match MRAM Developers Portal!</p>";
    }

    echo "<h3>Action Links:</h3>";
    echo "<ul>";
    echo "<li><a href='simple_test_sms.php'>Send Test SMS</a> - Test if it works</li>";
    echo "<li><a href='admin/sms_settings.php'>Open Settings Page</a> - Review settings</li>";
    echo "</ul>";

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

echo "<h3>Note:</h3>";
echo "<p>This process updates all settings according to MRAM Developers Portal (https://sms.mram.com.bd/Developers).</p>";
?>