<?php
/**
 * Fix SMS notification issues for bank transactions
 * This script will ensure all required settings are properly configured
 */

require_once 'config/database.php';

echo "<!DOCTYPE html>
<html>
<head>
    <title>Fix SMS Notifications</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
    </style>
</head>
<body>";

echo "<h1>🔧 Fixing SMS Notification Issues</h1>";

try {
    // Ensure settings table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        id INT PRIMARY KEY AUTO_INCREMENT,
        setting_key VARCHAR(100) UNIQUE,
        setting_value TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
    
    echo "<p class='info'>✅ Settings table checked/created</p>";
    
    // Required settings with their default values
    $required_settings = [
        // Core SMS settings
        'non_musking_enabled' => '1',
        'sms_send_bank_transaction_notifications' => '1',
        
        // MRAM API configuration
        'non_musking_api_key' => 'YOUR_MRAM_API_KEY_HERE',
        'non_musking_api_url' => 'https://esms.mram.com.bd/smsapi',
        'non_musking_sender_id' => 'SCHOOL',
        
        // SMS Templates - using the keys that SmsNotificationSystem expects
        'sms_tpl_bank_transaction' => 'Dear {name}, your bank transaction of ৳{paid_amount} has been successfully verified. Your current due is ৳{due_amount}. Thank you.',
        'sms_tpl_bank_transaction_rejection' => 'Dear {name}, your bank transaction of ৳{amount} with ID {transaction_id} has been rejected. Reason: {notes}. Please contact administration.',
        
        // Alternative template keys (backup)
        'non_musking_tpl_bank_transaction' => 'Dear {name}, your bank transaction of ৳{paid_amount} has been successfully verified. Your current due is ৳{due_amount}. Thank you.',
        'non_musking_tpl_bank_transaction_rejection' => 'Dear {name}, your bank transaction of ৳{amount} with ID {transaction_id} has been rejected. Reason: {notes}. Please contact administration.'
    ];
    
    echo "<h3>📝 Configuring Required Settings</h3>";
    
    $stmt = $pdo->prepare("
        INSERT INTO settings (setting_key, setting_value) 
        VALUES (?, ?) 
        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
    ");
    
    $configured_count = 0;
    foreach ($required_settings as $key => $value) {
        $stmt->execute([$key, $value]);
        echo "<p class='success'>✅ Configured: $key</p>";
        $configured_count++;
    }
    
    echo "<p class='info'>Total settings configured: $configured_count</p>";
    
    // Verify the configuration
    echo "<h3>🔍 Verification</h3>";
    
    $verification_checks = [
        'non_musking_enabled' => 'Non-Musking SMS Service',
        'sms_send_bank_transaction_notifications' => 'Bank Transaction Notifications',
        'sms_tpl_bank_transaction' => 'Bank Transaction Template',
        'sms_tpl_bank_transaction_rejection' => 'Bank Transaction Rejection Template'
    ];
    
    $all_verified = true;
    
    foreach ($verification_checks 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'])) {
            echo "<p class='success'>✅ $description is properly configured</p>";
        } else {
            echo "<p class='error'>❌ $description is missing or empty</p>";
            $all_verified = false;
        }
    }
    
    // Final status
    echo "<h3>📊 Final Status</h3>";
    
    if ($all_verified) {
        echo "<div class='success'>";
        echo "<h4>🎉 SUCCESS! SMS Notifications Are Now Configured</h4>";
        echo "<p>All required settings have been properly configured.</p>";
        echo "<p>You can now verify bank transactions and SMS notifications will be sent automatically.</p>";
        echo "<p><strong>Test URL:</strong> <a href='/bidda/fees/verify_bank_transactions.php'>http://localhost/bidda/fees/verify_bank_transactions.php</a></p>";
        echo "</div>";
        
        echo "<h4>📋 Next Steps:</h4>";
        echo "<ol>";
        echo "<li>Go to the bank transaction verification page</li>";
        echo "<li>Select a pending transaction</li>";
        echo "<li>Click 'Verify Payment'</li>";
        echo "<li>Check if SMS is sent to the student's phone</li>";
        echo "</ol>";
        
        echo "<h4>📱 Troubleshooting:</h4>";
        echo "<p>If SMS still doesn't send:</p>";
        echo "<ul>";
        echo "<li>Check that the student has a valid phone number in their profile</li>";
        echo "<li>Verify MRAM API credentials are correct</li>";
        echo "<li>Check server error logs for detailed error messages</li>";
        echo "<li>Run the diagnosis tool: <a href='/bidda/diagnose_sms_issues.php'>diagnose_sms_issues.php</a></li>";
        echo "</ul>";
    } else {
        echo "<div class='error'>";
        echo "<h4>❌ Some Issues Remain</h4>";
        echo "<p>Not all settings were properly configured. Please check the errors above.</p>";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<div class='error'>";
    echo "<h3>❌ ERROR OCCURRED</h3>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "</div>";
}

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