<?php
require_once __DIR__ . '/../../api/lib.php';
hw_require_auth(['client']);
$authUser = hw_get_auth_user();

// CHECK MEMBERSHIP
$db = hw_db();
$membershipStmt = $db->prepare("SELECT id, plan_type, expires_at FROM user_memberships WHERE user_id = ? AND status = 'active' AND expires_at > NOW() LIMIT 1");
$membershipStmt->execute([$authUser['id']]);
if (!$membershipStmt->fetch()) {
    header('Location: /files/atasteofafricanmarketplace/dashboard/user/choose-plan.php');
    exit;
}

$page_title = 'Billing & Payments | Herbal Wellness Care';
$page_description = 'Manage your payments, invoices, and billing information';
$page_content = function () use ($authUser) { ?>
<style>
  nav.fixed { 
    display: none !important; 
    visibility: hidden !important;
    position: absolute !important;
    pointer-events: none !important;
    z-index: -1 !important;
  }
  body > nav { 
    display: none !important; 
    visibility: hidden !important;
  }
  body {
    padding-top: 0 !important;
  }
</style>
<link rel="stylesheet" href="/files/atasteofafricanmarketplace/assets/dashboard.css">

<div class="dashboard-container">
  <!-- Sidebar -->
  <div class="dashboard-sidebar">
    <div class="sidebar-header">
      <div class="sidebar-profile">
        <div class="profile-avatar">
          <?= strtoupper(substr($authUser['first_name'], 0, 1) . substr($authUser['last_name'], 0, 1)) ?>
        </div>
        <div class="profile-info">
          <h3><?= htmlspecialchars($authUser['first_name'] . ' ' . $authUser['last_name']) ?></h3>
          <p>Wellness Member</p>
        </div>
      </div>
    </div>
    <nav class="sidebar-nav">
      <a href="/files/atasteofafricanmarketplace/dashboard/user/index.php"><i class="fas fa-home"></i>Home</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php"><i class="fas fa-calendar-check"></i>Appointments</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/messages.php"><i class="fas fa-comments"></i>Messages</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/records.php"><i class="fas fa-file-medical"></i>Records</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/profile.php"><i class="fas fa-user"></i>Profile & Support</a>
      <hr class="sidebar-divider">
      <a href="/files/atasteofafricanmarketplace/store.php"><i class="fas fa-store"></i>Wellness Store</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/membership.php"><i class="fas fa-crown"></i>My Membership</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/billing.php" class="active"><i class="fas fa-file-invoice-dollar"></i>Billing</a>
      <hr class="sidebar-divider">
      <a href="/files/atasteofafricanmarketplace/index.php"><i class="fas fa-arrow-left"></i>Back to Home</a>
    </nav>
    <div class="sidebar-footer">
      <a href="/files/atasteofafricanmarketplace/api/auth/logout.php" style="display: flex; align-items: center; gap: 12px; color: rgba(255,255,255,0.7); text-decoration: none; font-size: 13px; font-weight: 500; padding: 10px 0; border-top: 1px solid rgba(212, 173, 49, 0.15); transition: all 0.3s;"><i class="fas fa-sign-out-alt"></i>Sign Out</a>
    </div>
  </div>

  <!-- Main Content -->
  <div class="dashboard-content">
    <main>
      <!-- Header -->
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px; flex-wrap: wrap; gap: 16px;">
        <div>
          <h1 style="font-size: 32px; font-weight: 800; color: #0b3d2e; margin: 0 0 8px 0;">Billing & Payments</h1>
          <p style="font-size: 16px; color: #64748b; margin: 0;">Manage your payments, invoices, and billing information</p>
        </div>
        <button onclick="downloadStatement()" style="background: white; color: #0f5240; padding: 12px 24px; border-radius: 10px; font-size: 14px; font-weight: 700; border: 2px solid #0f5240; cursor: pointer; transition: all 0.3s; display: flex; align-items: center; gap: 8px;">
          <i class="fas fa-download"></i> Download Statement
        </button>
      </div>

      <!-- Payment Summary Cards -->
      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 32px;">
        <div style="background: linear-gradient(135deg, #0f5240 0%, #146651 100%); padding: 24px; border-radius: 16px; box-shadow: 0 8px 24px rgba(15, 82, 64, 0.2); position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
          <div style="position: relative; z-index: 1;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
              <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Total Spent</p>
              <i class="fas fa-wallet" style="color: rgba(255, 255, 255, 0.3); font-size: 24px;"></i>
            </div>
            <p style="font-size: 36px; font-weight: 800; color: white; margin: 0;" id="total-spent">$0.00</p>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 12px; margin: 8px 0 0 0;">All time spending</p>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); padding: 24px; border-radius: 16px; box-shadow: 0 8px 24px rgba(59, 130, 246, 0.2); position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
          <div style="position: relative; z-index: 1;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
              <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">This Month</p>
              <i class="fas fa-calendar-alt" style="color: rgba(255, 255, 255, 0.3); font-size: 24px;"></i>
            </div>
            <p style="font-size: 36px; font-weight: 800; color: white; margin: 0;" id="month-spent">$0.00</p>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 12px; margin: 8px 0 0 0;">January 2026</p>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #d4ad31 0%, #c9a227 100%); padding: 24px; border-radius: 16px; box-shadow: 0 8px 24px rgba(212, 173, 49, 0.2); position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
          <div style="position: relative; z-index: 1;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
              <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Outstanding</p>
              <i class="fas fa-exclamation-circle" style="color: rgba(255, 255, 255, 0.3); font-size: 24px;"></i>
            </div>
            <p style="font-size: 36px; font-weight: 800; color: white; margin: 0;" id="outstanding">$0.00</p>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 12px; margin: 8px 0 0 0;">Pending payments</p>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); padding: 24px; border-radius: 16px; box-shadow: 0 8px 24px rgba(139, 92, 246, 0.2); position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
          <div style="position: relative; z-index: 1;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
              <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Next Payment</p>
              <i class="fas fa-clock" style="color: rgba(255, 255, 255, 0.3); font-size: 24px;"></i>
            </div>
            <p style="font-size: 36px; font-weight: 800; color: white; margin: 0;" id="next-payment">$0.00</p>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 12px; margin: 8px 0 0 0;" id="next-payment-date">No upcoming payments</p>
          </div>
        </div>
      </div>

      <!-- Payment Methods -->
      <div style="background: white; padding: 32px; border-radius: 16px; margin-bottom: 32px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 16px;">
          <div>
            <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 6px 0; display: flex; align-items: center; gap: 12px;">
              <i class="fas fa-credit-card" style="color: #0f5240;"></i>
              Payment Methods
            </h3>
            <p style="color: #64748b; margin: 0; font-size: 14px;">Manage your payment methods and preferences</p>
          </div>
          <button onclick="addPaymentMethod()" style="background: linear-gradient(135deg, #0f5240, #146651); color: white; padding: 12px 24px; border-radius: 10px; font-size: 14px; font-weight: 700; border: none; cursor: pointer; box-shadow: 0 4px 12px rgba(15, 82, 64, 0.3); transition: all 0.3s; display: flex; align-items: center; gap: 8px;">
            <i class="fas fa-plus-circle"></i> Add Payment Method
          </button>
        </div>
        
        <div id="payment-methods">
          <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 40px; border-radius: 12px; border: 2px dashed #d4ad31; text-align: center;">
            <i class="fas fa-credit-card" style="font-size: 48px; color: #d4ad31; margin-bottom: 16px;"></i>
            <p style="color: #64748b; margin: 0 0 16px 0; font-size: 15px;">No payment methods added yet</p>
            <button onclick="addPaymentMethod()" style="background: white; color: #0f5240; padding: 12px 24px; border-radius: 10px; font-size: 14px; font-weight: 700; border: 2px solid #0f5240; cursor: pointer; transition: all 0.3s;">
              Add Your First Payment Method
            </button>
          </div>
        </div>
      </div>

      <!-- Recent Transactions -->
      <div style="background: white; padding: 32px; border-radius: 16px; margin-bottom: 32px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 16px;">
          <div>
            <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 6px 0; display: flex; align-items: center; gap: 12px;">
              <i class="fas fa-exchange-alt" style="color: #0f5240;"></i>
              Recent Transactions
            </h3>
            <p style="color: #64748b; margin: 0; font-size: 14px;">Your payment history and activity</p>
          </div>
          <div style="display: flex; gap: 8px;">
            <button onclick="filterTransactions('all')" class="filter-btn active" data-filter="all" style="background: #0f5240; color: white; padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 600; border: none; cursor: pointer; transition: all 0.3s;">All</button>
            <button onclick="filterTransactions('completed')" class="filter-btn" data-filter="completed" style="background: #f0f9f6; color: #0f5240; padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 600; border: none; cursor: pointer; transition: all 0.3s;">Completed</button>
            <button onclick="filterTransactions('pending')" class="filter-btn" data-filter="pending" style="background: #f0f9f6; color: #0f5240; padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 600; border: none; cursor: pointer; transition: all 0.3s;">Pending</button>
          </div>
        </div>
        
        <div id="recent-transactions" style="display: flex; flex-direction: column; gap: 12px;">
          <p style="color: #64748b; text-align: center; padding: 40px 0;">Loading transactions...</p>
        </div>
      </div>

      <!-- Invoices -->
      <div style="background: white; padding: 32px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
          <div>
            <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 6px 0; display: flex; align-items: center; gap: 12px;">
              <i class="fas fa-file-invoice" style="color: #0f5240;"></i>
              Invoices
            </h3>
            <p style="color: #64748b; margin: 0; font-size: 14px;">Download and view your invoices</p>
          </div>
        </div>
        
        <div id="invoices-list">
          <div style="background: #f9fafb; padding: 40px; border-radius: 12px; text-align: center;">
            <i class="fas fa-file-invoice" style="font-size: 48px; color: #cbd5e1; margin-bottom: 16px;"></i>
            <p style="color: #64748b; margin: 0;">No invoices available</p>
          </div>
        </div>
      </div>
    </main>
  </div>
</div>

<!-- Payment Method Modal -->
<div id="payment-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); backdrop-filter: blur(4px); z-index: 1000; align-items: center; justify-content: center;">
  <div style="background: white; padding: 32px; border-radius: 16px; max-width: 500px; width: 90%; max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3); animation: modalSlideIn 0.3s ease-out;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
      <h3 style="font-size: 22px; font-weight: 700; color: #0b3d2e; margin: 0;">Add Payment Method</h3>
      <button onclick="closePaymentModal()" style="background: transparent; border: none; color: #64748b; cursor: pointer; font-size: 24px; padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; transition: all 0.3s;">
        <i class="fas fa-times"></i>
      </button>
    </div>
    
    <form id="payment-method-form" style="display: flex; flex-direction: column; gap: 20px;">
      <div>
        <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 8px; font-size: 14px;">Payment Type *</label>
        <select name="type" style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit; background: white;">
          <option value="card">Credit/Debit Card</option>
          <option value="paypal">PayPal</option>
          <option value="bank">Bank Transfer</option>
          <option value="crypto">Cryptocurrency</option>
        </select>
      </div>
      
      <div id="card-fields">
        <div style="margin-bottom: 20px;">
          <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 8px; font-size: 14px;">Card Number *</label>
          <input type="text" name="card_number" placeholder="1234 5678 9012 3456" style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit;">
        </div>
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
          <div>
            <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 8px; font-size: 14px;">Expiry *</label>
            <input type="text" name="expiry" placeholder="MM/YY" style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit;">
          </div>
          <div>
            <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 8px; font-size: 14px;">CVV *</label>
            <input type="text" name="cvv" placeholder="123" style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit;">
          </div>
        </div>
      </div>
      
      <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 16px; border-radius: 8px; border: 1px solid #d4ad31;">
        <p style="margin: 0; font-size: 13px; color: #64748b;">
          <i class="fas fa-shield-alt" style="color: #10b981;"></i>
          Your payment information is encrypted and secure. We never store your CVV.
        </p>
      </div>
      
      <div style="display: flex; gap: 12px; margin-top: 8px;">
        <button type="button" onclick="closePaymentModal()" style="flex: 1; background: white; color: #64748b; padding: 14px; border-radius: 10px; font-size: 15px; font-weight: 700; border: 2px solid #e5e7eb; cursor: pointer; transition: all 0.3s;">
          Cancel
        </button>
        <button type="submit" style="flex: 1; background: linear-gradient(135deg, #0f5240, #146651); color: white; padding: 14px; border-radius: 10px; font-size: 15px; font-weight: 700; border: none; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 12px rgba(15, 82, 64, 0.3);">
          <i class="fas fa-plus-circle"></i> Add Method
        </button>
      </div>
    </form>
  </div>
</div>

<style>
@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.filter-btn:hover {
  background: #0f5240 !important;
  color: white !important;
  transform: translateY(-1px);
}

.filter-btn.active {
  background: #0f5240 !important;
  color: white !important;
}

button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2) !important;
}

button:active {
  transform: translateY(0);
}

input:focus, select:focus {
  outline: none;
  border-color: #0f5240;
  box-shadow: 0 0 0 3px rgba(15, 82, 64, 0.1);
}
</style>

<script>
let allTransactions = [];
let currentFilter = 'all';

async function loadBillingData() {
  // Mock data for billing dashboard
  const billingData = {
    total_spent: 436.94,
    month_spent: 99.00,
    outstanding: 0.00,
    next_payment: 99.00,
    next_payment_date: 'Feb 28, 2026',
    transactions: [
      {
        id: 1,
        description: 'Family Membership - Monthly',
        amount: 99.00,
        date: new Date('2026-01-15').toISOString(),
        status: 'completed',
        type: 'subscription',
        method: 'Visa •••• 1234'
      },
      {
        id: 2,
        description: 'Baobab Fruit Powder (2x)',
        amount: 49.98,
        date: new Date('2026-01-20').toISOString(),
        status: 'completed',
        type: 'product',
        method: 'Visa •••• 1234'
      },
      {
        id: 3,
        description: 'Video Consultation - Dr. Amara',
        amount: 75.00,
        date: new Date('2026-01-22').toISOString(),
        status: 'completed',
        type: 'service',
        method: 'Visa •••• 1234'
      },
      {
        id: 4,
        description: 'Wellness Assessment Package',
        amount: 125.00,
        date: new Date('2026-01-10').toISOString(),
        status: 'completed',
        type: 'service',
        method: 'PayPal'
      },
      {
        id: 5,
        description: 'Herbal Tea Collection',
        amount: 34.99,
        date: new Date('2026-01-08').toISOString(),
        status: 'completed',
        type: 'product',
        method: 'Visa •••• 1234'
      },
      {
        id: 6,
        description: 'Pending Payment - Lab Tests',
        amount: 150.00,
        date: new Date('2026-01-27').toISOString(),
        status: 'pending',
        type: 'service',
        method: 'Processing'
      }
    ]
  };
  
  allTransactions = billingData.transactions;
  
  // Update summary cards
  document.getElementById('total-spent').textContent = `$${billingData.total_spent.toFixed(2)}`;
  document.getElementById('month-spent').textContent = `$${billingData.month_spent.toFixed(2)}`;
  document.getElementById('outstanding').textContent = `$${billingData.outstanding.toFixed(2)}`;
  document.getElementById('next-payment').textContent = `$${billingData.next_payment.toFixed(2)}`;
  document.getElementById('next-payment-date').textContent = billingData.next_payment_date;
  
  // Render transactions
  renderTransactions();
}

function renderTransactions() {
  const transactionsEl = document.getElementById('recent-transactions');
  
  const filtered = currentFilter === 'all' 
    ? allTransactions 
    : allTransactions.filter(txn => txn.status === currentFilter);
  
  if (filtered.length > 0) {
    transactionsEl.innerHTML = filtered.map(txn => {
      const statusColor = txn.status === 'completed' ? '#10b981' : txn.status === 'pending' ? '#f59e0b' : '#ef4444';
      const statusBg = txn.status === 'completed' ? '#d1fae5' : txn.status === 'pending' ? '#fef3c7' : '#fee2e2';
      const typeIcon = txn.type === 'subscription' ? 'crown' : txn.type === 'product' ? 'shopping-bag' : 'stethoscope';
      
      return `
        <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 20px; border-radius: 12px; display: flex; justify-content: space-between; align-items: center; gap: 16px; transition: all 0.3s; border: 1px solid #e5e7eb; flex-wrap: wrap;" onmouseover="this.style.borderColor='#d4ad31'; this.style.boxShadow='0 4px 12px rgba(212, 173, 49, 0.2)'" onmouseout="this.style.borderColor='#e5e7eb'; this.style.boxShadow='none'">
          <div style="display: flex; gap: 16px; align-items: center; flex: 1; min-width: 200px;">
            <div style="width: 48px; height: 48px; background: white; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);">
              <i class="fas fa-${typeIcon}" style="color: #0f5240; font-size: 20px;"></i>
            </div>
            <div>
              <div style="font-weight: 700; color: #0b3d2e; font-size: 15px; margin-bottom: 4px;">${txn.description}</div>
              <div style="font-size: 13px; color: #64748b; display: flex; align-items: center; gap: 8px;">
                <i class="far fa-calendar" style="color: #0f5240;"></i>
                ${new Date(txn.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                <span style="margin: 0 4px;">•</span>
                ${txn.method}
              </div>
            </div>
          </div>
          <div style="display: flex; align-items: center; gap: 16px;">
            <div style="text-align: right;">
              <div style="font-size: 20px; font-weight: 800; color: #0b3d2e; margin-bottom: 4px;">$${txn.amount.toFixed(2)}</div>
              <div style="background: ${statusBg}; color: ${statusColor}; padding: 4px 12px; border-radius: 12px; font-size: 11px; font-weight: 700; text-transform: uppercase;">
                ${txn.status}
              </div>
            </div>
            <button onclick="downloadReceipt(${txn.id})" style="background: white; border: 2px solid #e5e7eb; color: #64748b; width: 36px; height: 36px; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.3s;" title="Download Receipt">
              <i class="fas fa-download"></i>
            </button>
          </div>
        </div>
      `;
    }).join('');
  } else {
    transactionsEl.innerHTML = `
      <div style="background: #f9fafb; padding: 40px; border-radius: 12px; text-align: center;">
        <i class="fas fa-receipt" style="font-size: 48px; color: #cbd5e1; margin-bottom: 16px;"></i>
        <p style="color: #64748b; margin: 0;">No ${currentFilter === 'all' ? '' : currentFilter} transactions found</p>
      </div>
    `;
  }
}

function filterTransactions(filter) {
  currentFilter = filter;
  
  // Update button styles
  document.querySelectorAll('.filter-btn').forEach(btn => {
    if (btn.dataset.filter === filter) {
      btn.classList.add('active');
      btn.style.background = '#0f5240';
      btn.style.color = 'white';
    } else {
      btn.classList.remove('active');
      btn.style.background = '#f0f9f6';
      btn.style.color = '#0f5240';
    }
  });
  
  renderTransactions();
}

function addPaymentMethod() {
  const modal = document.getElementById('payment-modal');
  modal.style.display = 'flex';
}

function closePaymentModal() {
  const modal = document.getElementById('payment-modal');
  modal.style.display = 'none';
}

function downloadReceipt(transactionId) {
  alert(`Downloading receipt for transaction #${transactionId}...`);
}

function downloadStatement() {
  alert('Downloading your billing statement...');
}

document.getElementById('payment-method-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  const submitBtn = e.target.querySelector('button[type="submit"]');
  submitBtn.disabled = true;
  submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding...';
  
  // Simulate API call
  setTimeout(() => {
    alert('Payment method added successfully!');
    closePaymentModal();
    
    // Update payment methods display
    document.getElementById('payment-methods').innerHTML = `
      <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px;">
        <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 20px; border-radius: 12px; border: 2px solid #d4ad31; position: relative;">
          <div style="position: absolute; top: 12px; right: 12px; background: #10b981; color: white; padding: 4px 12px; border-radius: 12px; font-size: 11px; font-weight: 700; text-transform: uppercase;">
            Default
          </div>
          <div style="margin-bottom: 16px;">
            <i class="fas fa-credit-card" style="font-size: 32px; color: #0f5240;"></i>
          </div>
          <div style="font-weight: 700; color: #0b3d2e; font-size: 16px; margin-bottom: 6px;">•••• •••• •••• 1234</div>
          <div style="display: flex; justify-content: space-between; align-items: center; color: #64748b; font-size: 13px; margin-bottom: 16px;">
            <span>Expires 12/25</span>
            <span>Visa</span>
          </div>
          <div style="display: flex; gap: 8px;">
            <button onclick="editPaymentMethod()" style="flex: 1; background: white; color: #0f5240; padding: 8px; border-radius: 8px; font-size: 13px; font-weight: 600; border: 2px solid #0f5240; cursor: pointer; transition: all 0.3s;">
              Edit
            </button>
            <button onclick="removePaymentMethod()" style="flex: 1; background: white; color: #ef4444; padding: 8px; border-radius: 8px; font-size: 13px; font-weight: 600; border: 2px solid #ef4444; cursor: pointer; transition: all 0.3s;">
              Remove
            </button>
          </div>
        </div>
      </div>
    `;
    
    submitBtn.disabled = false;
    submitBtn.innerHTML = '<i class="fas fa-plus-circle"></i> Add Method';
  }, 1000);
});

function editPaymentMethod() {
  alert('Edit payment method feature coming soon!');
}

function removePaymentMethod() {
  if (confirm('Are you sure you want to remove this payment method?')) {
    alert('Payment method removed successfully!');
    document.getElementById('payment-methods').innerHTML = `
      <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 40px; border-radius: 12px; border: 2px dashed #d4ad31; text-align: center;">
        <i class="fas fa-credit-card" style="font-size: 48px; color: #d4ad31; margin-bottom: 16px;"></i>
        <p style="color: #64748b; margin: 0 0 16px 0; font-size: 15px;">No payment methods added yet</p>
        <button onclick="addPaymentMethod()" style="background: white; color: #0f5240; padding: 12px 24px; border-radius: 10px; font-size: 14px; font-weight: 700; border: 2px solid #0f5240; cursor: pointer; transition: all 0.3s;">
          Add Your First Payment Method
        </button>
      </div>
    `;
  }
}

async function processPayment(amount, description) {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/billing/process.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({
        amount: amount,
        description: description,
        payment_method: 'demo'
      })
    });
    
    const data = await response.json();
    
    if (data.success) {
      alert(`Payment of $${amount} processed successfully!`);
      loadBillingData();
    } else {
      alert(data.message || 'Payment failed');
    }
  } catch (error) {
    alert('Network error. Please try again.');
  }
}

// Initialize
loadBillingData();
</script>

<?php };
include __DIR__ . '/../../partials/layout.php';
?>