{% extends "base.html" %}

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

<!-- Wallet Balance Banner -->
<div style="background: linear-gradient(135deg, #1a4a2e, #0f3460); 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: #a0a0a0; font-size: 14px; margin-bottom: 5px;">Wallet Balance</div>
            <div style="font-size: 32px; font-weight: bold; color: #4ade80;">{{ currency_symbol }}{{ wallet.balance }}</div>
            <div style="color: #a0a0a0; font-size: 13px; margin-top: 5px;">
                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>Manage Wallet
        </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: #16213e; border: 2px solid #4a9eff; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
    <h3 style="margin: 0 0 20px 0; color: #4a9eff;">
        <i class="fas fa-wallet me-2"></i>Payment Methods
    </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: #1a1a2e; border: 1px solid #0f3460; 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: #a0a0a0; 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;">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="background: #17a2b8; border: none; color: white; padding: 8px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; display: inline-block !important; visibility: visible !important;">Set Default</button>
                    {% endif %}
                    <button class="btn btn-secondary delete-method-btn" data-method-id="{{ method.id }}" data-method-type="{{ method.type }}" style="background: #dc3545; border: none; color: white; 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: #a0a0a0;">
        <i class="fas fa-credit-card fa-4x mb-3"></i>
        <h4 style="margin-bottom: 15px;">No payment methods configured</h4>
        <p style="margin-bottom: 20px;">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>Add Credit Card</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>Add Credit Card</button>
        {% endif %}
        <a href="{{ url_for(request, '/dashboard/wallet') }}" class="btn btn-secondary">
            <i class="fas fa-wallet me-2"></i>Top Up Wallet
        </a>
    </div>
</div>

<!-- Billing History Section -->
<div style="background: #16213e; border: 2px solid #17a2b8; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
    <h3 style="margin: 0 0 20px 0; color: #17a2b8;">
        <i class="fas fa-history me-2"></i>Billing History
    </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: #0f3460; color: #e0e0e0;">
                    <th style="padding: 12px; text-align: center; border-bottom: 1px solid #0f3460; font-weight: 600;">Date</th>
                    <th style="padding: 12px; text-align: left; border-bottom: 1px solid #0f3460; font-weight: 600;">Description</th>
                    <th style="padding: 12px; text-align: center; border-bottom: 1px solid #0f3460; font-weight: 600;">Amount</th>
                    <th style="padding: 12px; text-align: center; border-bottom: 1px solid #0f3460; font-weight: 600;">Method</th>
                    <th style="padding: 12px; text-align: center; border-bottom: 1px solid #0f3460; font-weight: 600;">Status</th>
                    <th style="padding: 12px; text-align: center; border-bottom: 1px solid #0f3460; font-weight: 600;">Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for tx in transactions %}
                <tr style="border-bottom: 1px solid #0f3460; color: #e0e0e0;">
                    <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: #a0a0a0;">{{ 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 %}
                            Plan Payment
                            {% endif %}
                        </div>
                        {% if tx.plan_name %}
                        <small style="color: #a0a0a0;">{{ 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>PayPal</small>
                        {% elif tx.payment_method == 'stripe' %}
                        <i class="fab fa-cc-stripe text-primary"></i><br><small>Credit Card</small>
                        {% elif tx.payment_method == 'bitcoin' %}
                        <i class="fab fa-bitcoin text-warning"></i><br><small>Bitcoin</small>
                        {% elif tx.payment_method == 'eth' or tx.payment_method == 'ethereum' %}
                        <i class="fab fa-ethereum text-purple"></i><br><small>Ethereum</small>
                        {% elif tx.payment_method == 'usdt' %}
                        <i class="fas fa-coins text-success"></i><br><small>USDT</small>
                        {% elif tx.payment_method == 'usdc' %}
                        <i class="fas fa-coins text-info"></i><br><small>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;">✓ Completed</span>
                        {% elif tx.status == 'pending' %}
                        <span style="background: #ffc107; color: black; padding: 4px 8px; border-radius: 10px; font-size: 12px;">⏳ Pending</span>
                        {% elif tx.status == 'failed' %}
                        <span style="background: #dc3545; color: white; padding: 4px 8px; border-radius: 10px; font-size: 12px;">✗ Failed</span>
                        {% elif tx.status == 'refunded' %}
                        <span style="background: #6c757d; color: white; padding: 4px 8px; border-radius: 10px; font-size: 12px;">↩ 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>Invoice
                        </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;">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;">Next</button>
    </div>
    {% endif %}

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

{% block extra_js %}
<style>
/* Payment Method Cards */
.payment-method-card {
    border: 1px solid #0f3460;
    border-radius: 5px;
    padding: 15px;
    background: #1a1a2e;
    margin-bottom: 10px;
    transition: all 0.2s ease;
}

.payment-method-card:hover {
    border-color: #4a9eff;
    box-shadow: 0 2px 8px rgba(74, 158, 255, 0.2);
}

.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: #e0e0e0;
}

.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 #0f3460;
    border-radius: 3px;
    font-size: 14px;
    background: #1a1a2e;
    color: #e0e0e0;
}

.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:#16213e;border:2px solid #4a9eff;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:#e0e0e0;font-size:24px;cursor:pointer;">&times;</button>
        <h3 style="margin:0 0 20px 0;color:#4a9eff;"><i class="fab fa-cc-stripe me-2"></i>Add Credit Card</h3>
        <form id="stripe-card-form">
            <div style="margin-bottom:20px;">
                <label style="display:block;margin-bottom:8px;color:#e0e0e0;font-weight:500;">Card Details</label>
                <div id="card-element" style="background:#1a1a2e;padding:12px;border:1px solid #0f3460;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">Cancel</button>
                <button type="submit" id="stripe-submit" class="btn"><i class="fas fa-plus me-2"></i>Add Card</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>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>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 %}
