<?php
require_once __DIR__.'/includes/functions.php';
require_once __DIR__.'/includes/account-v281-ui.php';

mj291_payment_ensure_schema();
if (function_exists('mj295_wallet_ensure_schema')) { mj295_wallet_ensure_schema(); }
$u = require_user();
$userId = (int)$u['id'];
mj_require_user_feature('billing_payments', $userId, 'Billing & Payments is not enabled for your account.');
$pageTitle = 'Billing & Payments';
verify_csrf();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'create_invoice_wallet') {
            $batchId = mj292_create_invoice_draft($userId, $_POST);
            try {
                mj295_pay_invoice_by_wallet($batchId, $userId, trim((string)($_POST['payment_note'] ?? '')));
                flash('success', 'Invoice generated and paid by wallet credit. Wallet balance was deducted immediately, receipt generated, and selected services activated.');
                redirect('billing-payments.php?tab=receipts&batch_id='.$batchId);
            } catch (Throwable $walletPayError) {
                flash('error', 'Invoice generated, but wallet payment could not be completed: '.$walletPayError->getMessage());
                redirect('billing-payments.php?tab=invoices&pay_batch='.$batchId);
            }
        }
        if ($action === 'create_invoice_draft') {
            $batchId = mj292_create_invoice_draft($userId, $_POST);
            flash('success', 'Invoice generated. Please review it first, then upload payment proof or pay by wallet when ready.');
            redirect('billing-payments.php?tab=invoices&pay_batch='.$batchId);
        }
        if ($action === 'submit_invoice_payment') {
            $batchId = mj292_submit_invoice_payment((int)($_POST['batch_id'] ?? 0), $userId, $_POST);
            flash('success', 'Payment proof uploaded for this invoice. Admin will review before activation.');
            redirect('billing-payments.php?tab=proofs&batch_id='.$batchId);
        }
        if ($action === 'pay_invoice_wallet') {
            $batchId = (int)($_POST['batch_id'] ?? 0);
            mj295_pay_invoice_by_wallet($batchId, $userId, trim((string)($_POST['payment_note'] ?? '')));
            flash('success', 'Paid by wallet credit. Wallet balance was deducted immediately, receipt generated, and selected services activated.');
            redirect('billing-payments.php?tab=receipts&batch_id='.$batchId);
        }
        if ($action === 'create_wallet_topup_invoice') {
            $batchId = mj291_create_wallet_topup_invoice($userId, (float)($_POST['topup_amount'] ?? 0), trim((string)($_POST['topup_currency'] ?? (setting('wallet_default_currency', setting('listing_upgrade_currency','SGD') ?: 'SGD')))), trim((string)($_POST['topup_note'] ?? '')));
            flash('success', 'Wallet top-up invoice generated. Please pay and upload proof. Admin will approve before credit is added.');
            redirect('billing-payments.php?tab=invoices&pay_batch='.$batchId);
        }
        if ($action === 'add_cart_item') {
            mj2919_cart_add($userId, $_POST);
            flash('success', 'Item added to cart. Review your cart and generate invoice when ready.');
            redirect('billing-payments.php?tab=cart');
        }
        if ($action === 'remove_cart_item') {
            mj2919_cart_remove($userId, (int)($_POST['cart_id'] ?? 0));
            flash('success', 'Cart item removed.');
            redirect('billing-payments.php?tab=cart');
        }
        if ($action === 'clear_cart') {
            mj2919_cart_clear($userId);
            flash('success', 'Cart cleared.');
            redirect('billing-payments.php?tab=cart');
        }
        if ($action === 'create_cart_invoice') {
            $batchId = mj2919_create_invoice_from_cart($userId, $_POST);
            flash('success', 'Cart invoice generated. Please review and pay from Invoices & Pay.');
            redirect('billing-payments.php?tab=invoices&pay_batch='.$batchId);
        }
        if ($action === 'edit_invoice_items') {
            mj292_cancel_invoice_for_edit((int)($_POST['batch_id'] ?? 0), $userId);
            flash('success', 'Invoice reopened for editing. Please select the correct items again.');
            redirect('billing-payments.php?tab=pay_pending');
        }
        if ($action === 'reupload_batch_proof') {
            mj291_reupload_batch_proof((int)($_POST['batch_id'] ?? 0), $userId, $_POST);
            flash('success', 'New payment proof uploaded. Admin will review again.');
            redirect('billing-payments.php?tab=proofs');
        }
        if ($action === 'create_payment_batch') {
            // Backward compatibility for old forms: create invoice first instead of forcing proof immediately.
            $batchId = mj292_create_invoice_draft($userId, $_POST);
            flash('success', 'Invoice generated. Please review it first, then upload payment proof when ready.');
            redirect('billing-payments.php?tab=invoices&pay_batch='.$batchId);
        }
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
        redirect('billing-payments.php?tab='.rawurlencode((string)($_POST['return_tab'] ?? 'pay_pending')));
    }
}

$tabs = [
    'overview'=>'Overview',
    'cart'=>'Cart',
    'pay_pending'=>'Generate Invoice',
    'invoices'=>'Invoices & Pay',
    'proofs'=>'Payment Proofs',
    'receipts'=>'Receipts',
    'wallet'=>'Wallet',
    'requests'=>'Payment Requests',
    'refunds'=>'Refunds',
    'tax'=>'Tax / Billing Details',
    'methods'=>'Payment Methods'
];
if (!mj_user_feature_enabled('wallet', $userId)) { unset($tabs['wallet']); }
$tab = (string)($_GET['tab'] ?? 'overview');
$aliases = ['payment_proofs'=>'proofs','proof'=>'proofs','upload'=>'proofs','extra'=>'pay_pending','extra_slots'=>'pay_pending','requests'=>'pay_pending','pay'=>'invoices'];
if (isset($aliases[$tab])) { $tab = $aliases[$tab]; }
if (!isset($tabs[$tab])) { $tab = 'overview'; }

$currency = setting('listing_upgrade_currency','SGD') ?: 'SGD';
$wallet = function_exists('mj295_wallet_get') ? mj295_wallet_get($userId, $currency) : null;
$currency = (string)($wallet['currency_code'] ?? $currency);
$walletAvailable = (float)($wallet['available_balance'] ?? max(0, (float)($wallet['balance'] ?? 0) - (float)($wallet['held_amount'] ?? 0)));
$walletHeld = (float)($wallet['held_amount'] ?? 0);
$walletPaymentEnabled = function_exists('mj295_pay_invoice_by_wallet') && setting('wallet_payment_enabled','1') === '1' && mj_user_feature_enabled('wallet', $userId);
$walletTopupEnabled = function_exists('mj291_create_wallet_topup_invoice') && setting('wallet_topup_enabled','1') === '1' && mj_user_feature_enabled('wallet', $userId);
$walletTopupMin = max(0.01, (float)setting('wallet_topup_min_amount','1.00'));
$walletTopupMax = max($walletTopupMin, (float)setting('wallet_topup_max_amount','9999.00'));

$methods = in_array($tab, ['invoices','proofs','receipts','methods'], true) ? mj291_payment_methods() : [];
if ($tab === 'pay_pending') { $methods = []; }
$extraCurrency = setting('extra_slot_currency', $currency) ?: $currency;
$extraListingAmount = (float)setting('extra_listing_slot_charge_amount','5.00');
$extraCompanyAmount = (float)setting('extra_company_slot_charge_amount','5.00');
$extraDealAmount = (float)setting('extra_deal_slot_charge_amount','5.00');
$dealRenewalAmount = (float)setting('deal_renewal_charge_amount','5.00');
$extraMin = max(1, (int)setting('extra_slot_min_qty','1'));
$extraMax = max($extraMin, (int)setting('extra_slot_max_qty','100'));
$taxEnabled = setting('payment_cart_tax_enabled', setting('billing_tax_enabled','0')) === '1';
$taxLabel = setting('payment_cart_tax_label', setting('billing_tax_label','GST/VAT')) ?: 'GST/VAT';
$taxRate = $taxEnabled ? (float)setting('payment_cart_default_tax_rate', setting('billing_default_tax_rate','0')) : 0;

// v2.9.3: lazy-load only the data needed for the selected tab. This keeps the account page fast.
$summary = function_exists('mj293_user_billing_summary') ? mj293_user_billing_summary($userId) : [];
$invoiceCreated = (int)($summary['invoice_created'] ?? 0);
$invoiceCreatedAmount = (float)($summary['invoice_created_amount'] ?? 0);
$pendingReview = (int)($summary['pending_review'] ?? 0);
$pendingAmount = (float)($summary['pending_amount'] ?? 0);
$uploadedProofs = (int)($summary['uploaded_proofs'] ?? 0);
$paidCount = (int)($summary['paid_count'] ?? 0);

$pendingItems = [];
$batches = [];
$batchItems = [];
$invoices = [];
$receipts = [];
$refunds = [];
$walletTx = [];
$cartItems = [];
$cartTotals = ['count'=>0,'subtotal'=>0,'tax'=>0,'total'=>0,'currency'=>$currency];
$userDealsForCart = [];

if ($tab === 'pay_pending') {
    $pendingItems = mj291_pending_upgrade_items($userId);
}

if (in_array($tab, ['overview','proofs'], true)) {
    try { $batches = table_exists('mj_payment_batches') ? all_rows('SELECT * FROM mj_payment_batches WHERE user_id=? ORDER BY id DESC LIMIT '.($tab === 'overview' ? 8 : 80), [$userId]) : []; } catch (Throwable $e) { $batches = []; }
}

if ($tab === 'invoices') {
    try { $invoices = table_exists('mj_invoices') ? all_rows('SELECT i.*, b.batch_no, b.id batch_id, b.status batch_status, b.proof_path batch_proof_path, b.payment_method batch_payment_method, b.reference_no batch_reference_no FROM mj_invoices i LEFT JOIN mj_payment_batches b ON b.invoice_id=i.id WHERE i.user_id=? ORDER BY i.id DESC LIMIT 80', [$userId]) : []; } catch (Throwable $e) { $invoices = []; }
    if ($invoices) {
        try {
            $bids = [];
            foreach ($invoices as $inv) { if (!empty($inv['batch_id'])) { $bids[] = (int)$inv['batch_id']; } }
            if ($bids && table_exists('mj_payment_batches')) {
                $ph = implode(',', array_fill(0, count($bids), '?'));
                foreach (all_rows('SELECT * FROM mj_payment_batches WHERE id IN ('.$ph.')', $bids) as $bb) { $batches[] = $bb; }
            }
        } catch (Throwable $e) {}
    }
}

if ($batches && table_exists('mj_payment_batch_items')) {
    try {
        $ids = array_values(array_unique(array_map(fn($b)=>(int)$b['id'], $batches)));
        if ($ids) {
            $ph = implode(',', array_fill(0, count($ids), '?'));
            foreach (all_rows('SELECT * FROM mj_payment_batch_items WHERE batch_id IN ('.$ph.') ORDER BY id ASC', $ids) as $it) { $batchItems[(int)$it['batch_id']][] = $it; }
        }
    } catch (Throwable $e) {}
}

if ($tab === 'receipts') {
    try { $receipts = table_exists('mj_receipts') ? all_rows('SELECT * FROM mj_receipts WHERE user_id=? ORDER BY id DESC LIMIT 50', [$userId]) : []; } catch (Throwable $e) { $receipts = []; }
}
if ($tab === 'refunds') {
    try { $refunds = table_exists('mj_refund_requests') ? all_rows('SELECT * FROM mj_refund_requests WHERE user_id=? ORDER BY id DESC LIMIT 30', [$userId]) : []; } catch (Throwable $e) { $refunds = []; }
}
if ($tab === 'wallet') {
    try {
        if (table_exists('mj_wallet_transactions')) {
            $walletWhere = mj_column_exists('mj_wallet_transactions', 'user_id') ? 'user_id=?' : 'wallet_id=?';
            $walletParam = mj_column_exists('mj_wallet_transactions', 'user_id') ? $userId : (int)($wallet['id'] ?? 0);
            $walletTx = all_rows('SELECT * FROM mj_wallet_transactions WHERE '.$walletWhere.' ORDER BY id DESC LIMIT 30', [$walletParam]);
        }
    } catch (Throwable $e) { $walletTx = []; }
}

if ($tab === 'cart') {
    try {
        mj2919_cart_ensure_schema();
        $cartItems = mj2919_cart_items($userId, 'cart');
        $cartTotals = mj2919_cart_totals($cartItems, $currency);
        $userDealsForCart = mj2919_user_deal_options($userId);
    } catch (Throwable $e) { $cartItems = []; $userDealsForCart = []; }
}

$pendingItemTotal = 0.0;
foreach ($pendingItems as $it) { $pendingItemTotal += (float)($it['total_amount'] ?? 0); }

$methodLabels = [];
foreach ($methods as $mk=>$m) { $methodLabels[(string)$mk] = (string)($m['label'] ?? $mk); }

function mj291_user_proof_href(string $path): string {
    $path = trim($path);
    if ($path === '' || strtoupper($path) === 'WALLET') { return ''; }
    if (preg_match('/^https?:\/\//i', $path)) { return $path; }
    return base_url(ltrim($path, '/'));
}
function mj292_batch_items_html(array $items, string $currency='SGD'): string {
    if (!$items) { return '<span class="text-muted">No items</span>'; }
    $html = '<div class="mj-invoice-items">';
    foreach ($items as $it) {
        $html .= '<div class="mj-invoice-item-row"><span><b>'.e($it['item_label'] ?? $it['item_type']).'</b><small>'.e($it['item_description'] ?? '').'</small></span><span>× '.e($it['quantity'] ?? 1).'</span><strong>'.money((float)($it['total_amount'] ?? 0),(string)($it['currency_code'] ?? $currency)).'</strong></div>';
    }
    $html .= '</div>';
    return $html;
}
function mj292_is_invoice_payable(array $b): bool {
    $s = strtolower((string)($b['status'] ?? ''));
    return in_array($s, ['invoice_created','unpaid','draft'], true) && trim((string)($b['proof_path'] ?? '')) === '';
}

if (!function_exists('mj301_billing_status_value')) {
function mj301_billing_status_value(array $row, string $context='payment'): string {
    $candidates = [];
    if ($context === 'receipt') {
        $candidates = [$row['status'] ?? '', $row['receipt_status'] ?? '', $row['batch_status'] ?? '', $row['invoice_status'] ?? '', 'paid'];
    } elseif ($context === 'invoice') {
        $candidates = [$row['status'] ?? '', $row['invoice_status'] ?? '', $row['batch_status'] ?? ''];
        $total = (float)($row['total_amount'] ?? 0);
        $paid = (float)($row['paid_amount'] ?? 0);
        if ($total > 0 && $paid + 0.001 >= $total) { $candidates[] = 'paid'; }
        if (trim((string)($row['batch_proof_path'] ?? $row['proof_path'] ?? '')) !== '') { $candidates[] = 'pending_review'; }
        $candidates[] = 'invoice_created';
    } else {
        $candidates = [$row['status'] ?? '', $row['batch_status'] ?? '', $row['invoice_status'] ?? ''];
        $proof = strtoupper(trim((string)($row['proof_path'] ?? $row['batch_proof_path'] ?? '')));
        if ($proof === 'WALLET') { $candidates[] = 'wallet_paid'; }
        if ($proof !== '') { $candidates[] = 'pending_review'; }
        $candidates[] = 'invoice_created';
    }
    foreach ($candidates as $candidate) {
        $v = trim((string)$candidate);
        if ($v !== '') { return $v; }
    }
    return $context === 'receipt' ? 'paid' : 'pending';
}
}

include __DIR__.'/includes/header.php';
?>
<div class="container-fluid mj-account-wide py-5"><div class="sidebar-layout"><?php include __DIR__.'/includes/account-sidebar.php'; ?><section>
  <div class="mj-page-hero rounded-4 mb-4"><div class="container-fluid px-0"><span class="mj-badge mb-2"><i class="bi bi-credit-card-2-front"></i> Billing & Payments</span><h1 class="fw-bold mb-1">Billing & Payments</h1><p class="text-muted mb-0">Generate invoice first, review/edit it, then upload one payment proof for all selected items.</p></div></div>
  <?php show_flash(); ?>
  <?php mj_v281_tabs($tabs,$tab,'billing-payments.php'); ?>

  <?php if($tab==='overview'): ?>
    <div class="row g-4 mb-4">
      <div class="col-md-3"><div class="stat"><b><?=money((float)($wallet['balance']??0),$currency)?></b><br><span class="muted">Wallet Balance</span><br><small class="text-muted">Available: <?=money($walletAvailable,$currency)?><?php if($walletHeld>0): ?> · Held: <?=money($walletHeld,$currency)?><?php endif; ?></small></div></div>
      <div class="col-md-3"><div class="stat"><b><?=e($invoiceCreated)?></b><br><span class="muted">Generated Invoices</span></div></div>
      <div class="col-md-3"><div class="stat"><b><?=e($pendingReview)?></b><br><span class="muted">Pending Admin Review</span></div></div>
      <div class="col-md-3"><div class="stat"><b><?=money($invoiceCreatedAmount + $pendingAmount,$currency)?></b><br><span class="muted">Open Amount</span></div></div>
    </div>
    <div class="alert alert-info rounded-4 mb-4"><b>New flow:</b> Generate invoice first. Before uploading proof, you can edit selected items. After payment, upload one proof and admin will approve activation.</div>
    <div class="card card-body border-0 rounded-4 shadow-sm mb-4">
      <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3"><h3 class="h5 fw-bold mb-0"><i class="bi bi-list-check me-1"></i>Payment Status Overview</h3><a class="btn btn-sm btn-outline-primary rounded-pill" href="<?=base_url('billing-payments.php?tab=proofs')?>">View all statuses</a></div>
      <div class="row g-3">
        <div class="col-md-3"><div class="mj-status-tile"><span>Generated invoices</span><b><?=e($invoiceCreated)?></b><small><?=money($invoiceCreatedAmount,$currency)?> open before proof</small></div></div>
        <div class="col-md-3"><div class="mj-status-tile"><span>Proof uploaded</span><b><?=e($uploadedProofs)?></b><small>Waiting / reviewed proof records</small></div></div>
        <div class="col-md-3"><div class="mj-status-tile"><span>Pending admin review</span><b><?=e($pendingReview)?></b><small><?=money($pendingAmount,$currency)?> waiting approval</small></div></div>
        <div class="col-md-3"><div class="mj-status-tile"><span>Paid / receipts</span><b><?=e($paidCount)?></b><small>Approved or wallet-paid invoices</small></div></div>
      </div>
    </div>
    <div class="row g-4 mb-4">
      <div class="col-lg-7"><div class="card card-body border-0 rounded-4 shadow-sm h-100"><div class="d-flex justify-content-between align-items-center mb-3"><h3 class="h5 fw-bold mb-0">Latest Invoices</h3><a class="btn btn-sm btn-outline-primary rounded-pill" href="<?=base_url('billing-payments.php?tab=invoices')?>">View all</a></div><?php if(!$batches): mj_v281_empty('No invoice yet','Generate invoice from pending items. Payment proof can be uploaded after you review it.','bi-receipt'); else: ?><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Invoice</th><th>Items</th><th>Status</th><th class="text-end">Total</th></tr></thead><tbody><?php foreach(array_slice($batches,0,5) as $b): ?><tr><td><b><?=e($b['batch_no'] ?: ('PAY-'.$b['id']))?></b><br><small><?=e($b['created_at']??'')?></small></td><td><?=e(count($batchItems[(int)$b['id']] ?? []))?> item(s)</td><td><?=mj291_status_badge(mj301_billing_status_value($b,'payment'))?></td><td class="text-end fw-bold"><?=money((float)$b['total_amount'], (string)$b['currency_code'])?></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?></div></div>
      <div class="col-lg-5"><div class="card card-body border-0 rounded-4 shadow-sm h-100"><h3 class="h5 fw-bold">Quick Actions</h3><div class="d-grid gap-2"><a class="btn btn-primary rounded-pill" href="<?=base_url('billing-payments.php?tab=pay_pending')?>"><i class="bi bi-file-earmark-plus me-1"></i> Generate Invoice</a><a class="btn btn-outline-primary rounded-pill" href="<?=base_url('billing-payments.php?tab=invoices')?>"><i class="bi bi-receipt me-1"></i> Pay Existing Invoice</a><a class="btn btn-outline-secondary rounded-pill" href="<?=base_url('billing-payments.php?tab=proofs')?>"><i class="bi bi-upload me-1"></i> Payment Proof Status</a></div></div></div>
    </div>
    <?php mj_v281_feature_grid([['bi-file-earmark-plus','Invoice First','Create invoice without payment proof.'],['bi-pencil-square','Edit Before Pay','Change selected items before uploading proof.'],['bi-plus-square','Multiple Extra Slots','Choose listing/company slot quantity.'],['bi-upload','One Proof Upload','Upload one proof for all invoice items.'],['bi-shield-check','Admin Approval','Nothing activates until admin approves.'],['bi-receipt','Receipt Generated','Receipt appears after approval.']]); ?>

  <?php elseif($tab==='cart'): ?>
    <div class="alert alert-info rounded-4"><b>Cart rule:</b> This cart is only for seller/user payments to admin such as extra slots and deal promotions. Customers cannot pay sellers through MJ Marketplace.</div>
    <div class="row g-4">
      <div class="col-xl-8">
        <div class="card card-body border-0 rounded-4 shadow-sm mb-4">
          <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
            <div><h3 class="h5 fw-bold mb-1"><i class="bi bi-cart3 me-1"></i>My Service Cart</h3><p class="text-muted mb-0">Add admin-charge services, then generate one invoice.</p></div>
            <?php if($cartItems): ?><form method="post" onsubmit="return confirm('Clear all items from your cart?');"><?=csrf_input()?><input type="hidden" name="action" value="clear_cart"><button class="btn btn-sm btn-outline-danger rounded-pill">Clear cart</button></form><?php endif; ?>
          </div>
          <?php if(!$cartItems): ?>
            <?php mj_v281_empty('Your cart is empty','Add extra slots or promote a deal. This cart does not accept customer-to-seller payments.','bi-cart'); ?>
          <?php else: ?>
            <form method="post" id="mjCreateCartInvoiceForm"><?=csrf_input()?><input type="hidden" name="action" value="create_cart_invoice"><input type="hidden" name="return_tab" value="cart"><input type="hidden" name="from_cart_form" value="1">
              <div class="mj-cart-list mb-3">
              <?php foreach($cartItems as $ci): ?>
                <label class="mj-cart-item">
                  <input class="mj-cart-check" type="checkbox" name="cart_ids[]" value="<?=e($ci['id'])?>" data-amount="<?=e($ci['total_amount'])?>" data-currency="<?=e($ci['currency_code'])?>" checked>
                  <span class="mj-cart-main"><b><?=e($ci['title'])?></b><small><?=e($ci['description'])?> · Qty <?=e($ci['quantity'])?></small></span>
                  <span class="mj-cart-price"><?=money((float)$ci['total_amount'], (string)$ci['currency_code'])?></span>
                </label>
              <?php endforeach; ?>
              </div>
              <textarea class="form-control rounded-4 mb-3" name="payment_note" rows="2" placeholder="Optional note to admin"></textarea>
              <div class="d-flex gap-2 flex-wrap justify-content-end">
                <a class="btn btn-outline-secondary rounded-pill" href="<?=base_url('billing-payments.php?tab=invoices')?>"><i class="bi bi-receipt me-1"></i>View invoices</a>
                <button class="btn btn-primary rounded-pill"><i class="bi bi-file-earmark-plus me-1"></i>Generate Invoice from Cart</button>
              </div>
            </form>
          <?php endif; ?>
        </div>
      </div>
      <div class="col-xl-4">
        <div class="card card-body border-0 rounded-4 shadow-sm mb-4 mj-checkout-summary">
          <h3 class="h6 fw-bold">Cart Summary</h3>
          <div class="d-flex justify-content-between"><span>Items</span><b><?=e($cartTotals['count'] ?? 0)?></b></div>
          <div class="d-flex justify-content-between"><span>Subtotal</span><b><?=money((float)($cartTotals['subtotal']??0),(string)($cartTotals['currency']??$currency))?></b></div>
          <?php if(($cartTotals['tax']??0)>0): ?><div class="d-flex justify-content-between"><span><?=e($taxLabel)?></span><b><?=money((float)$cartTotals['tax'],(string)$cartTotals['currency'])?></b></div><?php endif; ?>
          <hr><div class="d-flex justify-content-between h5"><span>Total</span><b><?=money((float)($cartTotals['total']??0),(string)($cartTotals['currency']??$currency))?></b></div>
          <small class="text-muted">After invoice generation, pay by wallet for instant approval or upload manual proof for admin approval.</small>
        </div>
        <div class="card card-body border-0 rounded-4 shadow-sm">
          <h3 class="h6 fw-bold mb-3"><i class="bi bi-plus-circle me-1"></i>Add to Cart</h3>
          <form method="post" class="mb-3"><?=csrf_input()?><input type="hidden" name="action" value="add_cart_item"><input type="hidden" name="return_tab" value="cart"><input type="hidden" name="cart_item_type" value="extra_listing_slot"><label class="form-label small">Extra listing slots</label><div class="input-group"><input class="form-control" type="number" min="<?=$extraMin?>" max="<?=$extraMax?>" name="quantity" value="1"><button class="btn btn-outline-primary">Add</button></div><small class="text-muted"><?=money($extraListingAmount,$extraCurrency)?> per slot</small></form>
          <form method="post" class="mb-3"><?=csrf_input()?><input type="hidden" name="action" value="add_cart_item"><input type="hidden" name="return_tab" value="cart"><input type="hidden" name="cart_item_type" value="extra_company_slot"><label class="form-label small">Extra company slots</label><div class="input-group"><input class="form-control" type="number" min="<?=$extraMin?>" max="<?=$extraMax?>" name="quantity" value="1"><button class="btn btn-outline-primary">Add</button></div><small class="text-muted"><?=money($extraCompanyAmount,$extraCurrency)?> per slot</small></form>
          <form method="post" class="mb-3"><?=csrf_input()?><input type="hidden" name="action" value="add_cart_item"><input type="hidden" name="return_tab" value="cart"><input type="hidden" name="cart_item_type" value="extra_deal_slot"><label class="form-label small">Extra deal slots</label><div class="input-group"><input class="form-control" type="number" min="<?=$extraMin?>" max="<?=$extraMax?>" name="quantity" value="1"><button class="btn btn-outline-primary">Add</button></div><small class="text-muted"><?=money($extraDealAmount,$extraCurrency)?> per slot</small></form>
          <?php if($userDealsForCart): ?>
          <form method="post" class="border-top pt-3"><?=csrf_input()?><input type="hidden" name="action" value="add_cart_item"><input type="hidden" name="return_tab" value="cart"><label class="form-label small">Promote one of my deals</label><select class="form-select mb-2" name="deal_id" required><?php foreach($userDealsForCart as $d): ?><option value="<?=e($d['id'])?>">#<?=e($d['id'])?> - <?=e($d['title'])?></option><?php endforeach; ?></select><div class="row g-2"><div class="col-7"><select class="form-select" name="cart_item_type"><option value="deal_featured">Featured Deal</option><option value="deal_sponsored">Sponsored Deal</option><option value="deal_homepage">Homepage Deal</option><option value="deal_bump">Bump Deal</option><option value="deal_urgent">Urgent Label</option><option value="deal_renewal">Renew Deal</option></select></div><div class="col-5"><input class="form-control" type="number" min="1" max="<?=e(setting('deal_promotion_max_days','90'))?>" name="duration_days" value="<?=e(setting('deal_promotion_default_days','7'))?>"></div></div><button class="btn btn-outline-primary rounded-pill w-100 mt-2">Add deal promotion</button></form>
          <?php else: ?>
          <div class="border-top pt-3"><small class="text-muted">Create a deal first to add featured/sponsored deal promotion to cart.</small></div>
          <?php endif; ?>
        </div>
      </div>
    </div>

  <?php elseif($tab==='pay_pending'): ?>
    <div class="alert alert-warning rounded-4"><b>Important:</b> This step only generates the invoice. Payment method and proof upload happen after you review the invoice.</div>
    <form method="post" id="mjPaymentCartForm">
      <?=csrf_input()?><input type="hidden" name="return_tab" value="pay_pending">
      <div class="row g-4">
        <div class="col-xl-8 col-lg-8">
          <div class="card card-body border-0 rounded-4 shadow-sm mb-4">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3"><div><h3 class="h5 fw-bold mb-1">1. Select Pending Items</h3><p class="text-muted mb-0">Tick one or more items. They will be combined into one invoice.</p></div><?php if($pendingItems): ?><button type="button" class="btn btn-sm btn-outline-primary rounded-pill" id="mjSelectAllPayItems">Select all</button><?php endif; ?></div>
            <?php if(!$pendingItems): ?>
              <?php mj_v281_empty('No pending upgrade items','Renewal, sponsor, featured, extra slot or admin payment requests will appear here when payment is required.','bi-cart'); ?>
            <?php else: ?>
              <div class="mj-cart-list">
                <?php foreach($pendingItems as $idx=>$it): $key=(string)$it['item_type'].':'.(int)$it['item_id']; $qty=max(1,(int)($it['quantity']??1)); $total=(float)($it['total_amount']??0); $cur=(string)($it['currency_code']??$currency); ?>
                  <label class="mj-cart-item">
                    <input class="mj-cart-check" type="checkbox" name="pay_items[]" value="<?=e($key)?>" data-amount="<?=e($total)?>" data-currency="<?=e($cur)?>">
                    <span class="mj-cart-main"><b><?=e($it['item_label']??'Payment Item')?></b><small><?=e($it['item_title']??'')?> <?= $qty>1 ? ' · Qty '.$qty : '' ?></small></span>
                    <span class="mj-cart-price"><?=money($total,$cur)?></span>
                  </label>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>

          <div class="card card-body border-0 rounded-4 shadow-sm mb-4">
            <h3 class="h5 fw-bold mb-1">2. Add Extra Slots if needed</h3><p class="text-muted">Buy more than one listing/company slot in the same invoice.</p>
            <div class="row g-3">
              <?php if(mj_user_feature_enabled('extra_listing_slots',$userId)): ?>
              <div class="col-md-6"><div class="mj-slot-box"><label class="d-flex gap-2 align-items-start"><input class="form-check-input mt-1 mj-extra-check" type="checkbox" name="include_extra_listing" value="1" data-target="extraListingQty"><span><b>Extra Listing Slots</b><br><small><?=money($extraListingAmount,$extraCurrency)?> per slot</small></span></label><div class="input-group mt-3"><button class="btn btn-outline-secondary mj-qty-minus" type="button" data-target="extraListingQty">-</button><input id="extraListingQty" class="form-control text-center mj-extra-qty" type="number" min="<?=$extraMin?>" max="<?=$extraMax?>" name="extra_listing_qty" value="1" data-unit="<?=e($extraListingAmount)?>" data-currency="<?=e($extraCurrency)?>"><button class="btn btn-outline-secondary mj-qty-plus" type="button" data-target="extraListingQty">+</button></div></div></div>
              <?php endif; ?>
              <?php if(mj_user_feature_enabled('extra_company_slots',$userId)): ?>
              <div class="col-md-6"><div class="mj-slot-box"><label class="d-flex gap-2 align-items-start"><input class="form-check-input mt-1 mj-extra-check" type="checkbox" name="include_extra_company" value="1" data-target="extraCompanyQty"><span><b>Extra Company Slots</b><br><small><?=money($extraCompanyAmount,$extraCurrency)?> per slot</small></span></label><div class="input-group mt-3"><button class="btn btn-outline-secondary mj-qty-minus" type="button" data-target="extraCompanyQty">-</button><input id="extraCompanyQty" class="form-control text-center mj-extra-qty" type="number" min="<?=$extraMin?>" max="<?=$extraMax?>" name="extra_company_qty" value="1" data-unit="<?=e($extraCompanyAmount)?>" data-currency="<?=e($extraCurrency)?>"><button class="btn btn-outline-secondary mj-qty-plus" type="button" data-target="extraCompanyQty">+</button></div></div></div>
              <?php endif; ?>
            </div>
          </div>

          <div class="card card-body border-0 rounded-4 shadow-sm">
            <h3 class="h5 fw-bold mb-2">3. Optional invoice note</h3>
            <textarea class="form-control" name="payment_note" rows="3" placeholder="Optional note to admin"></textarea>
          </div>
        </div>
        <div class="col-xl-4 col-lg-4"><div class="mj-checkout-summary sticky-top" style="top:90px"><div class="card card-body border-0 rounded-4 shadow-sm"><h3 class="h5 fw-bold">Invoice Summary</h3><div class="d-flex justify-content-between"><span>Selected items</span><b id="mjCartCount">0</b></div><div class="d-flex justify-content-between"><span>Subtotal</span><b id="mjCartSubtotal"><?=money(0,$currency)?></b></div><?php if($taxEnabled): ?><div class="d-flex justify-content-between"><span><?=e($taxLabel)?> (<?=e($taxRate)?>%)</span><b id="mjCartTax"><?=money(0,$currency)?></b></div><?php endif; ?><hr><div class="d-flex justify-content-between align-items-center"><span class="fw-bold">Total</span><b class="display-6" id="mjCartTotal"><?=money(0,$currency)?></b></div><button type="submit" name="action" value="create_invoice_draft" class="btn btn-primary rounded-pill w-100 mt-3"><i class="bi bi-file-earmark-plus me-1"></i> Generate Invoice</button><?php if($walletPaymentEnabled): ?><div class="mj-wallet-summary mt-3"><div class="d-flex justify-content-between"><span><i class="bi bi-wallet2 me-1"></i>Wallet available</span><b><?=money($walletAvailable,$currency)?></b></div><button type="submit" name="action" value="create_invoice_wallet" class="btn btn-success rounded-pill w-100 mt-2" onclick="return confirm('Generate this invoice and pay using wallet credit? Your wallet balance will be deducted immediately and eligible services will activate now.');"><i class="bi bi-wallet2 me-1"></i> Generate & Pay by Wallet</button><small class="d-block text-muted mt-2">Works only when your available wallet balance covers the full invoice total. Full wallet payments approve immediately.</small></div><?php endif; ?><p class="text-muted small mb-0 mt-3">No proof required to generate invoice. You can review and edit before payment.</p></div></div></div>
      </div>
    </form>

  <?php elseif($tab==='invoices'): ?>
    <div class="card card-body border-0 rounded-4 shadow-sm"><div class="d-flex justify-content-between flex-wrap gap-2 align-items-center mb-3"><div><h3 class="h5 fw-bold mb-1">Invoices & Payment</h3><p class="text-muted mb-0">Review invoice first. You can edit items before uploading proof.</p></div><a class="btn btn-outline-primary rounded-pill" href="<?=base_url('billing-payments.php?tab=pay_pending')?>"><i class="bi bi-plus-circle me-1"></i> Generate New Invoice</a></div>
      <?php if(!$invoices): mj_v281_empty('No invoices','Generate invoice first from pending items, then upload payment proof.','bi-file-earmark-text'); else: ?>
        <div class="mj-invoice-stack">
        <?php foreach($invoices as $inv): $bid=(int)($inv['batch_id'] ?? 0); $bitems=$batchItems[$bid] ?? []; $containsWalletTopup=false; foreach($bitems as $__it){ if((string)($__it['item_type']??'')==='wallet_topup'){ $containsWalletTopup=true; break; } } $proofHref=mj291_user_proof_href((string)($inv['batch_proof_path'] ?: ($inv['proof_path'] ?? ''))); $payableBatch = null; foreach($batches as $bb){ if((int)$bb['id']===$bid){$payableBatch=$bb; break;} } $canPay = $payableBatch && mj292_is_invoice_payable($payableBatch); $invoiceCurrency=(string)($inv['currency_code']??$currency); $invoiceWallet=function_exists('mj295_wallet_get') ? mj295_wallet_get($userId,$invoiceCurrency) : $wallet; $invoiceWalletAvailable=(float)($invoiceWallet['available_balance'] ?? max(0,(float)($invoiceWallet['balance']??0)-(float)($invoiceWallet['held_amount']??0))); ?>
          <div class="mj-invoice-card" id="invoice-<?=e((int)$inv['id'])?>">
            <div class="mj-invoice-head"><div><b><?=e($inv['invoice_no'] ?: ('INV-'.$inv['id']))?></b><small><?=e($inv['created_at']??'')?> · <?=e($inv['title']??'Marketplace payment checkout')?></small><div class="mt-2"><a class="btn btn-sm btn-outline-secondary rounded-pill" target="_blank" href="<?=base_url('invoice-print.php?invoice_id='.(int)$inv['id'])?>"><i class="bi bi-printer me-1"></i>Print Invoice</a></div></div><div class="text-end"><?=mj291_status_badge(mj301_billing_status_value($inv,'invoice'))?><div class="fw-bold mt-1"><?=money((float)($inv['total_amount']??0),(string)($inv['currency_code']??$currency))?></div></div></div>
            <?=mj292_batch_items_html($bitems,(string)($inv['currency_code']??$currency))?>
            <?php if($canPay): ?>
              <div class="alert alert-light border rounded-4 mt-3 mb-3"><b>Before payment:</b> Check all items and amount. Need to change anything? Click <b>Edit Items</b> before uploading proof.</div>
              <div class="row g-3">
                <div class="col-lg-8">
                  <?php $invoiceTotalForWallet = (float)($inv['total_amount'] ?? 0); ?>
                  <?php if($walletPaymentEnabled && !$containsWalletTopup): ?>
                    <div class="mj-wallet-pay-box mb-3">
                      <div class="d-flex flex-wrap justify-content-between align-items-center gap-2"><div><b><i class="bi bi-wallet2 me-1"></i> Pay using Wallet Credit</b><br><small class="text-muted">Available wallet balance: <?=money($invoiceWalletAvailable,$invoiceCurrency)?>. Full wallet payment approves immediately and deducts your wallet balance now.</small></div><div class="fw-bold"><?=money($invoiceWalletAvailable,$invoiceCurrency)?></div></div>
                      <?php if($invoiceWalletAvailable + 0.00001 >= $invoiceTotalForWallet): ?>
                        <form method="post" class="mt-2" onsubmit="return confirm('Use wallet balance for this invoice? Your wallet balance will be deducted immediately and eligible services will activate now.');"><?=csrf_input()?><input type="hidden" name="action" value="pay_invoice_wallet"><input type="hidden" name="return_tab" value="invoices"><input type="hidden" name="batch_id" value="<?=e($bid)?>"><textarea class="form-control mb-2" name="payment_note" rows="2" placeholder="Optional note to admin"></textarea><button class="btn btn-success rounded-pill"><i class="bi bi-wallet2 me-1"></i> Pay by Wallet Credit</button></form>
                      <?php else: $walletShort = max(0, $invoiceTotalForWallet - $invoiceWalletAvailable); ?>
                        <div class="alert alert-light border mt-2 mb-0 small">Wallet balance is short by <b><?=money($walletShort,$invoiceCurrency)?></b>. Upload payment proof below, or <a href="<?=base_url('billing-payments.php?tab=wallet')?>">top up wallet</a>.</div>
                      <?php endif; ?>
                    </div>
                  <?php endif; ?>
                  <?php if($containsWalletTopup): ?><div class="alert alert-info rounded-4"><b>Wallet top-up:</b> Please pay using one of the admin-enabled payment methods below and upload proof. Wallet credit is added only after admin approval.</div><?php endif; ?>
                  <?php if(!$methods): mj_v281_empty('No active manual payment method','Wallet payment is available for normal invoices when your wallet balance covers the full amount. Wallet top-up needs a manual payment method enabled by admin.','bi-credit-card'); else: ?>
                  <form method="post" enctype="multipart/form-data" class="mj-pay-invoice-form">
                    <?=csrf_input()?><input type="hidden" name="action" value="submit_invoice_payment"><input type="hidden" name="return_tab" value="invoices"><input type="hidden" name="batch_id" value="<?=e($bid)?>">
                    <h4 class="h6 fw-bold mb-2">Or upload manual payment proof</h4>
                    <div class="row g-3 mb-3"><?php foreach($methods as $mk=>$m): ?><div class="col-md-6"><label class="mj-pay-method-option"><input type="radio" name="payment_method" value="<?=e($mk)?>" required><span><b><i class="bi <?=e($m['icon'] ?? 'bi-credit-card')?> me-1"></i><?=e($m['label'] ?? $mk)?></b><small><?=nl2br(e($m['details'] ?? ''))?></small></span></label></div><?php endforeach; ?></div>
                    <div class="row g-3"><div class="col-md-6"><label class="form-label">Payment / transaction reference</label><input class="form-control" name="payment_reference" maxlength="190" required placeholder="Receipt no, transfer no, PayNow ref..."></div><div class="col-md-6"><label class="form-label">Upload one proof for this invoice</label><input class="form-control" type="file" name="payment_proof" accept=".jpg,.jpeg,.png,.webp,.pdf" required></div><div class="col-12"><label class="form-label">Note to admin</label><textarea class="form-control" name="payment_note" rows="2" placeholder="Optional note"></textarea></div><div class="col-12"><button class="btn btn-primary rounded-pill"><i class="bi bi-upload me-1"></i> Submit Payment Proof</button></div></div>
                  </form>
                  <?php endif; ?>
                </div>
                <div class="col-lg-4"><div class="mj-edit-invoice-box"><h4 class="h6 fw-bold">Need to edit?</h4><p class="text-muted small">This will cancel this unpaid invoice and return all items to the cart.</p><form method="post" onsubmit="return confirm('Cancel this unpaid invoice and edit selected items?');"><?=csrf_input()?><input type="hidden" name="action" value="edit_invoice_items"><input type="hidden" name="return_tab" value="invoices"><input type="hidden" name="batch_id" value="<?=e($bid)?>"><button class="btn btn-outline-primary rounded-pill w-100" type="submit"><i class="bi bi-pencil-square me-1"></i> Edit Items</button></form></div></div>
              </div>
            <?php else: ?>
              <div class="d-flex flex-wrap gap-2 mt-3 align-items-center"><?php if($proofHref): ?><a class="btn btn-sm btn-outline-primary rounded-pill" target="_blank" href="<?=e($proofHref)?>"><i class="bi bi-eye me-1"></i> View Proof</a><?php endif; ?><a class="btn btn-sm btn-outline-secondary rounded-pill" href="<?=base_url('billing-payments.php?tab=proofs')?>">View payment status</a></div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>

  <?php elseif($tab==='proofs'): ?>
    <div class="card card-body border-0 rounded-4 shadow-sm"><h3 class="h5 fw-bold">Payment Proof Status</h3><?php if(!$batches): mj_v281_empty('No payment proof uploaded','Generate invoice first, then upload proof from Invoices & Pay.','bi-upload'); else: ?><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Date</th><th>Invoice / Batch</th><th>Items</th><th>Method / Ref</th><th>Proof</th><th>Status</th><th class="text-end">Total</th></tr></thead><tbody><?php foreach($batches as $b): $bid=(int)$b['id']; ?><tr><td><?=e($b['created_at']??'')?></td><td><b><?=e($b['batch_no'] ?: ('PAY-'.$bid))?></b><br><small>Invoice #<?=e($b['invoice_id'] ?: '-')?></small></td><td><?php foreach(array_slice($batchItems[$bid] ?? [],0,3) as $it): ?><div><small><?=e($it['item_label']??$it['item_type'])?> × <?=e($it['quantity']??1)?></small></div><?php endforeach; if(count($batchItems[$bid] ?? [])>3): ?><small>+<?=e(count($batchItems[$bid])-3)?> more</small><?php endif; ?></td><td><?=e($methodLabels[(string)($b['payment_method']??'')] ?? ($b['payment_method']??''))?><br><small><?=e($b['reference_no']??'')?></small></td><td><?php $href=mj291_user_proof_href((string)($b['proof_path']??'')); if($href): ?><a class="btn btn-sm btn-outline-primary rounded-pill" target="_blank" href="<?=e($href)?>">View</a><?php else: ?><a class="btn btn-sm btn-outline-secondary rounded-pill" href="<?=base_url('billing-payments.php?tab=invoices&pay_batch='.$bid)?>">Pay now</a><?php endif; ?></td><td><?=mj291_status_badge(mj301_billing_status_value($b,'payment'))?><?php if(!empty($b['admin_note'])): ?><br><small class="text-muted"><?=e($b['admin_note'])?></small><?php endif; ?></td><td class="text-end fw-bold"><?=money((float)($b['total_amount']??0),(string)($b['currency_code']??$currency))?></td></tr><?php if(in_array(strtolower((string)($b['status']??'')), ['rejected','need_more_info'], true)): ?><tr><td colspan="7"><form method="post" enctype="multipart/form-data" class="p-3 bg-light rounded-4"><?=csrf_input()?><input type="hidden" name="action" value="reupload_batch_proof"><input type="hidden" name="return_tab" value="proofs"><input type="hidden" name="batch_id" value="<?=e($bid)?>"><b>Upload new proof for <?=e($b['batch_no'] ?: ('PAY-'.$bid))?></b><div class="row g-2 mt-2"><div class="col-md-3"><select class="form-select" name="payment_method" required><?php foreach($methods as $mk=>$m): ?><option value="<?=e($mk)?>" <?=(string)($b['payment_method']??'')===(string)$mk?'selected':''?>><?=e($m['label']??$mk)?></option><?php endforeach; ?></select></div><div class="col-md-3"><input class="form-control" name="payment_reference" required value="<?=e($b['reference_no']??'')?>"></div><div class="col-md-3"><input class="form-control" type="file" name="payment_proof" required accept=".jpg,.jpeg,.png,.webp,.pdf"></div><div class="col-md-3"><button class="btn btn-primary rounded-pill w-100">Re-upload Proof</button></div><div class="col-12"><textarea class="form-control" name="payment_note" rows="2" placeholder="Reply to admin / note"></textarea></div></div></form></td></tr><?php endif; endforeach; ?></tbody></table></div><?php endif; ?></div>

  <?php elseif($tab==='wallet'): ?>
    <div class="row g-4 mb-4">
      <div class="col-md-4"><div class="stat"><b><?=money((float)($wallet['balance']??0),$currency)?></b><br><span class="muted">Total Wallet Balance</span></div></div>
      <div class="col-md-4"><div class="stat"><b><?=money($walletAvailable,$currency)?></b><br><span class="muted">Available to Use</span></div></div>
      <div class="col-md-4"><div class="stat"><b><?=money($walletHeld,$currency)?></b><br><span class="muted">Held for Pending Approval</span></div></div>
    </div>
    <div class="alert alert-info rounded-4"><b>How wallet works:</b> You can top up wallet by invoice + payment proof. Admin approves the top-up before credit is added. When you pay a normal invoice fully by wallet, the wallet balance is deducted immediately and eligible services activate automatically.</div>
    <div class="row g-4 mb-4">
      <?php if($walletTopupEnabled): ?>
      <div class="col-lg-5"><div class="card card-body border-0 rounded-4 shadow-sm h-100"><h3 class="h5 fw-bold mb-1"><i class="bi bi-plus-circle me-1 text-success"></i> Top Up Wallet Credit</h3><p class="text-muted">Generate a top-up invoice, then pay and upload proof. Admin approval adds the credit to your wallet.</p><form method="post"> <?=csrf_input()?> <input type="hidden" name="action" value="create_wallet_topup_invoice"><input type="hidden" name="return_tab" value="wallet"><div class="row g-2"><div class="col-md-7"><label class="form-label">Top-up amount</label><input class="form-control" type="number" step="0.01" min="<?=e($walletTopupMin)?>" max="<?=e($walletTopupMax)?>" name="topup_amount" required placeholder="<?=e(number_format($walletTopupMin,2,'.',''))?>"></div><div class="col-md-5"><label class="form-label">Currency</label><input class="form-control" name="topup_currency" value="<?=e($currency)?>" maxlength="10"></div><div class="col-12"><label class="form-label">Note</label><textarea class="form-control" name="topup_note" rows="2" placeholder="Optional note to admin"></textarea></div><div class="col-12"><button class="btn btn-primary rounded-pill w-100"><i class="bi bi-file-earmark-plus me-1"></i> Generate Top-Up Invoice</button></div></div><small class="text-muted d-block mt-2">Minimum <?=money($walletTopupMin,$currency)?>, maximum <?=money($walletTopupMax,$currency)?>.</small></form></div></div>
      <?php endif; ?>
      <div class="<?= $walletTopupEnabled ? 'col-lg-7' : 'col-12' ?>"><div class="card card-body border-0 rounded-4 shadow-sm h-100"><div class="d-flex justify-content-between flex-wrap gap-2 align-items-center mb-3"><div><h3 class="h5 fw-bold mb-1">Wallet Ledger</h3><p class="text-muted mb-0">Every credit, debit, hold and release is shown here.</p></div><a href="<?=base_url('billing-payments.php?tab=invoices')?>" class="btn btn-outline-primary rounded-pill">Pay Invoice</a></div><?php if(!$walletTx): mj_v281_empty('No wallet entries','Credit and debit history will appear here.','bi-wallet2'); else: ?><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Date</th><th>Type</th><th>Description</th><th>Status</th><th class="text-end">Amount</th></tr></thead><tbody><?php foreach($walletTx as $tx): $dir=(string)($tx['direction']??''); ?><tr><td><?=e($tx['created_at']??'')?></td><td><b><?=e(ucwords(str_replace('_',' ',(string)($tx['transaction_type']??$tx['type']??''))))?></b></td><td><?=e($tx['description']??$tx['notes']??'')?></td><td><?=e(ucwords($dir))?></td><td class="text-end fw-bold <?= $dir==='debit'?'text-danger':'text-success' ?>"><?=($dir==='debit'?'-':'+')?><?=money((float)($tx['amount']??0),(string)($tx['currency_code']??$currency))?></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?></div></div>
    </div>

  <?php elseif($tab==='receipts'): ?>
    <div class="card card-body border-0 rounded-4 shadow-sm"><h3 class="h5 fw-bold">Receipts</h3><?php if(!$receipts): mj_v281_empty('No receipt yet','Receipt is generated after admin approves payment.','bi-receipt'); else: ?><div class="table-responsive"><table class="table"><thead><tr><th>Date</th><th>Receipt</th><th>Invoice</th><th>Method / Ref</th><th>Status</th><th class="text-end">Amount</th><th>Print</th></tr></thead><tbody><?php foreach($receipts as $r): ?><tr><td><?=e($r['created_at']??'')?></td><td><b><?=e($r['receipt_no']??('RCP-'.$r['id']))?></b></td><td>#<?=e($r['invoice_id']??'-')?></td><td><?=e($methodLabels[(string)($r['payment_method']??'')] ?? ($r['payment_method']??''))?><br><small><?=e($r['reference_no']??'')?></small></td><td><?=mj291_status_badge(mj301_billing_status_value($r,'receipt'))?></td><td class="text-end fw-bold"><?=money((float)($r['amount']??0),(string)($r['currency_code']??$currency))?></td><td><a class="btn btn-sm btn-outline-secondary rounded-pill" target="_blank" href="<?=base_url('receipt-print.php?receipt_id='.(int)$r['id'])?>">Print</a></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?></div>

  <?php elseif($tab==='refunds'): ?>
    <div class="card card-body border-0 rounded-4 shadow-sm"><h3 class="h5 fw-bold">Refund Requests</h3><?php if(!$refunds): mj_v281_empty('No refund requests','Refund and credit note requests will appear here for admin review.','bi-arrow-counterclockwise'); else: ?><div class="table-responsive"><table class="table"><thead><tr><th>Date</th><th>Reason</th><th>Status</th><th class="text-end">Amount</th></tr></thead><tbody><?php foreach($refunds as $r): ?><tr><td><?=e($r['created_at']??'')?></td><td><?=e($r['reason']??'')?></td><td><?=mj291_status_badge((string)($r['status']??'pending'))?></td><td class="text-end fw-bold"><?=money((float)($r['amount']??0),(string)($r['currency_code']??$currency))?></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?></div>

  <?php elseif($tab==='tax'): ?>
    <?php mj_v281_feature_grid([['bi-building','Company Invoice Details','Billing name, company number, tax number and billing address.'],['bi-percent','Tax / GST / VAT','Admin-controlled tax by country and invoice type.'],['bi-globe','Country Currency','Currency and invoice sequence by country/year.']]); ?>
    <div class="alert alert-info rounded-4 mt-4">Tax is currently <?=$taxEnabled?'enabled':'disabled'?>. Label: <b><?=e($taxLabel)?></b>, Default rate: <b><?=e($taxRate)?>%</b>.</div>

  <?php elseif($tab==='methods'): ?>
    <div class="card card-body border-0 rounded-4 shadow-sm"><h3 class="h5 fw-bold">Admin-enabled Payment Methods</h3><?php if(!$methods): mj_v281_empty('No active payment methods','Admin can enable Bank Transfer, PayNow / QR, PayPal or Cash from upgrade payment settings.','bi-credit-card'); else: ?><div class="row g-3"><?php foreach($methods as $m): ?><div class="col-md-6"><div class="mj-mini-card"><h5 class="fw-bold"><i class="bi <?=e($m['icon'] ?? 'bi-credit-card')?> me-1"></i><?=e($m['label']??'Payment Method')?></h5><p class="text-muted mb-1"><?=nl2br(e($m['details']??''))?></p><?=mj291_status_badge('active')?></div></div><?php endforeach; ?></div><?php endif; ?></div>
  <?php endif; ?>
<style>.mj-wallet-pay-box,.mj-wallet-summary{border:1px solid #bde7d1;background:#f0fdf4;border-radius:18px;padding:14px}.mj-wallet-pay-box .btn-success,.mj-wallet-summary .btn-success{background:linear-gradient(135deg,#16a34a,#22c55e);border:0;font-weight:800}</style>
</section></div></div>
<script>
(function(){
  function fmt(v,c){return (c||'<?=e($currency)?>')+' '+Number(v||0).toFixed(2)}
  function calc(){let total=0,count=0,cur='<?=e($currency)?>';document.querySelectorAll('.mj-cart-check:checked').forEach(function(el){total+=parseFloat(el.dataset.amount||0);cur=el.dataset.currency||cur;count++;});document.querySelectorAll('.mj-extra-check:checked').forEach(function(ch){let q=document.getElementById(ch.dataset.target);if(q){total+=parseFloat(q.dataset.unit||0)*parseInt(q.value||0);cur=q.dataset.currency||cur;count++;}});let taxRate=parseFloat('<?=e((string)$taxRate)?>')||0;let tax=<?= $taxEnabled ? 'total*taxRate/100' : '0' ?>;let grand=total+tax;let c=document.getElementById('mjCartCount'); if(c)c.textContent=count; let s=document.getElementById('mjCartSubtotal'); if(s)s.textContent=fmt(total,cur); let t=document.getElementById('mjCartTax'); if(t)t.textContent=fmt(tax,cur); let g=document.getElementById('mjCartTotal'); if(g)g.textContent=fmt(grand,cur);}
  document.addEventListener('change',function(e){if(e.target.matches('.mj-cart-check,.mj-extra-check,.mj-extra-qty'))calc();});
  document.addEventListener('click',function(e){let b=e.target.closest('.mj-qty-minus,.mj-qty-plus'); if(b){let q=document.getElementById(b.dataset.target); if(q){let v=parseInt(q.value||1); let min=parseInt(q.min||1); let max=parseInt(q.max||100); q.value=Math.max(min,Math.min(max,v+(b.classList.contains('mj-qty-plus')?1:-1))); calc();}} if(e.target.id==='mjSelectAllPayItems'){let boxes=document.querySelectorAll('.mj-cart-check'); let all=[...boxes].every(x=>x.checked); boxes.forEach(x=>x.checked=!all); calc();}});
  calc();
})();
</script>
<?php include __DIR__.'/includes/footer.php'; ?>
