<?php
/**
 * Test SMS sending functionality
 * This script will test if SMS can be sent using current configuration
 */

require_once 'config/database.php';
require_once 'includes/sms_notification_system.php';

echo "<!DOCTYPE html>
<html>
<head>
    <title>Test SMS Functionality</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        pre { background: #f5f5f5; padding: 10px; }
    </style>
</head>
<body>";

echo "<h1>🧪 Testing SMS Functionality</h1>";

try {
    // Check configuration
    echo "<h3>📋 Configuration Check</h3>";
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
    $stmt->execute();
    $result = $stmt->fetch();
    $sms_enabled = $result && $result['setting_value'] === '1';
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_bank_transaction_notifications'");
    $stmt->execute();
    $result = $stmt->fetch();
    $bank_notifications_enabled = $result && $result['setting_value'] === '1';
    
    echo "<p>Non-musking SMS Enabled: " . ($sms_enabled ? '✅ YES' : '❌ NO') . "</p>";
    echo "<p>Bank Notifications Enabled: " . ($bank_notifications_enabled ? '✅ YES' : '❌ NO') . "</p>";
    
    if (!$sms_enabled || !$bank_notifications_enabled) {
        echo "<p class='error'>❌ Required services are not enabled. Please run fix_sms_notifications.php first.</p>";
        exit;
    }
    
    // Get a test student with phone number
    echo "<h3>👤 Test Student Selection</h3>";
    
    $stmt = $pdo->prepare("
        SELECT s.id, s.first_name, s.last_name, s.phone 
        FROM students s 
        WHERE s.phone IS NOT NULL AND s.phone != ''
        LIMIT 1
    ");
    $stmt->execute();
    $student = $stmt->fetch();
    
    if (!$student) {
        echo "<p class='error'>❌ No students with phone numbers found. Please add phone numbers to student profiles.</p>";
        exit;
    }
    
    echo "<p>Selected student: {$student['first_name']} {$student['last_name']} (ID: {$student['id']})</p>";
    echo "<p>Phone number: " . htmlspecialchars($student['phone']) . "</p>";
    
    // Test SMS sending
    echo "<h3>📤 Testing SMS Send</h3>";
    
    $smsSystem = new SmsNotificationSystem($pdo);
    
    // Test bank transaction notification
    echo "<h4>Testing Bank Transaction Notification...</h4>";
    
    $test_result = $smsSystem->sendBankTransactionNotification(
        $student['id'],
        trim($student['first_name'] . ' ' . $student['last_name']),
        1000, // test amount
        500,  // test due amount
        $student['phone']
    );
    
    if ($test_result['success']) {
        echo "<p class='success'>✅ Bank transaction SMS sent successfully!</p>";
        echo "<p>To: " . implode(', ', $test_result['to']) . "</p>";
        echo "<pre>Response: " . htmlspecialchars($test_result['raw_response']) . "</pre>";
    } else {
        echo "<p class='error'>❌ Failed to send bank transaction SMS</p>";
        echo "<p>Error: " . htmlspecialchars($test_result['message'] ?? 'Unknown error') . "</p>";
        if (isset($test_result['raw_response'])) {
            echo "<pre>Raw Response: " . htmlspecialchars($test_result['raw_response']) . "</pre>";
        }
    }
    
    // Test bank transaction rejection notification
    echo "<h4>Testing Bank Transaction Rejection Notification...</h4>";
    
    $test_result2 = $smsSystem->sendBankTransactionRejectionNotification(
        $student['id'],
        trim($student['first_name'] . ' ' . $student['last_name']),
        1000, // test amount
        'TX123456789', // test transaction ID
        'Test rejection reason', // test reason
        $student['phone']
    );
    
    if ($test_result2['success']) {
        echo "<p class='success'>✅ Bank transaction rejection SMS sent successfully!</p>";
        echo "<p>To: " . implode(', ', $test_result2['to']) . "</p>";
        echo "<pre>Response: " . htmlspecialchars($test_result2['raw_response']) . "</pre>";
    } else {
        echo "<p class='error'>❌ Failed to send bank transaction rejection SMS</p>";
        echo "<p>Error: " . htmlspecialchars($test_result2['message'] ?? 'Unknown error') . "</p>";
        if (isset($test_result2['raw_response'])) {
            echo "<pre>Raw Response: " . htmlspecialchars($test_result2['raw_response']) . "</pre>";
        }
    }
    
    // Check messages log
    echo "<h3>📝 Messages Log</h3>";
    
    $stmt = $pdo->prepare("
        SELECT * FROM messages_log 
        WHERE recipient = ? 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    $stmt->execute([$student['phone']]);
    $logs = $stmt->fetchAll();
    
    if ($logs) {
        echo "<table border='1' cellpadding='8' cellspacing='0'>";
        echo "<tr><th>Date</th><th>Recipient</th><th>Status</th><th>Message Preview</th></tr>";
        
        foreach ($logs as $log) {
            $status_class = $log['status'] === 'sent' ? 'success' : 'error';
            $message_preview = substr($log['message_content'], 0, 50) . '...';
            
            echo "<tr>";
            echo "<td>{$log['created_at']}</td>";
            echo "<td>" . htmlspecialchars($log['recipient']) . "</td>";
            echo "<td class='$status_class'>{$log['status']}</td>";
            echo "<td>" . htmlspecialchars($message_preview) . "</td>";
            echo "</tr>";
        }
        
        echo "</table>";
    } else {
        echo "<p>No SMS logs found for this number.</p>";
    }
    
    // Summary
    echo "<h3>📊 Test Summary</h3>";
    
    $total_tests = 2;
    $successful_tests = ($test_result['success'] ? 1 : 0) + ($test_result2['success'] ? 1 : 0);
    
    if ($successful_tests === $total_tests) {
        echo "<div class='success'>";
        echo "<h4>🎉 ALL TESTS PASSED!</h4>";
        echo "<p>SMS functionality is working correctly.</p>";
        echo "<p>You can now verify bank transactions and automatic SMS notifications will be sent.</p>";
        echo "</div>";
    } else {
        echo "<div class='error'>";
        echo "<h4>❌ SOME TESTS FAILED</h4>";
        echo "<p>$successful_tests out of $total_tests tests passed.</p>";
        echo "<p>Possible issues:</p>";
        echo "<ul>";
        echo "<li>Incorrect MRAM API credentials</li>";
        echo "<li>Network connectivity issues</li>";
        echo "<li>MRAM service temporarily unavailable</li>";
        echo "<li>Invalid phone number format</li>";
        echo "</ul>";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<div class='error'>";
    echo "<h3>❌ ERROR OCCURRED</h3>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
    echo "</div>";
}

echo "</body></html>";
?>