<?php
/**
 * Direct Bank Transaction SMS Test
 * Tests SMS notification specifically for bank transaction verification
 */

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

echo "<h2>🧪 Direct Bank Transaction SMS Test</h2>";
echo "<p>Testing SMS notifications for bank transaction verification functionality</p>";

try {
    // First, ensure all required settings are enabled
    echo "<h3>🔧 Ensuring Required Settings:</h3>";
    
    $required_settings = [
        'sms_enabled' => '1',
        'non_musking_enabled' => '1',
        'sms_send_bank_transaction_notifications' => '1',
        'sms_send_to_guardian' => '1'
    ];
    
    foreach ($required_settings as $key => $value) {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$key, $value, $value]);
        echo "<p>✅ Ensured $key = $value</p>";
    }
    
    // Ensure SMS templates exist
    echo "<h3>📝 Ensuring SMS Templates:</h3>";
    
    $templates = [
        'sms_send_bank_transaction_templates_bank_transaction' => 'প্রিয় {name}, আপনার ব্যাংক ট্রানজেকশন ৳{amount} টাকা সফলভাবে যাচাই করা হয়েছে। বর্তমান বকেয়া: ৳{due_amount} টাকা। ধন্যবাদ।',
        'sms_send_bank_transaction_templates_bank_transaction_rejection' => 'প্রিয় {name}, আপনার ব্যাংক ট্রানজেকশন ৳{amount} টাকা প্রত্যাখ্যান করা হয়েছে। কারণ: {notes}।'
    ];
    
    foreach ($templates as $key => $value) {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$key, $value, $value]);
        echo "<p>✅ Ensured template: $key</p>";
    }
    
    // Test with a sample student
    echo "<h3>👤 Testing with Sample Student:</h3>";
    
    // Get a student with phone number for testing
    $stmt = $pdo->prepare("
        SELECT s.id, s.first_name, s.last_name, s.phone, s.guardian_phone 
        FROM students s 
        WHERE (s.phone IS NOT NULL AND s.phone != '') 
        OR (s.guardian_phone IS NOT NULL AND s.guardian_phone != '') 
        LIMIT 1
    ");
    $stmt->execute();
    $student = $stmt->fetch();
    
    if (!$student) {
        echo "<p>❌ No student found with phone number. Please add a student with phone number for testing.</p>";
        exit;
    }
    
    echo "<p><strong>Test Student:</strong> " . htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) . "</p>";
    echo "<p><strong>Phone:</strong> " . htmlspecialchars($student['phone'] ?? 'N/A') . "</p>";
    echo "<p><strong>Guardian Phone:</strong> " . htmlspecialchars($student['guardian_phone'] ?? 'N/A') . "</p>";
    
    // Test SMS sending
    echo "<h3>📱 Testing SMS Sending:</h3>";
    
    $smsHelperPath = __DIR__ . '/../includes/sms_helper.php';
    if (!file_exists($smsHelperPath)) {
        echo "<p>❌ SMS helper file not found at: $smsHelperPath</p>";
        exit;
    }
    
    require_once $smsHelperPath;
    
    // Test bank transaction verification SMS
    echo "<h4>Testing Bank Transaction Verification SMS:</h4>";
    
    try {
        $smsSystem = new SmsNotificationSystem($pdo);
        
        $test_result = $smsSystem->sendBankTransactionNotification(
            $student['id'],
            trim($student['first_name'] . ' ' . $student['last_name']),
            1500, // test amount
            500,  // test due amount
            $student['phone']
        );
        
        if ($test_result['success']) {
            echo "<p style='color: green;'>✅ SUCCESS: Bank transaction verification SMS sent!</p>";
            echo "<p><strong>To:</strong> " . implode(', ', $test_result['to']) . "</p>";
            echo "<p><strong>Message:</strong> " . htmlspecialchars($test_result['message']) . "</p>";
            if (isset($test_result['raw_response'])) {
                echo "<p><strong>Response:</strong> " . htmlspecialchars($test_result['raw_response']) . "</p>";
            }
        } else {
            echo "<p style='color: red;'>❌ FAILED: Could not send bank transaction verification SMS</p>";
            echo "<p><strong>Error:</strong> " . htmlspecialchars($test_result['message'] ?? 'Unknown error') . "</p>";
            if (isset($test_result['raw_response'])) {
                echo "<p><strong>Raw Response:</strong> " . htmlspecialchars($test_result['raw_response']) . "</p>";
            }
        }
    } catch (Exception $e) {
        echo "<p style='color: red;'>❌ Exception during SMS test: " . $e->getMessage() . "</p>";
    }
    
    // Test bank transaction rejection SMS
    echo "<h4>Testing Bank Transaction Rejection SMS:</h4>";
    
    try {
        $smsSystem = new SmsNotificationSystem($pdo);
        
        $test_result2 = $smsSystem->sendBankTransactionRejectionNotification(
            $student['id'],
            trim($student['first_name'] . ' ' . $student['last_name']),
            1500, // test amount
            'TX123456789', // test transaction ID
            'Test rejection - invalid receipt image', // test reason
            $student['phone']
        );
        
        if ($test_result2['success']) {
            echo "<p style='color: green;'>✅ SUCCESS: Bank transaction rejection SMS sent!</p>";
            echo "<p><strong>To:</strong> " . implode(', ', $test_result2['to']) . "</p>";
            echo "<p><strong>Message:</strong> " . htmlspecialchars($test_result2['message']) . "</p>";
            if (isset($test_result2['raw_response'])) {
                echo "<p><strong>Response:</strong> " . htmlspecialchars($test_result2['raw_response']) . "</p>";
            }
        } else {
            echo "<p style='color: red;'>❌ FAILED: Could not send bank transaction rejection SMS</p>";
            echo "<p><strong>Error:</strong> " . htmlspecialchars($test_result2['message'] ?? 'Unknown error') . "</p>";
            if (isset($test_result2['raw_response'])) {
                echo "<p><strong>Raw Response:</strong> " . htmlspecialchars($test_result2['raw_response']) . "</p>";
            }
        }
    } catch (Exception $e) {
        echo "<p style='color: red;'>❌ Exception during rejection SMS test: " . $e->getMessage() . "</p>";
    }
    
    // Show current configuration
    echo "<h3>📊 Current Configuration Summary:</h3>";
    
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE '%sms%' OR setting_key LIKE '%non_musking%' ORDER BY setting_key");
    $stmt->execute();
    $settings = $stmt->fetchAll();
    
    echo "<table border='1' cellpadding='5'>";
    echo "<tr><th>Setting</th><th>Value</th><th>Status</th></tr>";
    foreach ($settings as $setting) {
        $key = $setting['setting_key'];
        $value = $setting['setting_value'];
        $status = ($value === '1' || $value === 'true') ? '✅ ENABLED' : '⚪';
        if (strpos($key, 'password') !== false || strpos($key, 'api_key') !== false) {
            $value = '***HIDDEN***';
        }
        echo "<tr><td>$key</td><td>" . htmlspecialchars($value) . "</td><td>$status</td></tr>";
    }
    echo "</table>";
    
    echo "<h3>🎯 Next Steps:</h3>";
    echo "<ol>";
    echo "<li>Go to <a href='verify_bank_transactions.php'>Bank Transaction Verification Page</a></li>";
    echo "<li>Select a pending transaction</li>";
    echo "<li>Click 'Verify' to approve the transaction</li>";
    echo "<li>Check if SMS notification is sent to the student's phone</li>";
    echo "<li>Also test 'Reject' functionality to verify rejection SMS</li>";
    echo "</ol>";
    
    echo "<div style='background: #d4edda; padding: 15px; border: 1px solid #c3e6cb; border-radius: 5px; margin-top: 20px;'>";
    echo "<h4>✅ Test Complete</h4>";
    echo "<p>If the above tests were successful, bank transaction SMS notifications should now be working properly.</p>";
    echo "<p>Any issues with the actual verification page may be related to:</p>";
    echo "<ul>";
    echo "<li>Student phone number not properly stored in database</li>";
    echo "<li>MRAM API credentials or connectivity issues</li>";
    echo "<li>Server-side error handling in the verification script</li>";
    echo "</ul>";
    echo "</div>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'><strong>Error:</strong> " . $e->getMessage() . "</p>";
    echo "<p>Please check your database connection and try again.</p>";
}
?>