<?php
/**
 * Bank Transaction SMS Notification Deep Diagnostic
 * Comprehensive check for why SMS notifications aren't working after verification
 */

echo "<!DOCTYPE html>
<html>
<head>
    <title>Bank Transaction SMS Deep Diagnostic</title>
    <meta charset='UTF-8'>
    <style>
        body { font-family: Arial, sans-serif; max-width: 1000px; 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; }
        h4 { color: #666; }
        table { border-collapse: collapse; width: 100%; margin: 10px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .step { margin: 15px 0; padding: 10px; border-left: 4px solid #007cba; }
    </style>
</head>
<body>
    <h2>🔍 Bank Transaction SMS Notification Deep Diagnostic</h2>
    <p>Comprehensive analysis of why SMS notifications aren't working after bank transaction verification</p>";

try {
    // Load database configuration
    require_once 'config/database.php';
    echo "<div class='success'>✅ Database connection established</div>";
    
    // Step 1: Check all SMS-related settings
    echo "<div class='step'>";
    echo "<h3>Step 1: SMS Configuration Check</h3>";
    
    $required_settings = [
        'sms_enabled' => 'General SMS Service',
        'non_musking_enabled' => 'Non-Musking SMS Service',
        'sms_send_bank_transaction_notifications' => 'Bank Transaction Notifications',
        'sms_send_to_guardian' => 'Send to Guardian',
        'non_musking_api_key' => 'MRAM API Key',
        'non_musking_username' => 'MRAM Username',
        'non_musking_sender_id' => 'Sender ID'
    ];
    
    $missing_configs = [];
    
    echo "<table>";
    echo "<tr><th>Setting</th><th>Value</th><th>Status</th></tr>";
    
    foreach ($required_settings as $key => $description) {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        
        $value = $result ? $result['setting_value'] : 'NOT SET';
        $display_value = $value;
        
        // Hide sensitive information
        if (strpos($key, 'api_key') !== false || strpos($key, 'password') !== false) {
            $display_value = strlen($value) > 10 ? substr($value, 0, 5) . '...' . substr($value, -5) : '***HIDDEN***';
        }
        
        if ($result && $result['setting_value'] !== '' && $result['setting_value'] !== '0') {
            $status = '✅ CONFIGURED';
            echo "<tr><td>$description</td><td>$display_value</td><td style='color: green;'>$status</td></tr>";
        } else {
            $status = '❌ MISSING';
            echo "<tr><td>$description</td><td>$display_value</td><td style='color: red;'>$status</td></tr>";
            $missing_configs[$key] = '1';
        }
    }
    echo "</table>";
    
    if (!empty($missing_configs)) {
        echo "<div class='warning'>";
        echo "<h4>Missing Critical Configurations:</h4>";
        echo "<ul>";
        foreach ($missing_configs as $key => $value) {
            echo "<li>$key</li>";
        }
        echo "</ul>";
        echo "</div>";
    }
    echo "</div>";
    
    // Step 2: Check SMS templates
    echo "<div class='step'>";
    echo "<h3>Step 2: SMS Template Verification</h3>";
    
    $templates = [
        'sms_send_bank_transaction_templates_bank_transaction' => 'Bank Transaction Approval Template',
        'sms_send_bank_transaction_templates_bank_transaction_rejection' => 'Bank Transaction Rejection Template'
    ];
    
    echo "<table>";
    echo "<tr><th>Template</th><th>Status</th><th>Preview</th></tr>";
    
    foreach ($templates as $key => $description) {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        
        if ($result && !empty($result['setting_value'])) {
            $status = '✅ EXISTS';
            $preview = substr($result['setting_value'], 0, 50) . '...';
            echo "<tr><td>$description</td><td style='color: green;'>$status</td><td>$preview</td></tr>";
        } else {
            $status = '❌ MISSING';
            echo "<tr><td>$description</td><td style='color: red;'>$status</td><td>Not configured</td></tr>";
            $missing_configs[$key] = 'Your bank transaction of {amount} BDT has been verified. Current due: {due_amount} BDT. Thank you.';
        }
    }
    echo "</table>";
    echo "</div>";
    
    // Step 3: Test student phone numbers
    echo "<div class='step'>";
    echo "<h3>Step 3: Student Phone Number Check</h3>";
    
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as total_students,
               COUNT(CASE WHEN phone IS NOT NULL AND phone != '' THEN 1 END) as students_with_phone,
               COUNT(CASE WHEN guardian_phone IS NOT NULL AND guardian_phone != '' THEN 1 END) as students_with_guardian_phone
        FROM students
    ");
    $stmt->execute();
    $phone_stats = $stmt->fetch();
    
    echo "<div class='info'>";
    echo "<p><strong>Total Students:</strong> " . $phone_stats['total_students'] . "</p>";
    echo "<p><strong>Students with Phone:</strong> " . $phone_stats['students_with_phone'] . "</p>";
    echo "<p><strong>Students with Guardian Phone:</strong> " . $phone_stats['students_with_guardian_phone'] . "</p>";
    echo "</div>";
    
    if ($phone_stats['students_with_phone'] == 0 && $phone_stats['students_with_guardian_phone'] == 0) {
        echo "<div class='error'>❌ No students have phone numbers configured!</div>";
        echo "<div class='warning'>This is likely why no SMS notifications are being sent.</div>";
    } else {
        echo "<div class='success'>✅ Some students have phone numbers configured</div>";
    }
    echo "</div>";
    
    // Step 4: Test actual SMS sending
    echo "<div class='step'>";
    echo "<h3>Step 4: SMS Sending Test</h3>";
    
    // Get a test student
    $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();
    $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'] ?? 'N/A') . "</p>";
        echo "<p><strong>Guardian Phone:</strong> " . htmlspecialchars($test_student['guardian_phone'] ?? 'N/A') . "</p>";
        echo "</div>";
        
        // Test SMS helper
        $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);
                
                // Test bank transaction notification
                echo "<h4>Testing Bank Transaction Approval SMS:</h4>";
                $result = $smsSystem->sendBankTransactionNotification(
                    $test_student['id'],
                    trim($test_student['first_name'] . ' ' . $test_student['last_name']),
                    1500, // test amount
                    500,  // test due amount
                    $test_student['phone']
                );
                
                if ($result['success']) {
                    echo "<div class='success'>✅ SMS sent successfully!</div>";
                    echo "<p><strong>To:</strong> " . implode(', ', $result['to']) . "</p>";
                    echo "<p><strong>Message:</strong> " . htmlspecialchars($result['message']) . "</p>";
                } else {
                    echo "<div class='error'>❌ SMS failed to send</div>";
                    echo "<p><strong>Error:</strong> " . htmlspecialchars($result['message'] ?? 'Unknown error') . "</p>";
                    if (isset($result['raw_response'])) {
                        echo "<p><strong>Raw Response:</strong> " . htmlspecialchars($result['raw_response']) . "</p>";
                    }
                }
                
            } catch (Exception $e) {
                echo "<div class='error'>❌ SMS test failed: " . $e->getMessage() . "</div>";
            }
        } else {
            echo "<div class='error'>❌ SMS helper file not found at: $smsHelperPath</div>";
        }
    } else {
        echo "<div class='error'>❌ No test student found with phone number</div>";
    }
    echo "</div>";
    
    // Step 5: Fix missing configurations
    echo "<div class='step'>";
    echo "<h3>Step 5: Auto-Fix Missing Configurations</h3>";
    
    if (!empty($missing_configs)) {
        echo "<div class='warning'>Fixing " . count($missing_configs) . " missing configurations...</div>";
        
        foreach ($missing_configs 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'>✅ Fixed: $key</div>";
            } catch (Exception $e) {
                echo "<div class='error'>❌ Failed to fix $key: " . $e->getMessage() . "</div>";
            }
        }
    } else {
        echo "<div class='success'>✅ All configurations are present</div>";
    }
    echo "</div>";
    
    // Step 6: Final verification
    echo "<div class='step'>";
    echo "<h3>Step 6: Final Verification</h3>";
    
    // Check if all critical settings are now enabled
    $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') {
        echo "<div class='success' style='font-size: 18px;'>";
        echo "🎉 <strong>BANK TRANSACTION SMS NOTIFICATIONS ARE NOW ENABLED!</strong>";
        echo "</div>";
        echo "<p>You should now receive SMS notifications when verifying bank transactions.</p>";
    } else {
        echo "<div class='error'>❌ Bank transaction notifications are still disabled</div>";
    }
    
    // Show current status
    echo "<h4>Current Status Summary:</h4>";
    echo "<ul>";
    echo "<li>SMS Service: " . (isset($required_settings['sms_enabled']) ? '✅' : '❌') . "</li>";
    echo "<li>Bank Transaction Notifications: " . (isset($required_settings['sms_send_bank_transaction_notifications']) ? '✅' : '❌') . "</li>";
    echo "<li>Student Phone Numbers: " . ($phone_stats['students_with_phone'] > 0 ? '✅' : '❌') . "</li>";
    echo "<li>SMS Templates: " . (count($templates) > 0 ? '✅' : '❌') . "</li>";
    echo "</ul>";
    echo "</div>";
    
    echo "<div class='info'>";
    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>If still not working, check server error logs</li>";
    echo "</ol>";
    echo "</div>";
    
    echo "<div class='warning'>";
    echo "<h3>⚠️ Common Issues & Solutions:</h3>";
    echo "<ul>";
    echo "<li><strong>No phone numbers:</strong> Add phone numbers to student records</li>";
    echo "<li><strong>MRAM credentials:</strong> Verify API key and username are correct</li>";
    echo "<li><strong>Network issues:</strong> Check server connectivity to MRAM API</li>";
    echo "<li><strong>Balance issues:</strong> Ensure MRAM account has sufficient balance</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 "<p><strong>File:</strong> " . $e->getFile() . "</p>";
    echo "<p><strong>Line:</strong> " . $e->getLine() . "</p>";
    echo "</div>";
    
    echo "<div class='info'>";
    echo "<h4>Troubleshooting:</h4>";
    echo "<p>Please check:</p>";
    echo "<ul>";
    echo "<li>If MySQL server is running</li>";
    echo "<li>Database credentials in config/database.php</li>";
    echo "<li>If 'school_management' database exists</li>";
    echo "<li>PHP error logs for detailed information</li>";
    echo "</ul>";
    echo "</div>";
}

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