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

session_start();

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: auth-login.php');
    exit();
}

// Include database connection
require_once 'layouts/dbconn.php';

// Check if database connection exists
if (!isset($conn)) {
    die('Database connection not available');
}

// Get user information
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'Customer';

// Simple functions for payment gateways page
function getPaymentGatewayPluginsSimple($conn) {
    $query = "
        SELECT 
            p.product_id,
            p.name,
            p.description,
            p.logo_url as provider_logo,
            p.developer as provider_name,
            p.rating_average,
            p.rating_count,
            p.download_count,
            p.features,
            p.supported_currencies,
            COALESCE(pp.price, 99) as price,
            p.created_at,
            p.updated_at,
            CASE WHEN p.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END as is_new,
            p.is_featured as is_recommended
        FROM products p
        LEFT JOIN product_pricing pp ON p.product_id = pp.product_id AND pp.tier_name = 'Basic'
        LEFT JOIN product_categories pc ON p.category_id = pc.category_id
        WHERE (pc.slug = 'payment-gateways' OR pc.name LIKE '%payment%' OR pc.name LIKE '%gateway%') 
        AND p.is_active = 1
        ORDER BY p.download_count DESC, p.rating_average DESC
        LIMIT 20
    ";
    
    try {
        $result = $conn->query($query);
        $gateways = [];
        
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $gateways[] = $row;
            }
        }
        
        // If no gateways found in database, return sample data
        if (empty($gateways)) {
            return getSamplePaymentGateways();
        }
        
        return $gateways;
        
    } catch (Exception $e) {
        error_log("Error fetching payment gateways: " . $e->getMessage());
        return getSamplePaymentGateways();
    }
}

function getSamplePaymentGateways() {
    return [
        [
            'product_id' => 1,
            'name' => 'South Sudan MoMo Gateway',
            'description' => 'Complete mobile money payment gateway supporting MTN Mobile Money, m-GURUSH, and Nilepay for seamless WordPress e-commerce integration.',
            'provider_logo' => 'assets/images/providers/south-sudan-momo.png',
            'provider_name' => 'ConnectPay Solutions',
            'rating_average' => 4.8,
            'rating_count' => 156,
            'download_count' => 2340,
            'features' => '["Real-time transaction processing", "Multi-provider support", "Automatic order completion", "Comprehensive logging", "Mobile responsive checkout", "Webhook notifications"]',
            'supported_currencies' => '["SSP", "USD"]',
            'price' => 149,
            'created_at' => date('Y-m-d H:i:s', strtotime('-30 days')),
            'updated_at' => date('Y-m-d H:i:s', strtotime('-5 days')),
            'is_new' => 0,
            'is_recommended' => 1
        ],
        [
            'product_id' => 2,
            'name' => 'MTN Mobile Money Pro',
            'description' => 'Advanced MTN Mobile Money integration with real-time transaction status, automated reconciliation, and comprehensive reporting features.',
            'provider_logo' => 'assets/images/providers/mtn-logo.png',
            'provider_name' => 'MTN South Sudan',
            'rating_average' => 4.9,
            'rating_count' => 89,
            'download_count' => 1580,
            'features' => '["MTN API integration", "Real-time status updates", "Automated reconciliation", "Transaction reports", "Failed payment retry", "Customer notifications"]',
            'supported_currencies' => '["SSP", "USD"]',
            'price' => 199,
            'created_at' => date('Y-m-d H:i:s', strtotime('-45 days')),
            'updated_at' => date('Y-m-d H:i:s', strtotime('-10 days')),
            'is_new' => 0,
            'is_recommended' => 1
        ],
        [
            'product_id' => 3,
            'name' => 'Nilepay WooCommerce',
            'description' => 'Professional Nilepay integration for WooCommerce with multi-currency support, subscription billing, and advanced fraud protection.',
            'provider_logo' => 'assets/images/providers/nilepay-logo.png',
            'provider_name' => 'Nilepay',
            'rating_average' => 4.7,
            'rating_count' => 124,
            'download_count' => 980,
            'features' => '["Nilepay API integration", "Multi-currency support", "Subscription billing", "Fraud protection", "Instant notifications", "Refund management"]',
            'supported_currencies' => '["SSP", "USD", "EUR"]',
            'price' => 179,
            'created_at' => date('Y-m-d H:i:s', strtotime('-20 days')),
            'updated_at' => date('Y-m-d H:i:s', strtotime('-3 days')),
            'is_new' => 1,
            'is_recommended' => 0
        ],
        [
            'product_id' => 4,
            'name' => 'm-GURUSH Gateway',
            'description' => 'Complete m-GURUSH payment solution with instant notifications, automatic order completion, and detailed transaction logging.',
            'provider_logo' => 'assets/images/providers/mgurush-logo.png',
            'provider_name' => 'Zain South Sudan',
            'rating_average' => 4.6,
            'rating_count' => 67,
            'download_count' => 756,
            'features' => '["m-GURUSH API integration", "Instant notifications", "Order completion", "Transaction logging", "Payment verification", "Customer receipts"]',
            'supported_currencies' => '["SSP"]',
            'price' => 129,
            'created_at' => date('Y-m-d H:i:s', strtotime('-60 days')),
            'updated_at' => date('Y-m-d H:i:s', strtotime('-7 days')),
            'is_new' => 0,
            'is_recommended' => 0
        ],
        [
            'product_id' => 5,
            'name' => 'Universal MoMo Adapter',
            'description' => 'Universal mobile money adapter supporting multiple providers with intelligent failover, load balancing, and unified reporting.',
            'provider_logo' => 'assets/images/providers/universal-momo.png',
            'provider_name' => 'ConnectPay Solutions',
            'rating_average' => 4.5,
            'rating_count' => 203,
            'download_count' => 3420,
            'features' => '["Multi-provider support", "Intelligent failover", "Load balancing", "Unified reporting", "Provider switching", "Performance monitoring"]',
            'supported_currencies' => '["SSP", "USD", "EUR"]',
            'price' => 299,
            'created_at' => date('Y-m-d H:i:s', strtotime('-90 days')),
            'updated_at' => date('Y-m-d H:i:s', strtotime('-1 day')),
            'is_new' => 0,
            'is_recommended' => 1
        ],
        [
            'product_id' => 6,
            'name' => 'Bank Transfer Gateway',
            'description' => 'Secure bank transfer integration for major South Sudanese banks with automated verification and reconciliation.',
            'provider_logo' => 'assets/images/providers/bank-transfer.png',
            'provider_name' => 'ConnectPay Solutions',
            'rating_average' => 4.3,
            'rating_count' => 45,
            'download_count' => 534,
            'features' => '["Bank API integration", "Automated verification", "Reconciliation tools", "Multi-bank support", "Transfer tracking", "Receipt generation"]',
            'supported_currencies' => '["SSP", "USD"]',
            'price' => 249,
            'created_at' => date('Y-m-d H:i:s', strtotime('-15 days')),
            'updated_at' => date('Y-m-d H:i:s', strtotime('-2 days')),
            'is_new' => 1,
            'is_recommended' => 0
        ]
    ];
}

function getGatewayCategoriesSimple() {
    return [
        ['name' => 'Mobile Money', 'slug' => 'mobile-money', 'count' => 4],
        ['name' => 'Bank Transfer', 'slug' => 'bank-transfer', 'count' => 1],
        ['name' => 'Digital Wallets', 'slug' => 'digital-wallets', 'count' => 1],
        ['name' => 'Multi-Provider', 'slug' => 'multi-provider', 'count' => 2],
    ];
}

function getPopularGatewaysSimple($gateways) {
    // Return gateways with high download counts or recommended status
    $popular = array_filter($gateways, function($gateway) {
        return $gateway['download_count'] > 1000 || $gateway['is_recommended'];
    });
    
    return array_slice($popular, 0, 3);
}

function timeAgoSimple($datetime) {
    $time = time() - strtotime($datetime);
    
    if ($time < 60) return 'just now';
    if ($time < 3600) return floor($time/60) . ' min ago';
    if ($time < 86400) return floor($time/3600) . ' hr ago';
    if ($time < 2592000) return floor($time/86400) . ' days ago';
    if ($time < 31536000) return floor($time/2592000) . ' months ago';
    
    return floor($time/31536000) . ' years ago';
}

function getCategoryNameSimple($slug) {
    $categories = [
        'mobile-money' => 'Mobile Money',
        'bank-transfer' => 'Bank Transfer',
        'digital-wallets' => 'Digital Wallets',
        'multi-provider' => 'Multi-Provider'
    ];
    
    return $categories[$slug] ?? 'Payment Gateway';
}

// Get data
$payment_gateways = getPaymentGatewayPluginsSimple($conn);
$gateway_categories = getGatewayCategoriesSimple();
$popular_gateways = getPopularGatewaysSimple($payment_gateways);

// Filter by category if specified
$category_filter = $_GET['category'] ?? '';
if (!empty($category_filter)) {
    $payment_gateways = array_filter($payment_gateways, function($gateway) use ($category_filter) {
        // Simple filtering logic based on gateway name and description
        $search_terms = [
            'mobile-money' => ['mobile', 'momo', 'mtn', 'gurush', 'nilepay'],
            'bank-transfer' => ['bank', 'transfer'],
            'digital-wallets' => ['wallet', 'digital'],
            'multi-provider' => ['universal', 'multi', 'adapter']
        ];
        
        if (isset($search_terms[$category_filter])) {
            foreach ($search_terms[$category_filter] as $term) {
                if (stripos($gateway['name'] . ' ' . $gateway['description'], $term) !== false) {
                    return true;
                }
            }
        }
        return false;
    });
}

// Set title for the page
$title = "Payment Gateways";

// End output buffering and check for errors
$buffer = ob_get_clean();
if (!empty($buffer)) {
    error_log("Output buffer content: " . $buffer);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title><?php echo $title; ?> | ConnectPay Platform</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="ConnectPay Plugin Platform" name="description" />
    <meta content="ConnectPay" name="author" />
    
    <!-- App favicon -->
    <link rel="shortcut icon" href="assets/images/favicon.ico">
    
    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Icons CSS -->
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    
    <!-- App CSS -->
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />

<style>
    .gateway-card {
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        background: white;
        transition: all 0.2s ease;
        height: 100%;
        display: flex;
        flex-direction: column;
        position: relative;
        overflow: hidden;
    }
    
    .gateway-card:hover {
        border-color: #d1d5db;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
    }
    
    .gateway-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f3f4f6;
        background: #fafafa;
    }
    
    .provider-logo {
        width: 64px;
        height: 64px;
        border-radius: 8px;
        background: white;
        border: 1px solid #e5e7eb;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
    }
    
    .gateway-title {
        font-size: 1.25rem;
        font-weight: 600;
        color: #111827;
        margin: 0 0 0.25rem 0;
    }
    
    .gateway-provider {
        font-size: 0.875rem;
        color: #6b7280;
        margin: 0 0 0.5rem 0;
    }
    
    .gateway-content {
        padding: 1.5rem;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
    }
    
    .gateway-description {
        font-size: 0.875rem;
        color: #374151;
        line-height: 1.5;
        margin-bottom: 1.5rem;
        flex-grow: 1;
    }
    
    .features-list {
        list-style: none;
        padding: 0;
        margin: 0 0 1.5rem 0;
    }
    
    .features-list li {
        display: flex;
        align-items: center;
        font-size: 0.8125rem;
        color: #4b5563;
        margin-bottom: 0.5rem;
    }
    
    .features-list li:before {
        content: "✓";
        color: #10b981;
        font-weight: bold;
        margin-right: 0.5rem;
    }
    
    .gateway-footer {
        padding: 1.5rem;
        border-top: 1px solid #f3f4f6;
        background: #fafafa;
    }
    
    .price-section {
        margin-bottom: 1rem;
    }
    
    .gateway-price {
        font-size: 1.5rem;
        font-weight: 700;
        color: #111827;
        margin-bottom: 0.25rem;
    }
    
    .price-details {
        font-size: 0.75rem;
        color: #6b7280;
    }
    
    .btn-primary {
        background: #3b82f6;
        border: 1px solid #3b82f6;
        color: white;
        padding: 0.625rem 1.25rem;
        border-radius: 6px;
        font-size: 0.875rem;
        font-weight: 500;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 100%;
    }
    
    .btn-primary:hover {
        background: #2563eb;
        border-color: #2563eb;
        color: white;
        transform: translateY(-1px);
    }
    
    .btn-outline {
        background: white;
        border: 1px solid #d1d5db;
        color: #374151;
        padding: 0.625rem 1.25rem;
        border-radius: 6px;
        font-size: 0.875rem;
        font-weight: 500;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        margin-bottom: 0.5rem;
    }
    
    .btn-outline:hover {
        background: #f9fafb;
        border-color: #9ca3af;
        color: #374151;
    }
    
    .category-filter {
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        padding: 1.25rem;
        margin-bottom: 1.5rem;
    }
    
    .filter-tabs {
        display: flex;
        gap: 0.5rem;
        flex-wrap: wrap;
    }
    
    .filter-tab {
        padding: 0.5rem 1rem;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        background: white;
        color: #374151;
        text-decoration: none;
        font-size: 0.875rem;
        font-weight: 500;
        transition: all 0.2s ease;
    }
    
    .filter-tab:hover {
        background: #f9fafb;
        color: #374151;
    }
    
    .filter-tab.active {
        background: #3b82f6;
        border-color: #3b82f6;
        color: white;
    }
    
    .badge {
        display: inline-flex;
        align-items: center;
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
        font-size: 0.75rem;
        font-weight: 500;
        position: absolute;
        top: 1rem;
        right: 1rem;
    }
    
    .badge-popular {
        background: #dbeafe;
        color: #1e40af;
    }
    
    .badge-new {
        background: #dcfce7;
        color: #166534;
    }
    
    .badge-recommended {
        background: #fef3c7;
        color: #92400e;
    }
    
    .provider-stats {
        display: flex;
        gap: 1rem;
        margin-bottom: 1rem;
        font-size: 0.8125rem;
        color: #6b7280;
    }
    
    .stat-item {
        display: flex;
        align-items: center;
        gap: 0.25rem;
    }
    
    .section-header {
        margin-bottom: 1.5rem;
    }
    
    .section-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: #111827;
        margin: 0 0 0.5rem 0;
    }
    
    .section-subtitle {
        font-size: 0.875rem;
        color: #6b7280;
        margin: 0;
    }
    
    .hero-section {
        background: #f9fafb;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        padding: 2rem;
        margin-bottom: 2rem;
        text-align: center;
    }
    
    .hero-title {
        font-size: 1.875rem;
        font-weight: 700;
        color: #111827;
        margin-bottom: 0.75rem;
    }
    
    .hero-subtitle {
        font-size: 1rem;
        color: #6b7280;
        margin-bottom: 1.5rem;
        max-width: 600px;
        margin-left: auto;
        margin-right: auto;
    }
    
    .provider-count {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        background: white;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        padding: 0.5rem 1rem;
        font-size: 0.875rem;
        color: #374151;
        font-weight: 500;
    }
</style>
</head>

<body class="loading">

<!-- Begin page -->
<div id="wrapper">

    <!-- Topbar Start -->
    <?php 
    $pagetitle = "Payment Gateways"; 
    if (file_exists('partials/menu.php')) {
        include 'partials/menu.php'; 
    } else {
        // Simple fallback header
        echo '<div class="navbar-custom"><div class="container-fluid"><h4 class="page-title">Payment Gateways</h4></div></div>';
    }
    ?>
    <!-- end Topbar -->

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">

                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="<?php echo ($user_role === 'Customer') ? 'dashboard.php' : 'index.php'; ?>">Dashboard</a></li>
                                    <li class="breadcrumb-item">Plugin Store</li>
                                    <li class="breadcrumb-item active">Payment Gateways</li>
                                </ol>
                            </div>
                            <h4 class="page-title">Payment Gateways</h4>
                        </div>
                    </div>
                </div>

                <!-- Debug Info (remove in production) -->
                <?php if (isset($_GET['debug'])): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="alert alert-info">
                            <strong>Debug Info:</strong><br>
                            User ID: <?php echo $user_id; ?><br>
                            User Role: <?php echo $user_role; ?><br>
                            Total Gateways: <?php echo count($payment_gateways); ?><br>
                            Database Connection: <?php echo isset($conn) ? 'OK' : 'Failed'; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Hero Section -->
                <div class="row">
                    <div class="col-12">
                        <div class="hero-section">
                            <h2 class="hero-title">Mobile Money Payment Gateways</h2>
                            <p class="hero-subtitle">
                                Integrate popular mobile money providers in South Sudan with our WordPress plugins. 
                                Accept payments through MTN Mobile Money, m-GURUSH, Nilepay, and more.
                            </p>
                            <div class="provider-count">
                                <span>💳</span>
                                <span><?php echo count($payment_gateways); ?> Payment Providers Available</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Category Filters -->
                <div class="row">
                    <div class="col-12">
                        <div class="category-filter">
                            <label style="font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.75rem; display: block;">Filter by Provider Type</label>
                            <div class="filter-tabs">
                                <a href="?category=" class="filter-tab <?php echo empty($_GET['category']) ? 'active' : ''; ?>">All Providers</a>
                                <?php foreach ($gateway_categories as $category): ?>
                                <a href="?category=<?php echo $category['slug']; ?>" class="filter-tab <?php echo ($_GET['category'] ?? '') === $category['slug'] ? 'active' : ''; ?>">
                                    <?php echo htmlspecialchars($category['name']); ?>
                                    <span style="margin-left: 0.25rem; opacity: 0.7;">(<?php echo $category['count']; ?>)</span>
                                </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Popular Gateways Section -->
                <?php if (!empty($popular_gateways) && empty($_GET['category'])): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="section-header">
                            <h3 class="section-title">Popular Payment Gateways</h3>
                            <p class="section-subtitle">Most downloaded and highest-rated payment gateway plugins</p>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <?php foreach ($popular_gateways as $gateway): ?>
                    <div class="col-lg-4 col-md-6 mb-4">
                        <div class="gateway-card">
                            <span class="badge badge-popular">Popular</span>
                            
                            <div class="gateway-header">
                                <div class="d-flex align-items-center">
                                    <div class="provider-logo me-3">💳</div>
                                    <div class="flex-grow-1">
                                        <h4 class="gateway-title"><?php echo htmlspecialchars($gateway['name']); ?></h4>
                                        <p class="gateway-provider"><?php echo htmlspecialchars($gateway['provider_name']); ?></p>
                                        <div class="provider-stats">
                                            <div class="stat-item">
                                                <span>⭐</span>
                                                <span><?php echo number_format($gateway['rating_average'], 1); ?></span>
                                            </div>
                                            <div class="stat-item">
                                                <span>📥</span>
                                                <span><?php echo number_format($gateway['download_count']); ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="gateway-content">
                                <p class="gateway-description"><?php echo htmlspecialchars($gateway['description']); ?></p>
                                
                                <ul class="features-list">
                                    <?php 
                                    $features = json_decode($gateway['features'], true) ?: [];
                                    foreach (array_slice($features, 0, 4) as $feature): 
                                    ?>
                                    <li><?php echo htmlspecialchars($feature); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                            
                            <div class="gateway-footer">
                                <div class="price-section">
                                    <div class="gateway-price">$<?php echo number_format($gateway['price'], 0); ?></div>
                                    <div class="price-details">One-time purchase • Lifetime updates</div>
                                </div>
                                <a href="#" class="btn-outline">View Details</a>
                                <a href="#" class="btn-primary">Purchase Now</a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <!-- All Payment Gateways Section -->
                <div class="row">
                    <div class="col-12">
                        <div class="section-header">
                            <h3 class="section-title">
                                <?php if (!empty($_GET['category'])): ?>
                                <?php echo htmlspecialchars(getCategoryNameSimple($_GET['category'])); ?> Gateways
                                <?php else: ?>
                                All Payment Gateways
                                <?php endif; ?>
                            </h3>
                            <p class="section-subtitle">
                                <?php echo count($payment_gateways); ?> gateway(s) available
                                <?php if (!empty($_GET['category'])): ?>
                                - <a href="payment-gateways.php" style="color: #3b82f6;">View all gateways</a>
                                <?php endif; ?>
                            </p>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <?php if (!empty($payment_gateways)): ?>
                        <?php foreach ($payment_gateways as $gateway): ?>
                        <div class="col-lg-4 col-md-6 mb-4">
                            <div class="gateway-card">
                                <?php if ($gateway['is_new']): ?>
                                <span class="badge badge-new">New</span>
                                <?php elseif ($gateway['is_recommended']): ?>
                                <span class="badge badge-recommended">Recommended</span>
                                <?php endif; ?>
                                
                                <div class="gateway-header">
                                    <div class="d-flex align-items-center">
                                        <div class="provider-logo me-3">💳</div>
                                        <div class="flex-grow-1">
                                            <h4 class="gateway-title"><?php echo htmlspecialchars($gateway['name']); ?></h4>
                                            <p class="gateway-provider"><?php echo htmlspecialchars($gateway['provider_name']); ?></p>
                                            <div class="provider-stats">
                                                <div class="stat-item">
                                                    <span>⭐</span>
                                                    <span><?php echo number_format($gateway['rating_average'], 1); ?></span>
                                                </div>
                                                <div class="stat-item">
                                                    <span>📥</span>
                                                    <span><?php echo number_format($gateway['download_count']); ?></span>
                                                </div>
                                                <div class="stat-item">
                                                    <span>🔄</span>
                                                    <span>Updated <?php echo timeAgoSimple($gateway['updated_at']); ?></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="gateway-content">
                                    <p class="gateway-description"><?php echo htmlspecialchars($gateway['description']); ?></p>
                                    
                                    <ul class="features-list">
                                        <?php 
                                        $features = json_decode($gateway['features'], true) ?: [];
                                        foreach (array_slice($features, 0, 4) as $feature): 
                                        ?>
                                        <li><?php echo htmlspecialchars($feature); ?></li>
                                        <?php endforeach; ?>
                                        <?php if (count($features) > 4): ?>
                                        <li style="color: #6b7280; font-style: italic;">And <?php echo count($features) - 4; ?> more features...</li>
                                        <?php endif; ?>
                                    </ul>
                                    
                                    <?php if (!empty($gateway['supported_currencies'])): ?>
                                    <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #f3f4f6;">
                                        <div style="font-size: 0.75rem; color: #6b7280; margin-bottom: 0.5rem;">SUPPORTED CURRENCIES</div>
                                        <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
                                            <?php 
                                            $currencies = json_decode($gateway['supported_currencies'], true) ?: [];
                                            foreach ($currencies as $currency): 
                                            ?>
                                            <span style="background: #f3f4f6; color: #374151; padding: 0.125rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: 500;">
                                                <?php echo htmlspecialchars($currency); ?>
                                            </span>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="gateway-footer">
                                    <div class="price-section">
                                        <div class="gateway-price">$<?php echo number_format($gateway['price'], 0); ?></div>
                                        <div class="price-details">One-time purchase • Lifetime updates</div>
                                    </div>
                                    <a href="#" class="btn-outline">View Details</a>
                                    <a href="#" class="btn-primary">Purchase Now</a>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="col-12">
                            <div style="text-align: center; padding: 3rem; background: white; border: 1px solid #e5e7eb; border-radius: 8px;">
                                <div style="font-size: 3rem; color: #d1d5db; margin-bottom: 1rem;">💳</div>
                                <h3 style="color: #374151; margin-bottom: 0.5rem;">No payment gateways found</h3>
                                <p style="color: #6b7280; margin-bottom: 1.5rem;">
                                    There are no payment gateways available in this category.
                                </p>
                                <a href="payment-gateways.php" class="btn-primary" style="width: auto;">View All Gateways</a>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Information Section -->
                <div class="row mt-5">
                    <div class="col-12">
                        <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 2rem;">
                            <h4 style="color: #111827; margin-bottom: 1rem;">Need Help Choosing?</h4>
                            <div class="row">
                                <div class="col-md-6">
                                    <h6 style="color: #374151; margin-bottom: 0.5rem;">📱 MTN Mobile Money</h6>
                                    <p style="color: #6b7280; font-size: 0.875rem; margin-bottom: 1rem;">
                                        Most popular provider in South Sudan. Best for general e-commerce and widespread adoption.
                                    </p>
                                    
                                    <h6 style="color: #374151; margin-bottom: 0.5rem;">🔄 m-GURUSH</h6>
                                    <p style="color: #6b7280; font-size: 0.875rem; margin-bottom: 1rem;">
                                        Zain's mobile money service. Great for customers who prefer Zain network services.
                                    </p>
                                </div>
                                <div class="col-md-6">
                                    <h6 style="color: #374151; margin-bottom: 0.5rem;">💰 Nilepay</h6>
                                    <p style="color: #6b7280; font-size: 0.875rem; margin-bottom: 1rem;">
                                        Advanced payment solution with multi-currency support and business tools.
                                    </p>
                                    
                                    <h6 style="color: #374151; margin-bottom: 0.5rem;">🏢 Enterprise Solutions</h6>
                                    <p style="color: #6b7280; font-size: 0.875rem;">
                                        Need custom integration? Contact our team for enterprise payment gateway solutions.
                                    </p>
                                </div>
                            </div>
                            <div style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #e5e7eb;">
                                <a href="custom-solutions.php" class="btn-primary" style="width: auto; margin-right: 1rem;">Request Custom Solution</a>
                                <a href="#" class="btn-outline" style="width: auto;">View Documentation</a>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <!-- Footer -->
        <?php 
        if (file_exists('partials/footer.php')) {
            include 'partials/footer.php'; 
        }
        ?>
    </div>
</div>

<!-- Scripts -->
<script src="assets/js/vendor.min.js"></script>
<script src="assets/js/app.min.js"></script>

<script>
console.log('💳 Payment Gateways page loaded successfully');

// Add hover effects to cards
document.querySelectorAll('.gateway-card').forEach(card => {
    card.addEventListener('mouseenter', function() {
        this.style.transform = 'translateY(-4px)';
    });
    
    card.addEventListener('mouseleave', function() {
        this.style.transform = 'translateY(-2px)';
    });
});

// Track category filter clicks
document.querySelectorAll('.filter-tab').forEach(tab => {
    tab.addEventListener('click', function() {
        console.log('Category filter clicked:', this.textContent.trim());
    });
});

// Add click handlers for action buttons
document.querySelectorAll('.btn-primary, .btn-outline').forEach(btn => {
    btn.addEventListener('click', function(e) {
        // Only prevent default for demo links (href="#")
        if (this.getAttribute('href') === '#') {
            e.preventDefault();
            
            const action = this.textContent.trim();
            console.log('Action clicked:', action);
            
            // Show simple alert for demo
            if (action.includes('Purchase')) {
                alert('Redirecting to purchase...');
            } else if (action.includes('Details')) {
                alert('Loading product details...');
            } else if (action.includes('Custom Solution')) {
                window.location.href = 'custom-solutions.php';
            }
        }
    });
});

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    console.log('📊 Payment Gateway Statistics:', {
        total_gateways: <?php echo count($payment_gateways); ?>,
        popular_gateways: <?php echo count($popular_gateways); ?>,
        category_filter: '<?php echo $category_filter; ?>'
    });
    
    // Remove loading class
    document.body.classList.remove('loading');
    
    // Animate cards on load
    document.querySelectorAll('.gateway-card').forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        
        setTimeout(() => {
            card.style.transition = 'all 0.5s ease';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, index * 100);
    });
});
</script>

</body>
</html>