<?php
$active = 'tx';
$pageTitle = 'Wallet Transactions';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$vendor_id = (int)($_GET['vendor_id'] ?? 0);
$where = [];
$params = [];
if ($vendor_id) { $where[] = "t.vendor_id=?"; $params[] = $vendor_id; }

$sql = "SELECT t.*, v.vendor_code, v.name vendor_name FROM wallet_transactions t JOIN vendors v ON v.id=t.vendor_id";
if ($where) $sql .= " WHERE " . implode(" AND ", $where);
$sql .= " ORDER BY t.created_at DESC LIMIT 500";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$tx = $stmt->fetchAll();

// Quick totals (all time or by vendor)
$totWhere = $vendor_id ? " AND vendor_id=".(int)$vendor_id : "";
$totalCredits = (int)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='credit' $totWhere")->fetchColumn();
$totalDebits = (int)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='debit' $totWhere")->fetchColumn();
$totalEarnings = (int)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='earning' $totWhere")->fetchColumn();
$platformCommission = (int)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='debit' AND ref_type='lead' $totWhere")->fetchColumn();

function typeBadge($t){
  $map=['credit'=>'success','debit'=>'danger','earning'=>'primary'];
  $c=$map[$t]??'secondary';
  return "<span class='badge text-bg-$c'>$t</span>";
}
?>
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div>
    <h4 class="fw-bold mb-0">Wallet Transactions</h4>
    <div class="text-muted small">Credits (Razorpay), Debits (lead pick 20%), Earnings (vendor 80%)</div>
  </div>
  <a href="reports/transaction_report.php" class="btn btn-outline-dark">📊 Full Transaction Report</a>
</div>

<div class="report-summary mb-4">
  <div class="summary-item"><div class="label">Total Credits</div><div class="value text-success">₹<?php echo number_format($totalCredits); ?></div></div>
  <div class="summary-item"><div class="label">Platform Commission (20%)</div><div class="value text-warning">₹<?php echo number_format($platformCommission); ?></div></div>
  <div class="summary-item"><div class="label">Vendor Earnings (80%)</div><div class="value text-primary">₹<?php echo number_format($totalEarnings); ?></div></div>
  <div class="summary-item"><div class="label">Total Debits</div><div class="value text-danger">₹<?php echo number_format($totalDebits); ?></div></div>
</div>

<form class="row g-2 mb-3">
  <div class="col-md-3">
    <label class="form-label small text-muted">Vendor ID</label>
    <input class="form-control" name="vendor_id" value="<?php echo $vendor_id ?: ''; ?>" placeholder="Optional">
  </div>
  <div class="col-auto d-flex align-items-end">
    <button class="btn btn-outline-dark" type="submit">Filter</button>
  </div>
</form>

<div class="card p-3">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th>ID</th>
          <th>Vendor</th>
          <th>Type</th>
          <th>Amount</th>
          <th>Description</th>
          <th>Ref</th>
          <th>Payment</th>
          <th class="text-end">Created</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($tx as $t): ?>
          <tr>
            <td class="fw-semibold">#<?php echo (int)$t['id']; ?></td>
            <td><?php echo htmlspecialchars($t['vendor_code']); ?><div class="small text-muted"><?php echo htmlspecialchars($t['vendor_name']); ?></div></td>
            <td><?php echo typeBadge($t['type']); ?></td>
            <td>₹<?php echo (int)$t['amount']; ?></td>
            <td class="text-success"><?php echo !empty($t['discount_amount']) ? '-₹'.(int)$t['discount_amount'] : '-'; ?></td>
            <td><?php echo htmlspecialchars($t['description'] ?? '-'); ?></td>
            <td class="small text-muted"><?php echo htmlspecialchars(($t['ref_type'] ?? '-') . ' / ' . ($t['ref_id'] ?? '-')); ?></td>
            <td class="small"><?php echo htmlspecialchars($t['payment_mode'] ?? '-'); ?></td>
            <td class="text-end small text-muted"><?php echo htmlspecialchars($t['created_at']); ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (count($tx)===0): ?>
          <tr><td colspan="8" class="text-muted">No transactions found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require_once __DIR__ . '/partials/bottom.php'; ?>
