<?php
/**
 * Bank Transaction SMS Notification Fix
 * Specifically fixes SMS notifications for bank transaction verification
 */

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

echo "<h2>🔧 Bank Transaction SMS Notification Fix</h2>";
echo "<p>Fixing SMS notifications for bank transaction verification at verify_bank_transactions.php</p>";

try {
    // Check current SMS settings
    echo "<h3>🔍 Current SMS Settings Check:</h3>";
    
    $settings_to_check = [
        'sms_enabled' => 'General SMS Enabled',
        'non_musking_enabled' => 'Non-Musking SMS Service',
        'sms_send_bank_transaction_notifications' => 'Bank Transaction Notifications',
        'sms_send_to_guardian' => 'Send to Guardian',
        'sms_send_fee_notifications' => 'Fee Notifications'
    ];
    
    $missing_settings = [];
    
    foreach ($settings_to_check 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';
        $status = ($result && $result['setting_value'] === '1') ? '✅ ENABLED' : '❌ DISABLED';
        
        echo "<p><strong>$description:</strong> $status (Value: $value)</p>";
        
        if (!$result || $result['setting_value'] !== '1') {
            $missing_settings[$key] = '1';
        }
    }
    
    // Check SMS templates
    echo "<h3>📝 SMS Template Check:</h3>";
    
    $templates_to_check = [
        'sms_send_bank_transaction_templates_bank_transaction' => 'Bank Transaction Template',
        'sms_send_bank_transaction_templates_bank_transaction_rejection' => 'Bank Transaction Rejection Template'
    ];
    
    foreach ($templates_to_check as $key => $description) {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        
        $status = $result ? '✅ EXISTS' : '❌ MISSING';
        $value = $result ? substr($result['setting_value'], 0, 50) . '...' : 'NOT SET';
        
        echo "<p><strong>$description:</strong> $status</p>";
        if (!$result) {
            $missing_settings[$key] = 'Your bank transaction has been verified. Amount: {amount} BDT. Current due: {due_amount} BDT. Thank you.';
        }
    }
    
    // If there are missing settings, fix them
    if (!empty($missing_settings)) {
        echo "<h3>🔨 Fixing Missing Settings:</h3>";
        
        foreach ($missing_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 "<p>✅ Set $key = $value</p>";
            } catch (Exception $e) {
                echo "<p>❌ Failed to set $key: " . $e->getMessage() . "</p>";
            }
        }
    }
    
    // Verify the fix worked
    echo "<h3>✅ Verification After Fix:</h3>";
    
    // Check if bank transaction notifications are 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 "<p style='color: green; font-size: 18px;'>🎉 SUCCESS: Bank transaction notifications are now ENABLED!</p>";
        echo "<p>The bank transaction verification page should now send SMS notifications.</p>";
    } else {
        echo "<p style='color: red;'>❌ FAILED: Could not enable bank transaction notifications</p>";
    }
    
    // Test the SMS configuration
    echo "<h3>📱 SMS Configuration Test:</h3>";
    
    // Test if we can include the SMS helper
    $smsHelperPath = __DIR__ . '/../includes/sms_helper.php';
    if (file_exists($smsHelperPath)) {
        echo "<p>✅ SMS helper file found</p>";
        try {
            require_once $smsHelperPath;
            echo "<p>✅ SMS helper loaded successfully</p>";
        } catch (Exception $e) {
            echo "<p>❌ Failed to load SMS helper: " . $e->getMessage() . "</p>";
        }
    } else {
        echo "<p>❌ SMS helper file not found at: $smsHelperPath</p>";
    }
    
    // Check database connection for SMS settings
    echo "<h3>📡 Database SMS Settings:</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>Setting Value</th><th>Status</th></tr>";
    foreach ($all_settings as $setting) {
        $key = $setting['setting_key'];
        $value = $setting['setting_value'];
        $status = ($value === '1' || $value === 'true') ? '✅' : '⚪';
        if (strpos($key, 'password') !== false) {
            $value = '***HIDDEN***';
        }
        echo "<tr><td>$key</td><td>$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>Verify a transaction</li>";
    echo "<li>Check if SMS notification is sent to the student's phone</li>";
    echo "<li>If not working, check server error logs for detailed information</li>";
    echo "</ol>";
    
    echo "<div style='background: #fff3cd; padding: 15px; border: 1px solid #ffeaa7; border-radius: 5px; margin-top: 20px;'>";
    echo "<h4>⚠️ Troubleshooting:</h4>";
    echo "<p>If SMS still not working:</p>";
    echo "<ul>";
    echo "<li>Check if student has phone number in database</li>";
    echo "<li>Verify MRAM API credentials are correct</li>";
    echo "<li>Check server error logs for detailed errors</li>";
    echo "<li>Test general SMS functionality with other features</li>";
    echo "</ul>";
    echo "</div>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error: " . $e->getMessage() . "</p>";
}

echo "<p><strong>Process completed. Bank transaction SMS notifications should now work when transactions are verified.</strong></p>";
?>