<?php
// Ensure subscription is not null to prevent warnings
if (!$subscription) {
    $subscription = [];
}
?>

<div class="page-header">
    <div>
        <a href="<?= APP_URL ?>/dashboard" class="btn btn-ghost btn-sm mb-4" style="padding-left:0;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
            Back to Dashboard
        </a>
        <h1>Billing & Subscription</h1>
        <div class="page-subtitle">Manage your plan, check usage limits, and view invoices.</div>
    </div>
</div>

<div class="stats-grid mb-6">
    <div class="stat-card">
        <div class="stat-icon primary">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect><line x1="1" y1="10" x2="23" y2="10"></line></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Current Plan</div>
            <div class="stat-value"><?= e($package['name'] ?? 'Free') ?></div>
            <div class="stat-change text-muted">
                Renews on <?= ($subscription && $subscription['current_period_end']) ? date('M j, Y', strtotime($subscription['current_period_end'])) : 'Unknown' ?>
            </div>
        </div>
    </div>

    <div class="stat-card">
        <div class="stat-icon success">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Subscription Status</div>
            <div class="stat-value" style="color:var(--success);"><?= ucfirst(e($subscription['status'] ?? 'active')) ?></div>
            <div class="stat-change text-muted">
                Billed <?= e(($subscription['billing_cycle'] ?? 'monthly')) ?> 
                <?php if (($subscription['payment_method'] ?? 'manual') === 'paystack'): ?>
                    via Paystack
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="grid-2 gap-6 mb-6">
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Plan Usage Limits</h3>
            <span class="badge badge-primary"><?= e($package['name'] ?? 'Free') ?> Pack</span>
        </div>
        
        <?php foreach ($usage as $key => $u): ?>
        <div class="usage-bar-wrap mb-4">
            <div class="usage-bar-label">
                <span><?= ucfirst($key) ?></span>
                <span><?= $u['current'] ?> / <?= $u['limit'] == -1 ? 'Unlimited' : $u['limit'] ?></span>
            </div>
            <div class="usage-bar-track">
                <?php 
                $pct = $u['limit'] > 0 ? ($u['current'] / $u['limit']) * 100 : 0;
                if ($u['limit'] == -1) $pct = 10; // show something small for unlimited
                ?>
                <div class="usage-bar-fill <?= $pct >= 90 ? 'danger' : ($pct >= 75 ? 'warn' : '') ?>" style="width: <?= min(100, $pct) ?>%"></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Upgrade Plan</h3>

        </div>
        <p class="text-xs text-muted mb-6">Unlock more features, products, and multi-location support by upgrading your subscription.</p>
        
        <div id="plans-selector" class="pricing-grid">
            <?php foreach ($plans as $plan): 
                $currentPlanId = $subscription['plan_id'] ?? 0;
                if ($plan['id'] == $currentPlanId) continue;
                $features = json_decode($plan['features'], true);
                $isCurrentPlan = $currentPlanId == $plan['id'];
            ?>
            <div class="pricing-card <?= $isCurrentPlan ? 'current-plan' : '' ?>" 
                 onclick="selectPlan(<?= $plan['id'] ?>, '<?= e($plan['name']) ?>', <?= (float)$plan['price_monthly'] ?>)">
                
                <!-- Plan Header -->
                <div class="plan-header">
                    <div class="plan-name">
                        <?= e($plan['name']) ?>
                        <?php if ($isCurrentPlan): ?>
                        <span class="current-badge">Current Plan</span>
                        <?php endif; ?>
                    </div>
                    <div class="plan-price">
                        <span class="price-amount"><?= setting('currency_symbol', 'GH₵') ?><?= number_format($plan['price_monthly']) ?></span>
                        <span class="price-period">/month</span>
                    </div>
                </div>
                
                <!-- Plan Features -->
                <div class="plan-features">
                    <div class="feature-item">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px; height:16px;">
                            <path d="M20 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4-4v2"></path>
                            <polyline points="17,8 15,5 7,8"></polyline>
                            <line x1="15" y1="3" x2="9" y2="3"></line>
                            <line x1="9" y1="21" x2="15" y2="21"></line>
                        </svg>
                        <span>Products</span>
                        <div class="feature-value"><?= $plan['max_products'] == -1 ? 'Unlimited' : $plan['max_products'] ?></div>
                    </div>
                    
                    <div class="feature-item">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px; height:16px;">
                            <path d="M21 16V8a2 2 0 0 0-2-2H5a2 2 0 0 0-2-2v8a2 2 0 0 0 2h14a2 2 0 0 0 2-2z"></path>
                            <polyline points="7,10 12,15 17,10"></polyline>
                            <line x1="12" y1="15" x2="12" y2="3"></line>
                        </svg>
                        <span>Locations</span>
                        <div class="feature-value"><?= $plan['max_locations'] == -1 ? 'Unlimited' : $plan['max_locations'] ?></div>
                    </div>
                </div>
                
                <!-- Plan Action -->
                <div class="plan-action">
                    <?php if ($isCurrentPlan): ?>
                    <button class="btn btn-outline btn-disabled" disabled>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                            <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0z"></path>
                        </svg>
                        Current Plan
                    </button>
                    <?php else: ?>
                    <button class="btn btn-primary">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                            <path d="M5 13l4 4L19 7"></path>
                            <path d="M19 21l-7-7-7-7"></path>
                            <path d="M2 12h20"></path>
                        </svg>
                        Select Plan
                    </button>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3 class="card-title">Billing History</h3>
    </div>
    <div class="table-wrapper">
        <table>
             <thead>
                <tr>
                    <th>Date</th>
                    <th>Plan</th>
                    <th>Cycle</th>
                    <th>Amount</th>
                    <th>Payment</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
             </thead>
             <tbody>
                <?php if (!empty($subscription)): ?>
                <tr>
                    <td class="text-sm"><?= $subscription['created_at'] ? date('M j, Y', strtotime($subscription['created_at'])) : 'N/A' ?></td>
                    <td><strong><?= e($package['name'] ?? 'Free') ?></strong></td>
                    <td class="text-xs">Monthly</td>
                    <td class="font-bold"><?= setting('currency_symbol', 'GH₵') ?><?= number_format($subscription['price'] ?? 0, 2) ?></td>
                    <td class="text-sm">Trial/Manual</td>
                    <td><span class="badge badge-success">Paid</span></td>
                    <td class="text-right">
                        <button class="btn btn-ghost btn-icon" onclick="downloadInvoice('<?= $subscription['id'] ?? '' ?>')" title="Download Invoice">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;">
                                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2 2v-4"></path>
                                <polyline points="7 10 12 15 17 10"></polyline>
                                <line x1="12" y1="15" x2="12" y2="3"></line>
                            </svg>
                        </button>
                    </td>
                </tr>
                <?php else: ?>
                <tr>
                    <td colspan="7" class="text-center text-muted">No billing history available</td>
                </tr>
                <?php endif; ?>
             </tbody>
        </table>
    </div>
</div>

<!-- Plan Upgrade Modal -->
<div class="modal-overlay" id="upgradeModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Upgrade to <span id="modal-plan-name"></span></h3>
            <button class="modal-close" onclick="document.getElementById('upgradeModal').classList.remove('show')"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button>
        </div>
        <form action="<?= APP_URL ?>/billing/upgrade" method="POST">
            <?= Security::csrfField() ?>
            <input type="hidden" name="plan_id" id="modal-plan-id">
            <div class="modal-body">
                <div class="text-center p-6 bg-raised rounded mb-6">
                    <div class="text-muted mb-1 text-sm">Total due today</div>
                    <div style="font-size: 2rem; font-weight: 800; color: var(--primary-light);"><?= setting('currency_symbol', 'GH₵') ?><span id="modal-plan-price"></span>.00</div>
                </div>
                <div class="form-group">
                    <label class="form-label">Billing Cycle</label>
                    <select name="billing_cycle" id="billing-cycle" class="form-control" onchange="updateBillingCycle()">
                        <option value="monthly">Monthly (1 month)</option>
                        <option value="3months">3 Months</option>
                        <option value="6months">6 Months</option>
                        <option value="yearly">Yearly (12 months)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label">Payment Method</label>
                    <div class="payment-methods">
                        <div class="payment-option active" id="paystack-option" onclick="selectPaymentMethod('paystack')">
                            <div class="payment-icon">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:24px; height:24px;">
                                    <rect x="2" y="4" width="20" height="16" rx="2" ry="2"></rect>
                                    <line x1="2" y1="10" x2="22" y2="10"></line>
                                    <circle cx="8" cy="14" r="2"></circle>
                                    <path d="M16 14h2"></path>
                                </svg>
                            </div>
                            <div class="payment-info">
                                <div class="payment-title">Paystack Secure Payment</div>
                                <div class="payment-desc">Pay with Card, Bank Transfer, USSD</div>
                                <div class="payment-features">
                                    <span class="feature-badge">Instant</span>
                                    <span class="feature-badge">Secure</span>
                                    <span class="feature-badge">NGN Supported</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="payment-option" id="manual-option" onclick="selectPaymentMethod('manual')">
                            <div class="payment-icon">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:24px; height:24px;">
                                    <path d="M17 9V7a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z"></path>
                                    <polyline points="17,8 15,5 7,8"></polyline>
                                    <line x1="15" y1="3" x2="9" y2="3"></line>
                                    <line x1="9" y1="21" x2="15" y2="21"></line>
                                </svg>
                            </div>
                            <div class="payment-info">
                                <div class="payment-title">Manual Payment</div>
                                <div class="payment-desc">Contact support for manual setup</div>
                                <div class="payment-features">
                                    <span class="feature-badge">Bank Transfer</span>
                                    <span class="feature-badge">Invoice</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <input type="hidden" name="payment_method" id="selected-payment-method" value="paystack">
                </div>
                
                <div class="upgrade-summary">
                    <div class="summary-item">
                        <span class="summary-label">Total Due Today</span>
                        <span class="summary-value" id="modal-plan-price">0.00</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label">Billing Cycle</span>
                        <span class="summary-value" id="summary-billing-cycle">Monthly</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label">Next Billing</span>
                        <span class="summary-value" id="summary-next-billing"><?= date('M j, Y', strtotime('+1 month')) ?></span>
                    </div>
                </div>
                
                <p class="text-xs text-muted">By clicking "Complete Upgrade", you agree to the TellerPro subscription terms. Your plan will be updated immediately.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost btn-lg" onclick="document.getElementById('upgradeModal').classList.remove('show')">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                    Cancel
                </button>
                <button type="submit" class="btn btn-primary btn-lg btn-gradient" id="confirm-upgrade-btn">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                        <path d="M5 13l4 4L19 7"></path>
                        <path d="M19 21l-7-7-7-7"></path>
                        <path d="M2 12h20"></path>
                    </svg>
                    <span id="upgrade-btn-text">Complete Upgrade</span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
let selectedPlanPrice = 0;

function selectPlan(id, name, price) {
    document.getElementById('modal-plan-id').value = id;
    document.getElementById('modal-plan-name').innerText = name;
    selectedPlanPrice = price;
    document.getElementById('modal-plan-price').innerText = price;
    updateBillingCycle();
    document.getElementById('upgradeModal').classList.add('show');
}

function updateBillingCycle() {
    const cycle = document.getElementById('billing-cycle').value;
    const cycleDisplay = document.getElementById('summary-billing-cycle');
    const nextBilling = document.getElementById('summary-next-billing');
    const priceDisplay = document.getElementById('modal-plan-price');

    let multiplier = 1;
    let months = 1;
    let cycleText = 'Monthly';

    switch(cycle) {
        case '3months':
            multiplier = 3;
            months = 3;
            cycleText = '3 Months';
            break;
        case '6months':
            multiplier = 6;
            months = 6;
            cycleText = '6 Months';
            break;
        case 'yearly':
            multiplier = 12;
            months = 12;
            cycleText = 'Yearly';
            break;
        default:
            multiplier = 1;
            months = 1;
            cycleText = 'Monthly';
    }

    cycleDisplay.innerText = cycleText;
    priceDisplay.innerText = (selectedPlanPrice * multiplier).toFixed(2);

    const nextBillingDate = new Date();
    nextBillingDate.setMonth(nextBillingDate.getMonth() + months);
    nextBilling.innerText = nextBillingDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

function selectPaymentMethod(method) {
    // Remove active class from all options
    document.querySelectorAll('.payment-option').forEach(option => {
        option.classList.remove('active');
    });
    
    // Add active class to selected option
    document.getElementById(method + '-option').classList.add('active');
    
    // Update hidden field
    document.getElementById('selected-payment-method').value = method;
    
    // Update button text and styling
    const confirmBtn = document.getElementById('confirm-upgrade-btn');
    const btnText = document.getElementById('upgrade-btn-text');
    
    if (method === 'paystack') {
        confirmBtn.classList.add('btn-gradient');
        confirmBtn.classList.remove('btn-success');
        btnText.textContent = 'Complete Upgrade';
    } else {
        confirmBtn.classList.remove('btn-gradient');
        confirmBtn.classList.add('btn-success');
        btnText.textContent = 'Request Invoice';
    }
}

function downloadInvoice(subscriptionId) {
    // Create a temporary form to submit the download request
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '<?= APP_URL ?>/billing/download-invoice';
    form.target = '_blank';
    
    // Add CSRF token
    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = 'csrf_token';
    csrfInput.value = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    form.appendChild(csrfInput);
    
    // Add subscription ID
    const subscriptionInput = document.createElement('input');
    subscriptionInput.type = 'hidden';
    subscriptionInput.name = 'subscription_id';
    subscriptionInput.value = subscriptionId;
    form.appendChild(subscriptionInput);
    
    // Submit the form
    document.body.appendChild(form);
    form.submit();
    
    // Clean up
    document.body.removeChild(form);
}
</script>

<style>
.payment-methods {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.payment-option {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    border: 2px solid var(--border);
    border-radius: 0.5rem;
    background: var(--bg);
    cursor: pointer;
    transition: all 0.3s ease;
}

.payment-option:hover {
    border-color: var(--primary);
    transform: translateY(-2px);
}

.payment-option.active {
    border-color: var(--primary);
    background: var(--primary) 0.1;
    box-shadow: 0 4px 12px rgba(99, 102, 241, 0.1);
}

.payment-icon {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--bg-surface);
    border-radius: 0.375rem;
    flex-shrink: 0;
}

.payment-info {
    flex: 1;
}

.payment-title {
    font-weight: 600;
    color: var(--text);
    margin-bottom: 0.25rem;
}

.payment-desc {
    font-size: 0.875rem;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
}

.payment-features {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.feature-badge {
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    font-size: 0.625rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.025em;
}

.feature-badge:first-child {
    background: var(--success);
    color: white;
}

.feature-badge:nth-child(2) {
    background: var(--primary);
    color: white;
}

.feature-badge:nth-child(3) {
    background: var(--info);
    color: white;
}

.upgrade-summary {
    background: var(--bg-surface);
    border: 1px solid var(--border);
    border-radius: 0.5rem;
    padding: 1rem;
    margin-top: 1rem;
}

.summary-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.5rem 0;
    border-bottom: 1px solid var(--border);
}

.summary-item:last-child {
    border-bottom: none;
}

.summary-label {
    font-size: 0.875rem;
    color: var(--text-muted);
}

.summary-value {
    font-weight: 600;
    color: var(--text);
}

.btn-lg {
    padding: 0.625rem 1.25rem;
    font-size: 0.875rem;
}

.btn-gradient {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
    border: none;
    color: white;
    box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

.btn-gradient:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(99, 102, 241, 0.4);
}

.btn-success {
    background: var(--success);
    border-color: var(--success);
    color: white;
}

.btn-success:hover {
    background: var(--success-dark);
    border-color: var(--success-dark);
}

/* Pricing Grid Styles */
.pricing-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.pricing-card {
    background: var(--bg-card);
    border: 2px solid var(--border);
    border-radius: 12px;
    padding: 0;
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.pricing-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
    border-color: var(--primary);
}

.pricing-card.current-plan {
    border-color: var(--primary);
    background: var(--primary) 0.05;
    box-shadow: 0 8px 16px rgba(99, 102, 241, 0.15);
}

.plan-header {
    padding: 1rem;
    border-bottom: 1px solid var(--border);
    background: var(--bg-surface);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.plan-name {
    font-size: 1.125rem;
    font-weight: 700;
    color: var(--text);
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.current-badge {
    background: var(--success);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.625rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.025em;
}

.plan-price {
    text-align: right;
}

.price-amount {
    font-size: 2rem;
    font-weight: 800;
    color: var(--primary);
    line-height: 1;
}

.price-period {
    font-size: 0.875rem;
    color: var(--text-muted);
    margin-left: 0.25rem;
}

.plan-features {
    padding: 1.5rem;
}

.feature-item {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 0.75rem;
}

.feature-item:last-child {
    margin-bottom: 0;
}

.feature-value {
    font-weight: 600;
    color: var(--text);
    font-size: 0.875rem;
}

.plan-action {
    padding: 1rem;
    border-top: 1px solid var(--border);
    background: var(--bg-surface);
}

.btn-disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.btn-disabled:hover {
    transform: none;
    box-shadow: none;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .pricing-grid {
        grid-template-columns: 1fr;
        gap: 1rem;
    }
    
    .plan-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
    }
    
    .plan-name {
        font-size: 1.125rem;
    }
    
    .plan-price {
        text-align: left;
    }
}
</style>
