<?php
/**
 * Robust Bank Transaction SMS Fix
 * Handles database connection errors gracefully
 */

// Start output buffering to catch any errors
ob_start();

echo "<!DOCTYPE html>
<html>
<head>
    <title>Bank Transaction SMS 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; }
        table { border-collapse: collapse; width: 100%; margin: 10px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h2>🔧 Bank Transaction SMS Notification Fix</h2>
    <p>Fixing SMS notifications for bank transaction verification</p>";

try {
    // Try to include database configuration
    $db_file = __DIR__ . '/config/database.php';
    
    if (!file_exists($db_file)) {
        throw new Exception("Database configuration file not found at: $db_file");
    }
    
    // Include database configuration
    require_once $db_file;
    
    echo "<div class='info'>✅ Database connection established successfully</div>";
    
    // Check if PDO is available
    if (!isset($pdo) || !($pdo instanceof PDO)) {
        throw new Exception("PDO connection not available");
    }
    
    // Test database connection
    $pdo->query("SELECT 1");
    echo "<div class='success'>✅ Database connection test successful</div>";
    
    // 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 = [];
    $settings_status = [];
    
    foreach ($settings_to_check as $key => $description) {
        try {
            $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';
            $settings_status[$key] = $status;
            
            echo "<p><strong>$description:</strong> $status (Value: $value)</p>";
            
            if (!$result || $result['setting_value'] !== '1') {
                $missing_settings[$key] = '1';
            }
        } catch (Exception $e) {
            echo "<p><strong>$description:</strong> ❌ ERROR - " . $e->getMessage() . "</p>";
            $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) {
        try {
            $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';
            $settings_status[$key] = $status;
            
            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.';
            }
        } catch (Exception $e) {
            echo "<p><strong>$description:</strong> ❌ ERROR - " . $e->getMessage() . "</p>";
            $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 "<div class='success'>✅ Set $key = $value</div>";
            } catch (Exception $e) {
                echo "<div class='error'>❌ Failed to set $key: " . $e->getMessage() . "</div>";
            }
        }
    }
    
    // Verify the fix worked
    echo "<h3>✅ Verification After Fix:</h3>";
    
    try {
        $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;'>🎉 SUCCESS: Bank transaction notifications are now ENABLED!</div>";
            echo "<p>The bank transaction verification page should now send SMS notifications.</p>";
        } else {
            echo "<div class='error'>❌ FAILED: Could not enable bank transaction notifications</div>";
        }
    } catch (Exception $e) {
        echo "<div class='error'>❌ Verification failed: " . $e->getMessage() . "</div>";
    }
    
    // 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 "<div class='success'>✅ SMS helper file found</div>";
        try {
            require_once $smsHelperPath;
            echo "<div class='success'>✅ SMS helper loaded successfully</div>";
        } catch (Exception $e) {
            echo "<div class='error'>❌ Failed to load SMS helper: " . $e->getMessage() . "</div>";
        }
    } else {
        echo "<div class='error'>❌ SMS helper file not found at: $smsHelperPath</div>";
    }
    
    // Show database connection status
    echo "<h3>📊 Database Connection Status:</h3>";
    echo "<div class='info'>";
    echo "<p><strong>Host:</strong> localhost</p>";
    echo "<p><strong>Database:</strong> school_management</p>";
    echo "<p><strong>Connection:</strong> ✅ Successful</p>";
    echo "</div>";
    
    // Show all current settings
    echo "<h3>📡 All SMS Settings:</h3>";
    try {
        $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();
        
        if ($all_settings) {
            echo "<table>";
            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 || strpos($key, 'api_key') !== false) {
                    $value = '***HIDDEN***';
                }
                echo "<tr><td>$key</td><td>" . htmlspecialchars($value) . "</td><td>$status</td></tr>";
            }
            echo "</table>";
        } else {
            echo "<p>No SMS settings found in database</p>";
        }
    } catch (Exception $e) {
        echo "<div class='error'>❌ Could not retrieve settings: " . $e->getMessage() . "</div>";
    }
    
    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>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 class='warning'>";
    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>";
    
    echo "<div class='success'>";
    echo "<h4>✅ Fix Process Completed</h4>";
    echo "<p>Bank transaction SMS notifications should now work when transactions are verified.</p>";
    echo "<p>If you still experience issues, please check the error logs or contact system administrator.</p>";
    echo "</div>";
    
} catch (Exception $e) {
    echo "<div class='error'>";
    echo "<h3>❌ Error Occurred</h3>";
    echo "<p><strong>Error Message:</strong> " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p><strong>File:</strong> " . $e->getFile() . "</p>";
    echo "<p><strong>Line:</strong> " . $e->getLine() . "</p>";
    echo "</div>";
    
    echo "<div class='warning'>";
    echo "<h4>🔧 Troubleshooting Steps:</h4>";
    echo "<ol>";
    echo "<li>Check if MySQL server is running</li>";
    echo "<li>Verify database credentials in config/database.php</li>";
    echo "<li>Check if 'school_management' database exists</li>";
    echo "<li>Ensure 'settings' table exists in the database</li>";
    echo "<li>Check file permissions for the script</li>";
    echo "</ol>";
    echo "</div>";
}

// Flush output buffer
ob_end_flush();

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