<?php
// Simple SMS test 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>Simple SMS Test</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
                if (substr($phone, 0, 1) === '0') {
                    $phone = '+88' . $phone;
                } elseif (substr($phone, 0, 2) === '88') {
                    $phone = '+' . $phone;
                } elseif (substr($phone, 0, 3) !== '+88') {
                    $phone = '+88' . $phone;
                }
                
                echo "<h4>Sending test SMS to: $phone</h4>";
                
                // Create cURL request to test the API
                $apiUrl = $config['non_musking_api_url'];
                $apiKey = $config['non_musking_api_key'];
                
                $payload = [
                    'mobile_number' => $phone,
                    'sms' => $message,
                    'sender_id' => $config['non_musking_sender_id']
                ];
                
                $ch = curl_init($apiUrl);
                
                $authHeader = 'Authorization: App ' . $apiKey;
                
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Content-Type: application/json',
                    'Accept: application/json',
                    $authHeader
                ]);
                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>";
                
                if ($httpCode == 200 || (is_numeric($httpCode) && $httpCode >= 200 && $httpCode < 300)) {
                    echo "<p style='color:green; font-size:18px; font-weight:bold;'>✅ SMS Sent Successfully!</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='fix_api_key.php'>Fix API Key</a> - Fix common API key issues</li>";
echo "<li><a href='simple_sync.php'>Sync with MRAM</a> - Ensure settings match portal</li>";
echo "</ul>";
?>