{% extends "base.html" %}

{% block title %}Billing Management - {{ app_name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <h2><i class="fas fa-credit-card me-2"></i>Billing Management</h2>
            <p class="text-muted">Manage broker subscriptions, invoices, and payment settings.</p>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card bg-primary text-white h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-0">Total Subscriptions</h6>
                            <h2 class="mb-0" id="total-subscriptions">-</h2>
                        </div>
                        <i class="fas fa-users fa-2x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card bg-success text-white h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-0">Active Subscriptions</h6>
                            <h2 class="mb-0" id="active-subscriptions">-</h2>
                        </div>
                        <i class="fas fa-check-circle fa-2x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card bg-warning text-dark h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-0">Monthly Revenue</h6>
                            <h2 class="mb-0" id="monthly-revenue">-</h2>
                        </div>
                        <i class="fas fa-dollar-sign fa-2x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card bg-info text-white h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-0">Pending Invoices</h6>
                            <h2 class="mb-0" id="pending-invoices">-</h2>
                        </div>
                        <i class="fas fa-file-invoice fa-2x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabs -->
    <ul class="nav nav-tabs mb-3" id="billingTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="subscriptions-tab" data-bs-toggle="tab" 
                    data-bs-target="#subscriptions" type="button" role="tab">
                <i class="fas fa-users me-1"></i>Subscriptions
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="plans-tab" data-bs-toggle="tab" 
                    data-bs-target="#plans" type="button" role="tab">
                <i class="fas fa-tags me-1"></i>Plans
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="invoices-tab" data-bs-toggle="tab" 
                    data-bs-target="#invoices" type="button" role="tab">
                <i class="fas fa-file-invoice me-1"></i>Invoices
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="currencies-tab" data-bs-toggle="tab" 
                    data-bs-target="#currencies" type="button" role="tab">
                <i class="fas fa-coins me-1"></i>Currencies
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="gateways-tab" data-bs-toggle="tab" 
                    data-bs-target="#gateways" type="button" role="tab">
                <i class="fas fa-credit-card me-1"></i>Payment Gateways
            </button>
        </li>
    </ul>

    <div class="tab-content" id="billingTabContent">
        <!-- Subscriptions Tab -->
        <div class="tab-pane fade show active" id="subscriptions" role="tabpanel">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">All Subscriptions</h5>
                    <div>
                        <select class="form-select form-select-sm d-inline-block w-auto me-2" id="subscription-filter">
                            <option value="">All Status</option>
                            <option value="active">Active</option>
                            <option value="trial">Trial</option>
                            <option value="past_due">Past Due</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                        <button class="btn btn-sm btn-outline-secondary" onclick="loadSubscriptions()">
                            <i class="fas fa-sync me-1"></i>Refresh
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Plan</th>
                                    <th>Status</th>
                                    <th>Billing Period</th>
                                    <th>Amount</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="subscriptions-list">
                                <tr>
                                    <td colspan="6" class="text-center">
                                        <div class="spinner-border spinner-border-sm" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                        Loading subscriptions...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Plans Tab -->
        <div class="tab-pane fade" id="plans" role="tabpanel">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Subscription Plans</h5>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#planModal">
                        <i class="fas fa-plus me-1"></i>Add Plan
                    </button>
                </div>
                <div class="card-body">
                    <div class="row" id="plans-list">
                        <div class="col-12 text-center py-4">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            Loading plans...
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Invoices Tab -->
        <div class="tab-pane fade" id="invoices" role="tabpanel">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Recent Invoices</h5>
                    <div>
                        <select class="form-select form-select-sm d-inline-block w-auto me-2" id="invoice-filter">
                            <option value="">All Status</option>
                            <option value="pending">Pending</option>
                            <option value="paid">Paid</option>
                            <option value="overdue">Overdue</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                        <button class="btn btn-sm btn-outline-secondary" onclick="loadInvoices()">
                            <i class="fas fa-sync me-1"></i>Refresh
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Invoice #</th>
                                    <th>User</th>
                                    <th>Period</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Due Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="invoices-list">
                                <tr>
                                    <td colspan="7" class="text-center">
                                        <div class="spinner-border spinner-border-sm" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                        Loading invoices...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Currencies Tab -->
        <div class="tab-pane fade" id="currencies" role="tabpanel">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Supported Currencies</h5>
                    <div>
                        <select class="form-select form-select-sm d-inline-block w-auto me-2" id="currency-type-filter">
                            <option value="">All Types</option>
                            <option value="fiat">Fiat</option>
                            <option value="crypto">Crypto</option>
                        </select>
                        <button class="btn btn-sm btn-outline-primary" onclick="updateExchangeRates()">
                            <i class="fas fa-sync me-1"></i>Update Rates
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Code</th>
                                    <th>Name</th>
                                    <th>Symbol</th>
                                    <th>Type</th>
                                    <th>Exchange Rate (USD)</th>
                                    <th>Last Updated</th>
                                </tr>
                            </thead>
                            <tbody id="currencies-list">
                                <tr>
                                    <td colspan="6" class="text-center">
                                        <div class="spinner-border spinner-border-sm" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                        Loading currencies...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Payment Gateways Tab -->
        <div class="tab-pane fade" id="gateways" role="tabpanel">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Payment Gateways</h5>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#gatewayModal">
                        <i class="fas fa-plus me-1"></i>Add Gateway
                    </button>
                </div>
                <div class="card-body">
                    <div class="row" id="gateways-list">
                        <div class="col-12 text-center py-4">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            Loading gateways...
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Plan Modal -->
<div class="modal fade" id="planModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Plan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="plan-form">
                    <input type="hidden" id="plan-id" value="">
                    <input type="hidden" id="plan-type" value="">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Display Name</label>
                            <input type="text" class="form-control" id="plan-display-name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Description</label>
                            <input type="text" class="form-control" id="plan-description">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Monthly Fee ($)</label>
                            <input type="number" step="0.01" class="form-control" id="plan-monthly-fee" value="0.00">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Transaction Fee (%)</label>
                            <input type="number" step="0.01" class="form-control" id="plan-transaction-fee" value="0.00">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Revenue Share (%)</label>
                            <input type="number" step="0.01" class="form-control" id="plan-revenue-share" value="0.00">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Max API Keys</label>
                            <input type="number" class="form-control" id="plan-max-api-keys" value="1">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">API Requests/Month (0 = Unlimited)</label>
                            <input type="number" class="form-control" id="plan-api-requests" value="0">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Support Level</label>
                            <select class="form-select" id="plan-support-level">
                                <option value="email">Email</option>
                                <option value="email_chat">Email + Chat</option>
                                <option value="priority">Priority</option>
                                <option value="dedicated">Dedicated</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <div class="form-check mt-4">
                                <input type="checkbox" class="form-check-input" id="plan-custom-gateway">
                                <label class="form-check-label" for="plan-custom-gateway">Allow Custom Gateway</label>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="form-check mt-4">
                                <input type="checkbox" class="form-check-input" id="plan-dedicated-session">
                                <label class="form-check-label" for="plan-dedicated-session">Allow Dedicated Session</label>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="form-check mt-4">
                                <input type="checkbox" class="form-check-input" id="plan-contact-pricing">
                                <label class="form-check-label" for="plan-contact-pricing">Contact for Pricing</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="plan-is-active" checked>
                                <label class="form-check-label" for="plan-is-active">Active</label>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="plan-is-featured">
                                <label class="form-check-label" for="plan-is-featured">
                                    <i class="fas fa-star text-warning"></i> Featured as "Most Popular"
                                </label>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="savePlan()">Save Plan</button>
            </div>
        </div>
    </div>
</div>

<!-- Gateway Modal -->
<div class="modal fade" id="gatewayModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add/Edit Payment Gateway</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="gateway-form">
                    <input type="hidden" name="gateway_id" value="">
                    <div class="mb-3">
                        <label class="form-label">Gateway Name</label>
                        <input type="text" class="form-control" name="gateway_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Gateway Type</label>
                        <select class="form-select" name="gateway_type" required>
                            <option value="fiat">Fiat</option>
                            <option value="crypto">Crypto</option>
                            <option value="both">Both</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">API Key</label>
                        <input type="text" class="form-control" name="api_key">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">API Secret</label>
                        <input type="password" class="form-control" name="api_secret">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Webhook Secret</label>
                        <input type="password" class="form-control" name="webhook_secret">
                    </div>
                    <div class="form-check mb-3">
                        <input type="checkbox" class="form-check-input" name="is_active" id="gateway-active" checked>
                        <label class="form-check-label" for="gateway-active">Active</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveGateway()">Save Gateway</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// Currency configuration
let primaryCurrency = {
    code: 'USD',
    symbol: '$',
    position: 'before',
    exchange_rate: 1.0
};

document.addEventListener('DOMContentLoaded', function() {
    // Load initial data
    loadCurrencySettings();
    loadBillingSummary();
    loadSubscriptions();
    loadPlans();
    loadCurrencies();
    loadGateways();
    
    // Setup tab change handlers
    document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(tab => {
        tab.addEventListener('shown.bs.tab', function(e) {
            const target = e.target.getAttribute('data-bs-target');
            if (target === '#invoices') {
                loadInvoices();
            }
        });
    });
    
    // Setup filters
    document.getElementById('subscription-filter').addEventListener('change', loadSubscriptions);
    document.getElementById('invoice-filter').addEventListener('change', loadInvoices);
    document.getElementById('currency-type-filter').addEventListener('change', loadCurrencies);
});

function loadCurrencySettings() {
    fetch('/api/currency-settings')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.settings) {
                primaryCurrency = {
                    code: data.settings.primary_currency_code || 'USD',
                    symbol: data.settings.primary_currency_symbol || '$',
                    position: data.settings.position || 'before',
                    exchange_rate: data.settings.exchange_rate || 1.0
                };
            }
        })
        .catch(error => console.error('Error loading currency settings:', error));
}

function formatCurrency(amount) {
    const convertedAmount = amount * primaryCurrency.exchange_rate;
    if (primaryCurrency.position === 'before') {
        return `${primaryCurrency.symbol}${convertedAmount.toFixed(2)}`;
    } else {
        return `${convertedAmount.toFixed(2)}${primaryCurrency.symbol}`;
    }
}

function loadBillingSummary() {
    fetch('/api/admin/billing/summary')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.summary) {
                document.getElementById('total-subscriptions').textContent = data.summary.total_subscriptions || 0;
                document.getElementById('active-subscriptions').textContent = data.summary.active_subscriptions || 0;
                document.getElementById('monthly-revenue').textContent = formatCurrency(data.summary.monthly_revenue || 0);
                document.getElementById('pending-invoices').textContent = data.summary.pending_invoices || 0;
            }
        })
        .catch(error => console.error('Error loading billing summary:', error));
}

function loadSubscriptions() {
    const status = document.getElementById('subscription-filter').value;
    let url = '/api/admin/billing/subscriptions';
    if (status) {
        url += `?status=${status}`;
    }
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('subscriptions-list');
            if (data.success && data.subscriptions && data.subscriptions.length > 0) {
                tbody.innerHTML = data.subscriptions.map(sub => `
                    <tr>
                        <td>${sub.user_id}</td>
                        <td><span class="badge bg-primary">${sub.plan_type}</span></td>
                        <td><span class="badge ${getStatusBadgeClass(sub.status)}">${sub.status}</span></td>
                        <td>${formatDate(sub.current_period_start)} - ${formatDate(sub.current_period_end)}</td>
                        <td>${sub.currency} ${sub.amount.toFixed(2)}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" onclick="viewSubscription(${sub.id})">
                                <i class="fas fa-eye"></i>
                            </button>
                        </td>
                    </tr>
                `).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No subscriptions found</td></tr>';
            }
        })
        .catch(error => {
            console.error('Error loading subscriptions:', error);
            document.getElementById('subscriptions-list').innerHTML = 
                '<tr><td colspan="6" class="text-center text-danger">Failed to load subscriptions</td></tr>';
        });
}

function loadPlans() {
    fetch('/api/billing/plans')
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById('plans-list');
            if (data.success && data.plans && data.plans.length > 0) {
                container.innerHTML = data.plans.map(plan => {
                    const isFeatured = plan.is_featured || plan.plan_type === 'professional';
                    const priceDisplay = plan.contact_for_pricing
                        ? '<small class="text-muted">Contact us for pricing</small>'
                        : `${formatCurrency(plan.monthly_fee || 0)}<small class="text-muted">/mo</small>`;
                    const apiRequestsDisplay = plan.api_requests_per_month === 0
                        ? 'Unlimited'
                        : plan.api_requests_per_month.toLocaleString();
                    
                    return `
                    <div class="col-md-6 col-lg-3 mb-4">
                        <div class="card h-100 ${isFeatured ? 'border-primary' : ''}">
                            ${isFeatured ? '<div class="card-header bg-primary text-white text-center"><i class="fas fa-star me-1"></i>Most Popular</div>' : ''}
                            <div class="card-body text-center">
                                <h5 class="card-title">${plan.display_name}</h5>
                                <h2 class="card-price">${priceDisplay}</h2>
                                <p class="text-muted">${plan.max_api_keys} API key${plan.max_api_keys !== 1 ? 's' : ''}</p>
                                <ul class="list-unstyled text-start">
                                    <li><i class="fas fa-check text-success me-2"></i>API Requests: ${apiRequestsDisplay}/mo</li>
                                    <li><i class="fas fa-check text-success me-2"></i>Transaction Fee: ${(plan.transaction_fee * 100).toFixed(2)}%</li>
                                    <li><i class="fas fa-check text-success me-2"></i>Revenue Share: ${plan.revenue_share_percentage}%</li>
                                    <li><i class="fas fa-check text-success me-2"></i>Custom Gateway: ${plan.allow_custom_gateway ? 'Yes' : 'No'}</li>
                                    <li><i class="fas fa-check text-success me-2"></i>Dedicated Session: ${plan.allow_dedicated_session ? 'Yes' : 'No'}</li>
                                    <li><i class="fas fa-check text-success me-2"></i>Support: ${plan.support_level}</li>
                                </ul>
                            </div>
                            <div class="card-footer text-center">
                                <button class="btn btn-outline-primary btn-sm" onclick="editPlan(${plan.id})">
                                    <i class="fas fa-edit me-1"></i>Edit
                                </button>
                                <button class="btn btn-outline-${isFeatured ? 'secondary' : 'warning'} btn-sm ms-1" onclick="toggleFeatured(${plan.id}, ${!isFeatured})" title="${isFeatured ? 'Remove from featured' : 'Mark as featured'}">
                                    <i class="fas fa-star"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                `}).join('');
            } else {
                container.innerHTML = '<div class="col-12 text-center text-muted py-4">No plans configured</div>';
            }
        })
        .catch(error => {
            console.error('Error loading plans:', error);
            document.getElementById('plans-list').innerHTML =
                '<div class="col-12 text-center text-danger py-4">Failed to load plans</div>';
        });
}

function loadInvoices() {
    const status = document.getElementById('invoice-filter').value;
    // For admin, we'd need an admin endpoint for all invoices
    // For now, this is a placeholder
    const tbody = document.getElementById('invoices-list');
    tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">No invoices found</td></tr>';
}

function loadCurrencies() {
    const type = document.getElementById('currency-type-filter').value;
    let url = '/api/billing/currencies';
    if (type) {
        url += `?type=${type}`;
    }
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('currencies-list');
            if (data.success && data.currencies && data.currencies.length > 0) {
                tbody.innerHTML = data.currencies.map(currency => `
                    <tr>
                        <td><strong>${currency.code}</strong></td>
                        <td>${currency.name}</td>
                        <td>${currency.symbol}</td>
                        <td><span class="badge ${currency.currency_type === 'crypto' ? 'bg-warning' : 'bg-info'}">${currency.currency_type}</span></td>
                        <td>${currency.exchange_rate_to_usd ? currency.exchange_rate_to_usd.toFixed(6) : '-'}</td>
                        <td>${currency.last_rate_update ? formatDate(currency.last_rate_update) : '-'}</td>
                    </tr>
                `).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No currencies found</td></tr>';
            }
        })
        .catch(error => {
            console.error('Error loading currencies:', error);
            document.getElementById('currencies-list').innerHTML = 
                '<tr><td colspan="6" class="text-center text-danger">Failed to load currencies</td></tr>';
        });
}

function loadGateways() {
    fetch('/api/billing/gateways')
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById('gateways-list');
            if (data.success && data.gateways && data.gateways.length > 0) {
                container.innerHTML = data.gateways.map(gateway => `
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card h-100 ${gateway.is_active ? '' : 'bg-light'}">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <h5 class="card-title mb-0">${gateway.gateway_name}</h5>
                                    <span class="badge ${gateway.is_active ? 'bg-success' : 'bg-secondary'}">
                                        ${gateway.is_active ? 'Active' : 'Inactive'}
                                    </span>
                                </div>
                                <p class="text-muted mb-2">
                                    <i class="fas fa-${gateway.gateway_type === 'crypto' ? 'bitcoin' : 'credit-card'} me-1"></i>
                                    ${gateway.gateway_type.charAt(0).toUpperCase() + gateway.gateway_type.slice(1)}
                                </p>
                                <p class="text-muted mb-0 small">
                                    <i class="fas fa-percent me-1"></i>
                                    Fee: ${gateway.processing_fee_percent}% + $${gateway.processing_fee_fixed.toFixed(2)}
                                </p>
                            </div>
                            <div class="card-footer">
                                <button class="btn btn-outline-primary btn-sm" onclick="editGateway(${gateway.id})">
                                    <i class="fas fa-edit me-1"></i>Configure
                                </button>
                            </div>
                        </div>
                    </div>
                `).join('');
            } else {
                container.innerHTML = '<div class="col-12 text-center text-muted py-4">No payment gateways configured</div>';
            }
        })
        .catch(error => {
            console.error('Error loading gateways:', error);
            document.getElementById('gateways-list').innerHTML = 
                '<div class="col-12 text-center text-danger py-4">Failed to load gateways</div>';
        });
}

function updateExchangeRates() {
    const btn = event.target;
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Updating...';
    btn.disabled = true;
    
    fetch('/api/admin/billing/exchange-rates/update', { method: 'POST' })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('success', 'Exchange rates updated successfully');
                loadCurrencies();
            } else {
                showToast('error', data.error || 'Failed to update exchange rates');
            }
        })
        .catch(error => {
            console.error('Error updating exchange rates:', error);
            showToast('error', 'Failed to update exchange rates');
        })
        .finally(() => {
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
}

function getStatusBadgeClass(status) {
    switch (status) {
        case 'active': return 'bg-success';
        case 'trial': return 'bg-info';
        case 'past_due': return 'bg-warning';
        case 'cancelled': return 'bg-danger';
        default: return 'bg-secondary';
    }
}

function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleDateString();
}

function showToast(type, message) {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'error' ? 'danger' : 'success'} alert-dismissible fade show position-fixed`;
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    toast.innerHTML = `
        <i class="fas fa-${type === 'error' ? 'exclamation-triangle' : 'check-circle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(toast);
    
    setTimeout(() => toast.remove(), 5000);
}

function viewSubscription(id) {
    // TODO: Implement subscription details modal
    console.log('View subscription:', id);
}

function editPlan(id) {
    // Fetch plan details and show modal
    fetch(`/api/billing/plans/${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.plan) {
                const plan = data.plan;
                document.getElementById('plan-id').value = plan.id;
                document.getElementById('plan-type').value = plan.plan_type;
                document.getElementById('plan-display-name').value = plan.display_name;
                document.getElementById('plan-description').value = plan.description || '';
                document.getElementById('plan-monthly-fee').value = plan.monthly_fee || 0;
                document.getElementById('plan-contact-pricing').checked = plan.contact_for_pricing || false;
                document.getElementById('plan-transaction-fee').value = (plan.transaction_fee * 100).toFixed(2);
                document.getElementById('plan-revenue-share').value = plan.revenue_share_percentage;
                document.getElementById('plan-max-api-keys').value = plan.max_api_keys;
                document.getElementById('plan-api-requests').value = plan.api_requests_per_month || 0;
                document.getElementById('plan-custom-gateway').checked = plan.allow_custom_gateway;
                document.getElementById('plan-dedicated-session').checked = plan.allow_dedicated_session;
                document.getElementById('plan-support-level').value = plan.support_level;
                document.getElementById('plan-is-active').checked = plan.is_active;
                document.getElementById('plan-is-featured').checked = plan.is_featured || false;
                
                // Show modal
                const modal = new bootstrap.Modal(document.getElementById('planModal'));
                modal.show();
            } else {
                alert('Failed to load plan details');
            }
        })
        .catch(error => {
            console.error('Error loading plan:', error);
            alert('Error loading plan details');
        });
}

function toggleFeatured(id, featured) {
    fetch(`/api/billing/plans/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ is_featured: featured })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadPlans();
            } else {
                alert('Failed to update plan: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error updating plan:', error);
            alert('Error updating plan');
        });
}

function savePlan() {
    const id = document.getElementById('plan-id').value;
    const data = {
        display_name: document.getElementById('plan-display-name').value,
        description: document.getElementById('plan-description').value,
        monthly_fee: parseFloat(document.getElementById('plan-monthly-fee').value) || 0,
        contact_for_pricing: document.getElementById('plan-contact-pricing').checked,
        transaction_fee: parseFloat(document.getElementById('plan-transaction-fee').value) / 100,
        revenue_share_percentage: parseFloat(document.getElementById('plan-revenue-share').value) || 0,
        max_api_keys: parseInt(document.getElementById('plan-max-api-keys').value) || 1,
        api_requests_per_month: parseInt(document.getElementById('plan-api-requests').value) || 0,
        allow_custom_gateway: document.getElementById('plan-custom-gateway').checked,
        allow_dedicated_session: document.getElementById('plan-dedicated-session').checked,
        support_level: document.getElementById('plan-support-level').value,
        is_active: document.getElementById('plan-is-active').checked,
        is_featured: document.getElementById('plan-is-featured').checked
    };
    
    fetch(`/api/billing/plans/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                bootstrap.Modal.getInstance(document.getElementById('planModal')).hide();
                loadPlans();
            } else {
                alert('Failed to save plan: ' + (result.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error saving plan:', error);
            alert('Error saving plan');
        });
}

function editGateway(id) {
    // TODO: Implement gateway edit
    console.log('Edit gateway:', id);
}

function saveGateway() {
    // TODO: Implement gateway save
    console.log('Save gateway');
}
</script>
{% endblock %}