{% extends "base.html" %}

{% block content %}
<h2 style="margin-bottom: 20px;" data-i18n="billing_page.title">Billing & Payments</h2>

<!-- Wallet Balance Banner -->
<div style="background: var(--bg-panel); border: 2px solid #28a745; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
    <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px;">
        <div>
            <div style="color: var(--color-muted); font-size: 14px; margin-bottom: 5px;" data-i18n="billing_page.wallet_balance">Wallet Balance</div>
            <div style="font-size: 32px; font-weight: bold; color: #4ade80;">{{ currency_symbol }}{{ wallet.balance }}</div>
            <div style="color: var(--color-muted); font-size: 13px; margin-top: 5px;" data-i18n="billing_page.wallet_desc">
                All subscription renewals and payments are automatically charged from your wallet first.
            </div>
        </div>
        <a href="{{ url_for(request, '/dashboard/wallet') }}" class="btn" style="background: #28a745;">
            <i class="fas fa-wallet me-2"></i><span data-i18n="billing_page.manage_wallet">Manage Wallet</span>
        </a>
    </div>
</div>

{% if success %}
<div class="alert alert-success">{{ success }}</div>
{% endif %}

{% if error %}
<div class="alert alert-error">{{ error }}</div>
{% endif %}

<!-- Payment Methods Section -->
<div style="background: var(--bg-panel); border: 2px solid var(--color-border); border-radius: 8px; padding: 20px; margin-bottom: 20px;">
    <h3 style="margin: 0 0 20px 0; color: var(--color-link);">
        <i class="fas fa-wallet me-2"></i><span data-i18n="billing_page.payment_methods">Payment Methods</span>
    </h3>

    {% if payment_methods and payment_methods|length > 0 %}
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px;">
        {% for method in payment_methods %}
        <div class="payment-method-card {% if method.is_default %}default{% endif %}" style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; margin-bottom: 10px;">
            <div style="display: flex; align-items: center; margin-bottom: 10px;">
                <div style="margin-right: 15px;">
                    {% if method.type == 'paypal' %}
                    <i class="fab fa-paypal fa-2x text-primary"></i>
                    {% elif method.type == 'stripe' %}
                    <i class="fab fa-cc-stripe fa-2x text-primary"></i>
                    {% elif method.type == 'bitcoin' %}
                    <i class="fab fa-bitcoin fa-2x text-warning"></i>
                    {% elif method.type == 'ethereum' or method.type == 'eth' %}
                    <i class="fab fa-ethereum fa-2x text-purple"></i>
                    {% elif method.type == 'usdt' %}
                    <i class="fas fa-coins fa-2x text-success"></i>
                    {% elif method.type == 'usdc' %}
                    <i class="fas fa-coins fa-2x text-info"></i>
                    {% else %}
                    <i class="fas fa-credit-card fa-2x text-secondary"></i>
                    {% endif %}
                </div>
                <div style="flex-grow: 1;">
                    <div style="font-weight: bold; margin-bottom: 5px;">{{ method.type|title }}</div>
                    <div style="color: var(--color-muted); font-size: 14px;">
                        {% if method.last4 %}
                        **** **** **** {{ method.last4 }}
                        {% else %}
                        {{ method.email if method.email else method.address }}
                        {% endif %}
                    </div>
                    {% if method.is_default %}
                    <span style="background: #28a745; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px; margin-top: 5px; display: inline-block;" data-i18n="billing_page.default_label">Default</span>
                    {% endif %}
                </div>
                <div style="display: flex; flex-direction: column; gap: 5px;">
                    {% if not method.is_default %}
                    <button class="btn btn-secondary set-default-btn" data-method-id="{{ method.id }}" style="border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; display: inline-block !important; visibility: visible !important;" data-i18n="billing_page.set_default">Set Default</button>
                    {% endif %}
                    <button class="btn btn-danger delete-method-btn" data-method-id="{{ method.id }}" data-method-type="{{ method.type }}" style="border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; font-size: 14px; display: inline-block !important; visibility: visible !important; width: auto; min-width: 40px;" title="Delete payment method">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div style="text-align: center; padding: 40px; color: var(--color-muted);">
        <i class="fas fa-credit-card fa-4x mb-3"></i>
        <h4 style="margin-bottom: 15px;" data-i18n="billing_page.no_payment_methods">No payment methods configured</h4>
        <p style="margin-bottom: 20px;" data-i18n="billing_page.no_payment_methods_desc">Add a credit card to enable automatic subscription renewals.</p>
        {% if 'stripe' in enabled_gateways %}
        <button id="stripe-button" class="btn"><i class="fab fa-cc-stripe me-2"></i><span data-i18n="billing_page.add_credit_card">Add Credit Card</span></button>
        {% endif %}
    </div>
    {% endif %}

    <div style="display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap; align-items: center;">
        {% if 'stripe' in enabled_gateways %}
        <button id="stripe-button-bottom" class="btn"><i class="fab fa-cc-stripe me-2"></i><span data-i18n="billing_page.add_credit_card">Add Credit Card</span></button>
        {% endif %}
        <a href="{{ url_for(request, '/dashboard/wallet') }}" class="btn btn-secondary">
            <i class="fas fa-wallet me-2"></i><span data-i18n="billing_page.top_up_wallet">Top Up Wallet</span>
        </a>
    </div>
</div>

<!-- Billing History Section -->
<div style="background: var(--bg-panel); border: 2px solid var(--color-border); border-radius: 8px; padding: 20px; margin-bottom: 20px;">
    <h3 style="margin: 0 0 20px 0; color: var(--color-link);">
        <i class="fas fa-history me-2"></i><span data-i18n="billing_page.billing_history">Billing History</span>
    </h3>

    {% if transactions and transactions|length > 0 %}
    <div style="overflow-x: auto;">
        <table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
            <thead>
                <tr style="background:var(--bg-accent); color: var(--color-text);">
                    <th style="padding: 12px; text-align: center; border-bottom:1px solid var(--color-border); font-weight: 600;" data-i18n="billing_page.col_date">Date</th>
                    <th style="padding: 12px; text-align: left; border-bottom:1px solid var(--color-border); font-weight: 600;" data-i18n="billing_page.col_description">Description</th>
                    <th style="padding: 12px; text-align: center; border-bottom:1px solid var(--color-border); font-weight: 600;" data-i18n="billing_page.col_amount">Amount</th>
                    <th style="padding: 12px; text-align: center; border-bottom:1px solid var(--color-border); font-weight: 600;" data-i18n="billing_page.col_method">Method</th>
                    <th style="padding: 12px; text-align: center; border-bottom:1px solid var(--color-border); font-weight: 600;" data-i18n="billing_page.col_status">Status</th>
                    <th style="padding: 12px; text-align: center; border-bottom:1px solid var(--color-border); font-weight: 600;" data-i18n="billing_page.col_actions">Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for tx in transactions %}
                <tr style="border-bottom:1px solid var(--color-border); color: var(--color-text);">
                    <td style="padding: 12px; text-align: center;">
                        <div style="font-weight: bold;">{{ tx.created_at.split(' ')[0] if tx.created_at else '' }}</div>
                        <small style="color: var(--color-muted);">{{ tx.created_at.split(' ')[1] if tx.created_at else '' }}</small>
                    </td>
                    <td style="padding: 12px;">
                        <div style="font-weight: bold;">
                            {% if tx.description %}
                            {{ tx.description }}
                            {% else %}
                            <span data-i18n="billing_page.plan_payment">Plan Payment</span>
                            {% endif %}
                        </div>
                        {% if tx.plan_name %}
                        <small style="color: var(--color-muted);">{{ tx.plan_name }}</small>
                        {% endif %}
                    </td>
                    <td style="padding: 12px; text-align: center;">
                        <span style="font-size: 18px; font-weight: bold; color: #4ade80;">
                            {% if tx.currency_symbol %}
                            {{ tx.currency_symbol }}
                            {% else %}
                            $
                            {% endif %}
                            {{ tx.amount }}
                        </span>
                    </td>
                    <td style="padding: 12px; text-align: center;">
                        {% if tx.payment_method == 'paypal' %}
                        <i class="fab fa-paypal text-primary"></i><br><small data-i18n="billing_page.paypal">PayPal</small>
                        {% elif tx.payment_method == 'stripe' %}
                        <i class="fab fa-cc-stripe text-primary"></i><br><small data-i18n="billing_page.credit_card">Credit Card</small>
                        {% elif tx.payment_method == 'bitcoin' %}
                        <i class="fab fa-bitcoin text-warning"></i><br><small data-i18n="billing_page.bitcoin">Bitcoin</small>
                        {% elif tx.payment_method == 'eth' or tx.payment_method == 'ethereum' %}
                        <i class="fab fa-ethereum text-purple"></i><br><small data-i18n="billing_page.ethereum">Ethereum</small>
                        {% elif tx.payment_method == 'usdt' %}
                        <i class="fas fa-coins text-success"></i><br><small data-i18n="billing_page.usdt">USDT</small>
                        {% elif tx.payment_method == 'usdc' %}
                        <i class="fas fa-coins text-info"></i><br><small data-i18n="billing_page.usdc">USDC</small>
                        {% else %}
                        <i class="fas fa-credit-card text-secondary"></i><br><small>{{ tx.payment_method|title }}</small>
                        {% endif %}
                    </td>
                    <td style="padding: 12px; text-align: center;">
                        {% if tx.status == 'completed' %}
                        <span style="background: #28a745; color: white; padding: 4px 8px; border-radius: 10px; font-size: 12px;" data-i18n="billing_page.status_completed">✓ Completed</span>
                        {% elif tx.status == 'pending' %}
                        <span style="background: #ffc107; color: black; padding: 4px 8px; border-radius: 10px; font-size: 12px;" data-i18n="billing_page.status_pending">⏳ Pending</span>
                        {% elif tx.status == 'failed' %}
                        <span style="background: #dc3545; color: white; padding: 4px 8px; border-radius: 10px; font-size: 12px;" data-i18n="billing_page.status_failed">✗ Failed</span>
                        {% elif tx.status == 'refunded' %}
                        <span style="background: #6c757d; color: white; padding: 4px 8px; border-radius: 10px; font-size: 12px;" data-i18n="billing_page.status_refunded">↩ Refunded</span>
                        {% else %}
                        <span style="background: #6c757d; color: white; padding: 4px 8px; border-radius: 10px; font-size: 12px;">{{ tx.status|title }}</span>
                        {% endif %}
                    </td>
                    <td style="padding: 12px; text-align: center;">
                        {% if tx.invoice_id %}
                        <a href="#" class="btn btn-secondary" style="padding: 5px 10px; font-size: 12px;">
                            <i class="fas fa-file-pdf me-1"></i><span data-i18n="billing_page.invoice">Invoice</span>
                        </a>
                        {% endif %}
                        <button class="btn btn-secondary" style="padding: 5px 10px; font-size: 12px; margin-left: 5px;" title="View Details">
                            <i class="fas fa-eye"></i>
                        </button>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    {% if transactions|length > 10 %}
    <div style="margin-top: 20px; text-align: center;">
        <button class="btn btn-secondary" style="margin: 0 5px;" data-i18n="billing_page.prev">Previous</button>
        <button class="btn" style="margin: 0 5px;">1</button>
        <button class="btn btn-secondary" style="margin: 0 5px;">2</button>
        <button class="btn btn-secondary" style="margin: 0 5px;" data-i18n="billing_page.next">Next</button>
    </div>
    {% endif %}

    {% else %}
    <div style="text-align: center; padding: 40px; color: var(--color-muted);">
        <i class="fas fa-receipt fa-4x mb-3"></i>
        <h4 style="margin-bottom: 15px;" data-i18n="billing_page.no_history">No billing history yet</h4>
        <p style="margin-bottom: 20px;" data-i18n="billing_page.no_history_desc">You don't have any payment transactions on your account.</p>
        <p style="margin-bottom: 20px;" data-i18n="billing_page.no_history_upgrade">Upgrade your plan to get started!</p>
        <a href="{{ url_for(request, '/dashboard/pricing') }}" class="btn">
            <i class="fas fa-star me-2"></i><span data-i18n="billing_page.view_plans">View Plans & Pricing</span>
        </a>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<style>
/* Payment Method Cards */
.payment-method-card {
    border:1px solid var(--color-border);
    border-radius: 5px;
    padding: 15px;
    background: var(--bg-page);
    margin-bottom: 10px;
    transition: all 0.2s ease;
}

.payment-method-card:hover {
    border-color: var(--color-link);
    box-shadow: 0 2px 8px var(--shadow);
}

.payment-method-card.default {
    border-color: #28a745;
    box-shadow: 0 0 10px rgba(40, 167, 69, 0.3);
}

.text-purple {
    color: #6f42c1;
}

/* Form groups */
.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
    color: var(--color-text);
}

.form-group input[type="text"],
.form-group input[type="password"],
.form-group input[type="number"],
.form-group select {
    width: 100%;
    padding: 8px;
    border:1px solid var(--color-border);
    border-radius: 3px;
    font-size: 14px;
    background: var(--bg-page);
    color: var(--color-text);
}

.form-group input[type="checkbox"] {
    margin-right: 5px;
}

/* Payment method buttons styling */
.delete-method-btn, .set-default-btn {
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    visibility: visible !important;
    opacity: 1 !important;
    min-height: 32px !important;
    min-width: 32px !important;
}

.delete-method-btn:hover {
    background: #c82333 !important;
}

.set-default-btn:hover {
    background: #0d8aa8 !important;
}

/* Ensure Font Awesome icons are visible */
.fas, .fab, .far {
    font-family: "Font Awesome 6 Free", "Font Awesome 6 Brands" !important;
    font-weight: 900 !important;
    display: inline-block !important;
}
</style>

<!-- Stripe Card Modal -->
<div id="stripe-modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);z-index:1000;align-items:center;justify-content:center;">
    <div style="background:var(--bg-panel);border:2px solid var(--color-link);border-radius:8px;padding:30px;max-width:500px;width:90%;position:relative;">
        <button id="close-stripe-modal" style="position:absolute;top:15px;right:15px;background:transparent;border:none;color:var(--color-text);font-size:24px;cursor:pointer;">&times;</button>
        <h3 style="margin:0 0 20px 0;color:var(--color-link);"><i class="fab fa-cc-stripe me-2"></i><span data-i18n="billing_page.add_credit_card">Add Credit Card</span></h3>
        <form id="stripe-card-form">
            <div style="margin-bottom:20px;">
                <label style="display:block;margin-bottom:8px;color:var(--color-text);font-weight:500;">Card Details</label>
                <div id="card-element" style="background:var(--bg-page);padding:12px;border:1px solid var(--color-border);border-radius:4px;"></div>
                <div id="card-errors" style="color:#dc3545;margin-top:8px;font-size:14px;"></div>
            </div>
            <div style="display:flex;gap:10px;justify-content:flex-end;">
                <button type="button" id="cancel-stripe" class="btn btn-secondary" data-i18n="billing_page.cancel">Cancel</button>
                <button type="submit" id="stripe-submit" class="btn"><i class="fas fa-plus me-2"></i><span data-i18n="billing_page.add_card">Add Card</span></button>
            </div>
        </form>
    </div>
</div>

<script src="https://js.stripe.com/v3/"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // existing delete/set-default logic unchanged below...

    {% if stripe_publishable_key %}
    const STRIPE_KEY = '{{ stripe_publishable_key }}';
    let stripe, cardElement, stripeReady = false;

    function openStripeModal() {
        document.getElementById('stripe-modal').style.display = 'flex';
        if (!stripeReady) {
            stripe = Stripe(STRIPE_KEY);
            cardElement = stripe.elements().create('card', {
                style: { base: { color: '#e0e0e0', fontSize: '16px', '::placeholder': { color: '#a0a0a0' } }, invalid: { color: '#dc3545' } }
            });
            cardElement.mount('#card-element');
            cardElement.on('change', e => { document.getElementById('card-errors').textContent = e.error ? e.error.message : ''; });
            stripeReady = true;
        }
    }

    ['stripe-button', 'stripe-button-bottom'].forEach(id => {
        const btn = document.getElementById(id);
        if (btn) btn.addEventListener('click', openStripeModal);
    });

    document.getElementById('close-stripe-modal').addEventListener('click', () => document.getElementById('stripe-modal').style.display = 'none');
    document.getElementById('cancel-stripe').addEventListener('click', () => document.getElementById('stripe-modal').style.display = 'none');
    document.getElementById('stripe-modal').addEventListener('click', e => { if (e.target === document.getElementById('stripe-modal')) document.getElementById('stripe-modal').style.display = 'none'; });

    document.getElementById('stripe-card-form').addEventListener('submit', async e => {
        e.preventDefault();
        const btn = document.getElementById('stripe-submit');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing…';
        const { error, paymentMethod } = await stripe.createPaymentMethod({ type: 'card', card: cardElement });
        if (error) {
            document.getElementById('card-errors').textContent = error.message;
            btn.disabled = false;
            btn.innerHTML = `<i class="fas fa-plus me-2"></i>${window.i18n.t('billing.add_card')}`;
            return;
        }
        const res = await fetch('/dashboard/billing/add-method/stripe', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ payment_method_id: paymentMethod.id })
        });
        const data = await res.json();
        if (data.success) {
            window.location.href = '/dashboard/billing?success=' + encodeURIComponent(data.message || 'Card added');
        } else {
            document.getElementById('card-errors').textContent = data.error || 'Failed to add card';
            btn.disabled = false;
            btn.innerHTML = `<i class="fas fa-plus me-2"></i>${window.i18n.t('billing.add_card')}`;
        }
    });
    {% endif %}

    // Delete payment method
    const deleteButtons = document.querySelectorAll('.delete-method-btn');
    console.log('Found delete buttons:', deleteButtons.length);

    deleteButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            console.log('Delete button clicked');

            const methodId = this.dataset.methodId;
            const methodType = this.dataset.methodType;

            console.log('Method ID:', methodId, 'Method Type:', methodType);

            if (!methodId) {
                console.error('No method ID found');
                showAlert('Error: Payment method ID not found', 'Error', '❌', 'danger');
                return;
            }

            showDangerConfirm(`Are you sure you want to delete this ${methodType || 'payment'} method?`, 'Delete Payment Method').then(ok => {
                if (!ok) return;
                console.log('Sending DELETE request to:', `/dashboard/billing/payment-methods/${methodId}`);

                fetch(`/dashboard/billing/payment-methods/${methodId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => {
                    console.log('Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Response data:', data);
                    if (data.success) {
                        showAlert('Payment method deleted successfully', 'Done', '✅', 'info').then(() => window.location.reload());
                    } else {
                        showAlert('Error: ' + (data.error || 'Failed to delete payment method'), 'Error', '❌', 'danger');
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    showAlert('An error occurred while deleting the payment method: ' + error.message, 'Error', '❌', 'danger');
                });
            });
        });
    });

    // Set default payment method
    const setDefaultButtons = document.querySelectorAll('.set-default-btn');
    console.log('Found set default buttons:', setDefaultButtons.length);

    setDefaultButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            console.log('Set default button clicked');

            const methodId = this.dataset.methodId;
            console.log('Method ID:', methodId);

            if (!methodId) {
                console.error('No method ID found');
                showAlert('Error: Payment method ID not found', 'Error', '❌', 'danger');
                return;
            }

            console.log('Sending POST request to:', `/dashboard/billing/payment-methods/${methodId}/set-default`);

            fetch(`/dashboard/billing/payment-methods/${methodId}/set-default`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => {
                console.log('Response status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('Response data:', data);
                if (data.success) {
                    showAlert('Payment method set as default', 'Done', '✅', 'info').then(() => window.location.reload());
                } else {
                    showAlert('Error: ' + (data.error || 'Failed to set default payment method'), 'Error', '❌', 'danger');
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
                showAlert('An error occurred while setting default payment method: ' + error.message, 'Error', '❌', 'danger');
            });
        });
    });

    // Check if buttons have data attributes
    deleteButtons.forEach((btn, index) => {
        console.log(`Delete button ${index}: methodId=${btn.dataset.methodId}, methodType=${btn.dataset.methodType}`);
    });

    setDefaultButtons.forEach((btn, index) => {
        console.log(`Set default button ${index}: methodId=${btn.dataset.methodId}`);
    });
});
</script>
{% endblock %}
