<?php
// Advanced SMS test with proper encoding for MRAM API
$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>Advanced 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> " . ($config['non_musking_api_key'] ?? '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 for MRAM API
                $normalized_phone = $phone;
                if (substr($phone, 0, 3) === '+88') {
                    $normalized_phone = substr($phone, 1); // Remove the +
                } 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>";
                
                // Get API credentials
                $apiUrl = $config['non_musking_api_url'];
                $apiKey = $config['non_musking_api_key'];
                $senderId = $config['non_musking_sender_id'];
                
                // Method 1: Using cURL with POST data (more reliable)
                echo "<h5>Method 1: POST Request</h5>";
                
                $postData = [
                    'api_key' => $apiKey,
                    'type' => 'text',
                    'contacts' => $normalized_phone,
                    'senderid' => $senderId,
                    'msg' => $message
                ];
                
                $ch = curl_init($apiUrl);
                
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
                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>POST 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>";
                
                // Method 2: Using GET request as backup
                echo "<h5>Method 2: GET Request (Backup)</h5>";
                
                $getUrl = $apiUrl . '?' . http_build_query([
                    'api_key' => $apiKey,
                    'type' => 'text',
                    'contacts' => $normalized_phone,
                    'senderid' => $senderId,
                    'msg' => $message
                ], '', '&', PHP_QUERY_RFC3986);
                
                echo "<p><strong>GET URL:</strong> $getUrl</p>";
                
                $ch2 = curl_init($getUrl);
                
                curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch2, CURLOPT_TIMEOUT, 30);
                curl_setopt($ch2, CURLOPT_HTTPHEADER, [
                    'Content-Type: application/x-www-form-urlencoded',
                    'Accept: application/json'
                ]);
                curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
                
                $getResponse = curl_exec($ch2);
                $getHttpCode = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
                $getCurlError = curl_error($ch2);
                curl_close($ch2);
                
                echo "<h4>GET Response:</h4>";
                echo "<p><strong>HTTP Code:</strong> $getHttpCode</p>";
                if ($getCurlError) {
                    echo "<p style='color:red;'><strong>Error:</strong> $getCurlError</p>";
                }
                echo "<p><strong>Raw Response:</strong> " . htmlspecialchars($getResponse) . "</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'
                ];
                
                // Check responses for error codes
                $responses = [$response, $getResponse];
                $hasError = false;
                
                foreach ($responses as $resp) {
                    if (is_numeric(trim($resp))) {
                        $errorCode = trim($resp);
                        if (isset($error_interpretation[$errorCode])) {
                            echo "<p style='color:red; font-weight:bold;'>❌ Error Code $errorCode: {$error_interpretation[$errorCode]}</p>";
                            $hasError = true;
                        } else {
                            echo "<p style='color:orange; font-weight:bold;'>⚠️ Unknown Numeric Response: $errorCode</p>";
                        }
                    }
                }
                
                if (!$hasError && ($httpCode == 200 || $getHttpCode == 200)) {
                    echo "<p style='color:green; font-size:18px; font-weight:bold;'>✅ SMS Request Successfully Processed!</p>";
                    echo "<p>If you're not receiving SMS on your phone, check:</p>";
                    echo "<ul>";
                    echo "<li>Your MRAM account balance</li>";
                    echo "<li>Sender ID approval status</li>";
                    echo "<li>Phone number validity</li>";
                    echo "<li>Message content compliance</li>";
                    echo "</ul>";
                }
            }
        }
    }
    
} 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='final_api_key_fix.php'>Final API Key Fix</a> - Ensure correct API key</li>";
echo "<li><a href='comprehensive_fix.php'>Comprehensive Fix</a> - Verify all settings</li>";
echo "</ul>";
?>