<?php
// Enhanced SMS test with proper URL encoding
$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>Enhanced SMS Test with Proper Encoding</h2>";
    
    // Get current 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);
    
    $config = [];
    foreach ($settings as $setting) {
        $config[$setting['setting_key']] = $setting['setting_value'];
    }

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

    // Check if we have all required settings
    $required = [
        'non_musking_enabled',
        'non_musking_api_url', 
        'non_musking_api_key',
        'non_musking_username',
        'non_musking_password',
        'non_musking_sender_id'
    ];
    
    $missing = [];
    foreach ($required as $req) {
        if (empty($config[$req])) {
            $missing[] = $req;
        }
    }
    
    if (!empty($missing)) {
        echo "<h3>Missing Settings:</h3>";
        echo "<ul>";
        foreach ($missing as $miss) {
            echo "<li style='color:red;'>❌ $miss</li>";
        }
        echo "</ul>";
    } else {
        echo "<h3>✅ All required settings are present!</h3>";
        
        // Show a test form
        echo "<h3>Send Test SMS:</h3>";
        echo "<form method='post'>";
        echo "<p>Phone: <input type='tel' name='phone' value='+8801977861762' placeholder='Enter phone number' required></p>";
        echo "<p>Message: <textarea name='message' required>Test message from Bidda system</textarea></p>";
        echo "<p><input type='submit' name='send' value='Send Test SMS'></p>";
        echo "</form>";
        
        if (isset($_POST['send'])) {
            $phone = trim($_POST['phone']);
            $message = trim($_POST['message']);
            
            if (!empty($phone) && !empty($message)) {
                // Normalize phone number (remove +88 prefix for MRAM API)
                $normalized_phone = $phone;
                if (substr($phone, 0, 3) === '+88') {
                    $normalized_phone = substr($phone, 1); // Remove the +, keep 88
                } elseif (substr($phone, 0, 2) === '88') {
                    $normalized_phone = $phone;
                } elseif (substr($phone, 0, 1) === '0') {
                    $normalized_phone = '88' . $phone;
                }
                
                echo "<h4>Sending test SMS to: $normalized_phone</h4>";
                
                // Create cURL request to test the API
                $apiUrl = $config['non_musking_api_url'];
                $apiKey = $config['non_musking_api_key'];
                $senderId = $config['non_musking_sender_id'];
                
                // Prepare the API request with proper URL encoding
                $params = [
                    'api_key' => $apiKey,
                    'type' => 'text',  // Changed to text
                    'contacts' => $normalized_phone,  // Proper phone format
                    'senderid' => $senderId,
                    'msg' => $message  // We'll encode this properly below
                ];
                
                // Build query string manually with proper encoding
                $query_string = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
                
                $full_url = $apiUrl . '?' . $query_string;
                
                echo "<p><strong>Request URL:</strong> $full_url</p>";
                
                $ch = curl_init($full_url);
                
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Content-Type: application/x-www-form-urlencoded',
                    'Accept: application/json'
                ]);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $curlError = curl_error($ch);
                curl_close($ch);
                
                echo "<h4>Response:</h4>";
                echo "<p><strong>HTTP Code:</strong> $httpCode</p>";
                if ($curlError) {
                    echo "<p style='color:red;'><strong>Error:</strong> $curlError</p>";
                }
                echo "<p><strong>Raw Response:</strong> " . htmlspecialchars($response) . "</p>";
                
                // Interpret MRAM error codes
                $error_interpretation = [
                    '1002' => 'Sender Id/Masking Not Found',
                    '1003' => 'API Not Found',
                    '1004' => 'SPAM Detected',
                    '1005' => 'Internal Error',
                    '1006' => 'Internal Error',
                    '1007' => 'Balance Insufficient',
                    '1008' => 'Message is empty',
                    '1009' => 'Message Type Not Set (text/unicode)',
                    '1010' => 'Invalid User & Password',
                    '1011' => 'Invalid User Id',
                    '1012' => 'Invalid Number',
                    '1013' => 'API limit error',
                    '1014' => 'No matching template',
                    '1015' => 'SMS Content Validation Fails',
                    '1016' => 'IP address not allowed!!',
                    '1019' => 'Sms Purpose Missing'
                ];
                
                if (is_numeric(trim($response))) {
                    $error_code = trim($response);
                    if (isset($error_interpretation[$error_code])) {
                        echo "<p style='color:red; font-weight:bold;'>❌ Error Code $error_code: {$error_interpretation[$error_code]}</p>";
                    } else {
                        echo "<p style='color:red; font-weight:bold;'>❌ Unknown Error Code: $error_code</p>";
                    }
                } elseif ($httpCode == 200) {
                    if (is_numeric(trim($response))) {
                        echo "<p style='color:orange; font-weight:bold;'>⚠️ Got numeric response instead of success: " . trim($response) . "</p>";
                        echo "<p>This might indicate an internal error or processing delay.</p>";
                    } else {
                        echo "<p style='color:green; font-size:18px; font-weight:bold;'>✅ SMS Request Accepted!</p>";
                        echo "<p>The API accepted your request. The message should be delivered shortly.</p>";
                    }
                } else {
                    echo "<p style='color:red; font-size:18px; font-weight:bold;'>❌ Failed to send SMS</p>";
                    if ($httpCode == 401) {
                        echo "<p style='color:red;'>⚠️ 401 Authentication Error - Check your API Key and credentials!</p>";
                    }
                }
            }
        }
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Database connection error: " . $e->getMessage() . "</p>";
}

echo "<h3>Helpful Links:</h3>";
echo "<ul>";
echo "<li><a href='comprehensive_fix.php'>Comprehensive Fix</a> - Verify all settings</li>";
echo "<li><a href='update_to_real_mram_api.php'>Update MRAM API</a> - Ensure correct values</li>";
echo "</ul>";
?>