<?php
/**
 * Immediate SMS Notification Fix
 * Direct fix for bank transaction verification SMS notifications
 */

echo "<!DOCTYPE html>
<html>
<head>
    <title>Immediate SMS Notification Fix</title>
    <meta charset='UTF-8'>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 20px auto; padding: 20px; }
        .error { background: #f8d7da; color: #721c24; padding: 15px; border: 1px solid #f5c6cb; border-radius: 5px; margin: 10px 0; }
        .success { background: #d4edda; color: #155724; padding: 15px; border: 1px solid #c3e6cb; border-radius: 5px; margin: 10px 0; }
        .info { background: #d1ecf1; color: #0c5460; padding: 15px; border: 1px solid #bee5eb; border-radius: 5px; margin: 10px 0; }
        .warning { background: #fff3cd; color: #856404; padding: 15px; border: 1px solid #ffeaa7; border-radius: 5px; margin: 10px 0; }
        h2 { color: #333; }
        h3 { color: #555; }
        pre { background: #f8f9fa; padding: 10px; border-radius: 5px; overflow-x: auto; }
    </style>
</head>
<body>
    <h2>📱 Immediate SMS Notification Fix</h2>
    <p>Fixing SMS notifications for bank transaction verification - Payment verified but no notification sent</p>";

try {
    require_once 'config/database.php';
    echo "<div class='success'>✅ Database connected successfully</div>";
    
    // Step 1: Force enable all critical SMS settings
    echo "<h3>🔧 Step 1: Enabling Critical SMS Settings</h3>";
    
    $critical_settings = [
        'sms_enabled' => '1',
        'non_musking_enabled' => '1', 
        'sms_send_bank_transaction_notifications' => '1',
        'sms_send_to_guardian' => '1'
    ];
    
    foreach ($critical_settings as $key => $value) {
        try {
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$key, $value, $value]);
            echo "<div class='success'>✅ Enabled: $key</div>";
        } catch (Exception $e) {
            echo "<div class='error'>❌ Failed to enable $key: " . $e->getMessage() . "</div>";
        }
    }
    
    // Step 2: Create/update SMS templates with proper keys
    echo "<h3>📝 Step 2: Setting Up SMS Templates</h3>";
    
    $templates = [
        // Primary template key used in the verification code
        'non_musking_tpl_bank_transaction' => 'প্রিয় {name}, আপনার ব্যাংক ট্রানজেকশন ৳{amount} টাকা সফলভাবে যাচাই করা হয়েছে। বর্তমান বকেয়া: ৳{due_amount} টাকা। ধন্যবাদ।',
        
        // Backup template keys (alternative names)
        'sms_tpl_bank_transaction' => 'প্রিয় {name}, আপনার ব্যাংক ট্রানজেকশন ৳{amount} টাকা সফলভাবে যাচাই করা হয়েছে। বর্তমান বকেয়া: ৳{due_amount} টাকা। ধন্যবাদ।',
        
        // Standard template keys
        'sms_send_bank_transaction_templates_bank_transaction' => 'প্রিয় {name}, আপনার ব্যাংক ট্রানজেকশন ৳{amount} টাকা সফলভাবে যাচাই করা হয়েছে। বর্তমান বকেয়া: ৳{due_amount} টাকা। ধন্যবাদ।',
        
        // Rejection template
        'sms_send_bank_transaction_templates_bank_transaction_rejection' => 'প্রিয় {name}, আপনার ব্যাংক ট্রানজেকশন ৳{amount} টাকা প্রত্যাখ্যান করা হয়েছে। কারণ: {notes}।'
    ];
    
    foreach ($templates as $key => $value) {
        try {
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$key, $value, $value]);
            echo "<div class='success'>✅ Set template: $key</div>";
        } catch (Exception $e) {
            echo "<div class='error'>❌ Failed to set template $key: " . $e->getMessage() . "</div>";
        }
    }
    
    // Step 3: Verify student phone numbers exist
    echo "<h3>👤 Step 3: Checking Student Phone Numbers</h3>";
    
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as total, 
               COUNT(CASE WHEN phone IS NOT NULL AND phone != '' THEN 1 END) as with_phone,
               COUNT(CASE WHEN guardian_phone IS NOT NULL AND guardian_phone != '' THEN 1 END) as with_guardian_phone
        FROM students
    ");
    $stmt->execute();
    $phone_stats = $stmt->fetch();
    
    echo "<div class='info'>";
    echo "<p><strong>Total Students:</strong> " . $phone_stats['total'] . "</p>";
    echo "<p><strong>Students with Phone:</strong> " . $phone_stats['with_phone'] . "</p>";
    echo "<p><strong>Students with Guardian Phone:</strong> " . $phone_stats['with_guardian_phone'] . "</p>";
    echo "</div>";
    
    if ($phone_stats['with_phone'] == 0 && $phone_stats['with_guardian_phone'] == 0) {
        echo "<div class='error'>❌ CRITICAL: No students have phone numbers!</div>";
        echo "<div class='warning'>This is why no SMS notifications can be sent. Please add phone numbers to student records.</div>";
    } else {
        echo "<div class='success'>✅ Students with phone numbers found</div>";
    }
    
    // Step 4: Test with actual student data
    echo "<h3>🧪 Step 4: Testing with Real Student Data</h3>";
    
    if ($phone_stats['with_phone'] > 0) {
        // 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,
                   COALESCE(SUM(f.amount - f.paid_amount), 0) as total_due
            FROM students s
            LEFT JOIN fees f ON s.id = f.student_id AND f.status IN ('pending', 'partial', 'overdue')
            WHERE s.phone IS NOT NULL AND s.phone != ''
            GROUP BY s.id
            LIMIT 1
        ");
        $stmt->execute();
        $test_student = $stmt->fetch();
        
        if ($test_student) {
            echo "<div class='info'>";
            echo "<p><strong>Test Student:</strong> " . htmlspecialchars($test_student['first_name'] . ' ' . $test_student['last_name']) . "</p>";
            echo "<p><strong>Phone:</strong> " . htmlspecialchars($test_student['phone']) . "</p>";
            echo "<p><strong>Current Due:</strong> ৳" . number_format($test_student['total_due'], 2) . "</p>";
            echo "</div>";
            
            // Test SMS functionality
            $smsHelperPath = __DIR__ . '/includes/sms_helper.php';
            if (file_exists($smsHelperPath)) {
                require_once $smsHelperPath;
                echo "<div class='success'>✅ SMS helper loaded</div>";
                
                try {
                    $smsSystem = new SmsNotificationSystem($pdo);
                    
                    echo "<h4>Testing Bank Transaction Notification:</h4>";
                    $result = $smsSystem->sendBankTransactionNotification(
                        $test_student['id'],
                        trim($test_student['first_name'] . ' ' . $test_student['last_name']),
                        1500, // test amount
                        $test_student['total_due'],
                        $test_student['phone']
                    );
                    
                    if ($result['success']) {
                        echo "<div class='success'>🎉 <strong>SUCCESS!</strong> SMS notification sent successfully!</div>";
                        echo "<p><strong>To:</strong> " . implode(', ', $result['to']) . "</p>";
                        echo "<p><strong>Message:</strong> " . htmlspecialchars($result['message']) . "</p>";
                        echo "<div class='success' style='font-size: 18px;'>";
                        echo "✅ <strong>THIS MEANS SMS NOTIFICATIONS SHOULD NOW WORK!</strong>";
                        echo "</div>";
                    } else {
                        echo "<div class='error'>❌ SMS test failed</div>";
                        echo "<p><strong>Error:</strong> " . htmlspecialchars($result['message'] ?? 'Unknown error') . "</p>";
                        if (isset($result['raw_response'])) {
                            echo "<p><strong>Response:</strong> " . htmlspecialchars($result['raw_response']) . "</p>";
                        }
                    }
                    
                } catch (Exception $e) {
                    echo "<div class='error'>❌ SMS test exception: " . $e->getMessage() . "</div>";
                }
            } else {
                echo "<div class='error'>❌ SMS helper not found at: $smsHelperPath</div>";
            }
        }
    }
    
    // Step 5: Show all current SMS settings
    echo "<h3>📊 Step 5: Current SMS Configuration</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();
    $all_settings = $stmt->fetchAll();
    
    echo "<table border='1' cellpadding='5'>";
    echo "<tr><th>Setting Key</th><th>Value</th></tr>";
    foreach ($all_settings as $setting) {
        $key = $setting['setting_key'];
        $value = $setting['setting_value'];
        if (strpos($key, 'password') !== false || strpos($key, 'api_key') !== false) {
            $value = '***HIDDEN***';
        }
        $status = (in_array($key, array_keys($critical_settings)) && $value === '1') ? '✅ ACTIVE' : '⚪';
        echo "<tr><td>$key</td><td>" . htmlspecialchars($value) . " $status</td></tr>";
    }
    echo "</table>";
    
    // Final Status Check
    echo "<h3>🏁 Final Status Check</h3>";
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_bank_transaction_notifications'");
    $stmt->execute();
    $result = $stmt->fetch();
    
    if ($result && $result['setting_value'] === '1' && $phone_stats['with_phone'] > 0) {
        echo "<div class='success' style='font-size: 20px; padding: 20px;'>";
        echo "🎉 <strong>ALL SYSTEMS READY!</strong>";
        echo "<p>Bank transaction SMS notifications should now be working properly.</p>";
        echo "</div>";
    } else {
        echo "<div class='warning'>";
        echo "<h4>⚠️ Issues Found:</h4>";
        if (!$result || $result['setting_value'] !== '1') {
            echo "<p>❌ Bank transaction notifications not enabled</p>";
        }
        if ($phone_stats['with_phone'] == 0) {
            echo "<p>❌ No students have phone numbers</p>";
        }
        echo "</div>";
    }
    
    echo "<div class='info'>";
    echo "<h3>🎯 Next Steps:</h3>";
    echo "<ol>";
    echo "<li>Go to <a href='fees/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>If still not working, check server error logs</li>";
    echo "</ol>";
    echo "</div>";
    
    echo "<div class='warning'>";
    echo "<h3>⚠️ If Still Not Working:</h3>";
    echo "<p>Check these common issues:</p>";
    echo "<ul>";
    echo "<li>Student phone numbers in database (must not be empty)</li>";
    echo "<li>MRAM API credentials and account balance</li>";
    echo "<li>Server connectivity to MRAM SMS gateway</li>";
    echo "<li>Check PHP error logs for detailed debugging</li>";
    echo "</ul>";
    echo "</div>";
    
} catch (Exception $e) {
    echo "<div class='error'>";
    echo "<h3>❌ Critical Error</h3>";
    echo "<p><strong>Error:</strong> " . $e->getMessage() . "</p>";
    echo "</div>";
}

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