<?php
/**
 * Diagnose SMS notification issues for bank transactions
 * Access via: http://localhost/bidda/diagnose_sms_issues.php
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<!DOCTYPE html>
<html>
<head>
    <title>SMS Notification Diagnosis</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .success { color: green; }
        .error { color: red; }
        .warning { color: orange; }
        pre { background: #f5f5f5; padding: 10px; }
    </style>
</head>
<body>";

echo "<h1>🔍 SMS Notification Diagnosis Tool</h1>";

try {
    // Include database connection
    require_once 'config/database.php';
    
    echo "<h2>✅ Database Connection Successful</h2>";
    
    // Check all required settings
    $required_settings = [
        'non_musking_enabled' => 'Non-Musking SMS Service',
        'sms_send_bank_transaction_notifications' => 'Bank Transaction Notifications',
        'non_musking_api_key' => 'MRAM API Key',
        'non_musking_api_url' => 'MRAM API URL',
        'non_musking_sender_id' => 'Sender ID',
        'non_musking_tpl_bank_transaction' => 'Bank Transaction Template',
        'non_musking_tpl_bank_transaction_rejection' => 'Bank Transaction Rejection Template'
    ];
    
    echo "<h3>📋 Required Settings Check</h3>";
    echo "<table border='1' cellpadding='8' cellspacing='0'>";
    echo "<tr><th>Setting</th><th>Status</th><th>Value</th></tr>";
    
    $all_settings_ok = true;
    
    foreach ($required_settings as $key => $description) {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        
        if ($result) {
            $value = $result['setting_value'];
            $is_set = !empty($value);
            
            if ($key === 'non_musking_api_key' && $is_set) {
                $display_value = substr($value, 0, 5) . '...' . substr($value, -3);
            } else {
                $display_value = $value;
            }
            
            if ($is_set) {
                echo "<tr><td>$description</td><td class='success'>✅ SET</td><td>" . htmlspecialchars($display_value) . "</td></tr>";
            } else {
                echo "<tr><td>$description</td><td class='warning'>⚠️ EMPTY</td><td>" . htmlspecialchars($value) . "</td></tr>";
                $all_settings_ok = false;
            }
        } else {
            echo "<tr><td>$description</td><td class='error'>❌ MISSING</td><td>NOT FOUND</td></tr>";
            $all_settings_ok = false;
        }
    }
    
    echo "</table>";
    
    // Check if SMS can be sent
    echo "<h3>📡 SMS Sending Capability</h3>";
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
    $stmt->execute();
    $result = $stmt->fetch();
    $sms_enabled = $result && $result['setting_value'] === '1';
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_bank_transaction_notifications'");
    $stmt->execute();
    $result = $stmt->fetch();
    $bank_notifications_enabled = $result && $result['setting_value'] === '1';
    
    if ($sms_enabled && $bank_notifications_enabled) {
        echo "<p class='success'>✅ Both SMS service and bank notifications are enabled</p>";
    } else {
        echo "<p class='error'>❌ Required services are not enabled:</p>";
        if (!$sms_enabled) {
            echo "<p>- Non-musking SMS service is disabled</p>";
        }
        if (!$bank_notifications_enabled) {
            echo "<p>- Bank transaction notifications are disabled</p>";
        }
        $all_settings_ok = false;
    }
    
    // Test recent transactions
    echo "<h3>💳 Recent Bank Transactions</h3>";
    
    $stmt = $pdo->prepare("
        SELECT bt.*, s.phone, s.first_name, s.last_name 
        FROM bank_transactions bt 
        JOIN students s ON bt.student_id = s.id 
        WHERE bt.status IN ('pending', 'verified', 'rejected')
        ORDER BY bt.submitted_at DESC 
        LIMIT 5
    ");
    $stmt->execute();
    $transactions = $stmt->fetchAll();
    
    if ($transactions) {
        echo "<table border='1' cellpadding='8' cellspacing='0'>";
        echo "<tr><th>ID</th><th>Transaction ID</th><th>Amount</th><th>Status</th><th>Student</th><th>Phone</th><th>Can Send SMS?</th></tr>";
        
        foreach ($transactions as $tx) {
            $can_send_sms = !empty($tx['phone']) && $sms_enabled && $bank_notifications_enabled;
            $sms_status = $can_send_sms ? '<span class="success">✅ YES</span>' : '<span class="error">❌ NO</span>';
            
            echo "<tr>";
            echo "<td>{$tx['id']}</td>";
            echo "<td>{$tx['transaction_id']}</td>";
            echo "<td>৳" . number_format($tx['amount'], 2) . "</td>";
            echo "<td>{$tx['status']}</td>";
            echo "<td>{$tx['first_name']} {$tx['last_name']}</td>";
            echo "<td>" . (!empty($tx['phone']) ? htmlspecialchars($tx['phone']) : '<span class="error">MISSING</span>') . "</td>";
            echo "<td>$sms_status</td>";
            echo "</tr>";
        }
        
        echo "</table>";
    } else {
        echo "<p>No recent bank transactions found.</p>";
    }
    
    // Overall diagnosis
    echo "<h3>📊 Overall Diagnosis</h3>";
    
    if ($all_settings_ok && $sms_enabled && $bank_notifications_enabled) {
        echo "<div class='success'>";
        echo "<h4>✅ SYSTEM IS READY FOR SMS NOTIFICATIONS</h4>";
        echo "<p>All required settings are properly configured.</p>";
        echo "<p>SMS notifications should be working when you verify bank transactions at:</p>";
        echo "<p><a href='/bidda/fees/verify_bank_transactions.php' target='_blank'>http://localhost/bidda/fees/verify_bank_transactions.php</a></p>";
        echo "</div>";
    } else {
        echo "<div class='error'>";
        echo "<h4>❌ ISSUES DETECTED</h4>";
        echo "<p>The following issues need to be resolved:</p>";
        echo "<ul>";
        
        if (!$sms_enabled) {
            echo "<li>Enable non-musking SMS service in admin settings</li>";
        }
        if (!$bank_notifications_enabled) {
            echo "<li>Enable bank transaction notifications in admin settings</li>";
        }
        
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_api_key'");
        $stmt->execute();
        $result = $stmt->fetch();
        if (!$result || empty($result['setting_value'])) {
            echo "<li>Configure MRAM API key</li>";
        }
        
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_api_url'");
        $stmt->execute();
        $result = $stmt->fetch();
        if (!$result || empty($result['setting_value'])) {
            echo "<li>Configure MRAM API URL</li>";
        }
        
        echo "</ul>";
        echo "<p>Go to Admin Panel → SMS Settings to configure these items.</p>";
        echo "</div>";
    }
    
    // Debug information
    echo "<h3>🔧 Debug Information</h3>";
    echo "<details>";
    echo "<summary>Click to view detailed debug info</summary>";
    echo "<pre>";
    echo "PHP Version: " . phpversion() . "\n";
    echo "Current Time: " . date('Y-m-d H:i:s') . "\n";
    echo "Script Path: " . __FILE__ . "\n";
    echo "Database Host: " . $host . "\n";
    echo "Database Name: " . $dbname . "\n";
    echo "</pre>";
    echo "</details>";
    
} catch (Exception $e) {
    echo "<div class='error'>";
    echo "<h3>❌ ERROR OCCURRED</h3>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "</div>";
}

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