<?php
// Enable Bank Transaction SMS Notifications
header('Content-Type: text/html; charset=utf-8');

echo "<h2>Enabling Bank Transaction SMS Notifications</h2>\n";
echo "<p>This script will ensure all required settings for bank transaction SMS notifications are properly configured.</p>\n";

// Database configuration (same as in config/database.php)
$host = 'localhost';
$dbname = 'school_management';
$username = 'root';
$password = 'root';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    echo "<p>✅ Successfully connected to database: {$dbname}</p>\n";
    
    // Check if settings table exists, create if it doesn't
    $stmt = $pdo->prepare("SHOW TABLES LIKE 'settings'");
    $stmt->execute();
    $tableExists = $stmt->fetch();
    
    if (!$tableExists) {
        echo "<p>⚠️ Settings table does not exist, creating it...</p>\n";
        
        $pdo->exec("
            CREATE TABLE 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>✅ Settings table created successfully</p>\n";
    } else {
        echo "<p>✅ Settings table exists</p>\n";
    }
    
    // Required settings for bank transaction SMS
    $required_settings = [
        // Core SMS service settings
        ['non_musking_enabled', '1', 'Enable non-musking SMS service'],
        ['non_musking_api_key', 'C30027916974e980709412.23354057', 'MRAM API Key'],
        ['non_musking_api_url', 'https://rest.mrmessaging.net/messages', 'MRAM API URL'],
        ['non_musking_sender_id', '8809601016579', 'MRAM Sender ID'],
        ['non_musking_method', 'sms', 'SMS Method'],
        
        // Bank transaction specific settings
        ['sms_send_bank_transaction_notifications', '1', 'Enable bank transaction notifications'],
        
        // Template settings for bank transaction notifications
        ['sms_send_bank_transaction_templates_bank_transaction', 'ব্যাংক ট্রানজেকশন পেমেন্ট রিসিভড {paid_amount} টাকা। বকেয়া: {due_amount} টাকা।', 'Bank transaction confirmation template'],
        ['sms_send_bank_transaction_templates_bank_transaction_rejection', 'ব্যাংক ট্রানজেকশন প্রত্যাখ্যান করা হয়েছে। পরিমাণ: {amount} টাকা। কারণ: {notes}', 'Bank transaction rejection template']
    ];
    
    echo "<h3>Configuring Required Settings:</h3>\n";
    echo "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse;'>\n";
    echo "<tr style='background-color: #f2f2f2;'><th>Setting Key</th><th>Description</th><th>Status</th></tr>\n";
    
    $configured_count = 0;
    foreach ($required_settings as $setting_data) {
        $key = $setting_data[0];
        $value = $setting_data[1];
        $description = $setting_data[2];
        
        // Check if setting exists
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $existing = $stmt->fetch();
        
        if ($existing) {
            // Update existing setting
            $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
            $stmt->execute([$value, $key]);
            $status = "🔄 Updated";
        } else {
            // Insert new setting
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)");
            $stmt->execute([$key, $value]);
            $status = "✅ Added";
        }
        
        echo "<tr><td>{$key}</td><td>{$description}</td><td>{$status}</td></tr>\n";
        $configured_count++;
    }
    
    echo "</table>\n";
    echo "<p><strong>✅ {$configured_count} settings configured successfully!</strong></p>\n";
    
    // Verification: Check if the critical setting is properly enabled
    echo "<h3>Verification:</h3>\n";
    
    $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>✅ <strong>Critical Setting Verified:</strong> Bank transaction notifications are ENABLED</p>\n";
    } else {
        echo "<p>❌ <strong>Critical Setting Error:</strong> Bank transaction notifications are NOT enabled</p>\n";
    }
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
    $stmt->execute();
    $result = $stmt->fetch();
    
    if ($result && $result['setting_value'] === '1') {
        echo "<p>✅ <strong>Critical Setting Verified:</strong> Non-musking SMS service is ENABLED</p>\n";
    } else {
        echo "<p>⚠️ <strong>Critical Setting Warning:</strong> Non-musking SMS service is NOT enabled</p>\n";
    }
    
    // Show all bank-related settings
    echo "<h3>All Bank Transaction Related Settings:</h3>\n";
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE '%bank%' OR setting_key LIKE '%sms%' ORDER BY setting_key");
    $stmt->execute();
    $results = $stmt->fetchAll();
    
    echo "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse;'>\n";
    echo "<tr style='background-color: #f2f2f2;'><th>Setting Key</th><th>Setting Value</th></tr>\n";
    
    foreach ($results as $row) {
        $key = htmlspecialchars($row['setting_key']);
        $value = htmlspecialchars($row['setting_value']);
        echo "<tr><td>{$key}</td><td>{$value}</td></tr>\n";
    }
    
    echo "</table>\n";
    
    echo "<h3>Conclusion:</h3>\n";
    echo "<p><strong>✅ Bank transaction SMS notifications have been properly configured!</strong></p>\n";
    echo "<p>When a bank transaction is verified in <code>fees/verify_bank_transactions.php</code>, SMS notifications will now be sent to students' phones.</p>\n";
    echo "<p>The system will send:</p>\n";
    echo "<ul>\n";
    echo "    <li>Confirmation SMS when a bank transaction is APPROVED</li>\n";
    echo "    <li>Rejection SMS when a bank transaction is REJECTED</li>\n";
    echo "</ul>\n";
    echo "</p>\n";

} catch (PDOException $e) {
    echo "<p>❌ Database connection error: " . htmlspecialchars($e->getMessage()) . "</p>\n";
    echo "<p>Please make sure:</p>\n";
    echo "<ol>\n";
    echo "    <li>MAMP/WAMP/XAMPP is running</li>\n";
    echo "    <li>MySQL server is started</li>\n";
    echo "    <li>Database 'school_management' exists</li>\n";
    echo "    <li>Correct credentials are used (root/root)</li>\n";
    echo "</ol>\n";
    echo "</p>\n";
}
?>