<?php
$reportActive = 'transaction';
$pageTitle = 'Transaction Report';
require_once __DIR__ . '/../partials/top.php';

$pdo = db();
$dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$dateTo = $_GET['date_to'] ?? date('Y-m-d');
$type = $_GET['type'] ?? '';
$dtFrom = $dateFrom . ' 00:00:00';
$dtTo = $dateTo . ' 23:59:59';

$where = ["t.created_at BETWEEN ? AND ?"];
$params = [$dtFrom, $dtTo];
if ($type && in_array($type, ['credit','debit','earning'])) {
  $where[] = "t.type=?";
  $params[] = $type;
}

// Summary by type
$stmt = $pdo->prepare("SELECT type, COUNT(*) cnt, COALESCE(SUM(amount),0) amt FROM wallet_transactions WHERE created_at BETWEEN ? AND ? GROUP BY type");
$stmt->execute([$dtFrom, $dtTo]);
$byType = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Razorpay/Recharge (credits from recharge)
$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='credit' AND ref_type='recharge' AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$razorpayRecharge = (int)$stmt->fetchColumn();

// Platform commission (debits from lead picks = 20%)
$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='debit' AND ref_type='lead' AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$platformCommission = (int)$stmt->fetchColumn();

// Vendor earnings
$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='earning' AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$vendorEarnings = (int)$stmt->fetchColumn();

// Withdrawals
$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='debit' AND ref_type='withdrawal' AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$withdrawals = (int)$stmt->fetchColumn();

// Daily breakdown for chart
$stmt = $pdo->prepare("
  SELECT DATE(created_at) d,
    SUM(CASE WHEN type='credit' THEN amount ELSE 0 END) credits,
    SUM(CASE WHEN type='debit' THEN amount ELSE 0 END) debits,
    SUM(CASE WHEN type='earning' THEN amount ELSE 0 END) earnings,
    COUNT(*) cnt
  FROM wallet_transactions WHERE created_at BETWEEN ? AND ?
  GROUP BY DATE(created_at) ORDER BY d
");
$stmt->execute([$dtFrom, $dtTo]);
$dailyTx = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

function txBadge($t) {
  $map = ['credit'=>'success','debit'=>'danger','earning'=>'primary'];
  return '<span class="badge bg-'.($map[$t]??'secondary').'">'.$t.'</span>';
}
?>
<div class="page-header">
  <h1>Transaction Report</h1>
  <p class="subtitle">Wallet transactions, Razorpay recharge & payment flow</p>
</div>

<div class="report-filters">
  <form method="get" class="row g-3 align-items-end">
    <div class="col-md-2"><label class="form-label">From</label><input type="date" name="date_from" class="form-control" value="<?php echo htmlspecialchars($dateFrom); ?>"></div>
    <div class="col-md-2"><label class="form-label">To</label><input type="date" name="date_to" class="form-control" value="<?php echo htmlspecialchars($dateTo); ?>"></div>
    <div class="col-md-2"><label class="form-label">Type</label><select name="type" class="form-select"><option value="">All</option><option value="credit" <?php echo $type==='credit'?'selected':''; ?>>Credit</option><option value="debit" <?php echo $type==='debit'?'selected':''; ?>>Debit</option><option value="earning" <?php echo $type==='earning'?'selected':''; ?>>Earning</option></select></div>
    <div class="col-md-2"><button type="submit" class="btn btn-dark">Apply</button></div>
  </form>
</div>

<?php
$creditsAmt = 0; $debitsAmt = 0;
foreach ($byType as $x) { if ($x['type']==='credit') $creditsAmt += (int)$x['amt']; if ($x['type']==='debit') $debitsAmt += (int)$x['amt']; }
?>
<div class="report-summary">
  <div class="summary-item"><div class="label">Total Credits</div><div class="value text-success">₹<?php echo number_format($creditsAmt); ?></div><div class="small text-muted">Razorpay: ₹<?php echo number_format($razorpayRecharge); ?></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($vendorEarnings); ?></div></div>
  <div class="summary-item"><div class="label">Total Debits</div><div class="value text-danger">₹<?php echo number_format($debitsAmt); ?></div><div class="small text-muted">Withdrawals: ₹<?php echo number_format($withdrawals); ?></div></div>
</div>

<div class="row g-4 mb-4">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header">Transaction Flow (Daily)</div>
      <div class="card-body">
        <div class="chart-container"><canvas id="txChart"></canvas></div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">By Type</div>
      <div class="card-body">
        <div class="chart-container"><canvas id="typeChart"></canvas></div>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header">Transaction List (Last 500)</div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>ID</th><th>Vendor</th><th>Type</th><th>Amount</th><th>Description</th><th>Ref</th><th>Date</th></tr></thead>
        <tbody>
          <?php foreach ($transactions as $t): ?>
          <tr>
            <td>#<?php echo $t['id']; ?></td>
            <td><?php echo htmlspecialchars($t['vendor_code']); ?></td>
            <td><?php echo txBadge($t['type']); ?></td>
            <td class="fw-semibold">₹<?php echo number_format($t['amount']); ?></td>
            <td class="small"><?php echo htmlspecialchars($t['description'] ?? '-'); ?></td>
            <td class="small"><?php echo htmlspecialchars(($t['ref_type'] ?? '-') . ' #' . ($t['ref_id'] ?? '-')); ?></td>
            <td class="small"><?php echo date('M d, H:i', strtotime($t['created_at'])); ?></td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($transactions)): ?><tr><td colspan="7" class="text-muted">No transactions</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
const dailyTx = <?php echo json_encode($dailyTx); ?>;
const byType = <?php echo json_encode($byType); ?>;
new Chart(document.getElementById('txChart'), {
  type: 'bar',
  data: {
    labels: dailyTx.map(r=>r.d),
    datasets: [
      { label: 'Credits', data: dailyTx.map(r=>r.credits), backgroundColor: 'rgba(16,185,129,0.7)', borderRadius: 4 },
      { label: 'Debits', data: dailyTx.map(r=>r.debits), backgroundColor: 'rgba(239,68,68,0.7)', borderRadius: 4 },
      { label: 'Earnings', data: dailyTx.map(r=>r.earnings), backgroundColor: 'rgba(59,130,246,0.7)', borderRadius: 4 }
    ]
  },
  options: { responsive: true, maintainAspectRatio: false, scales: { x: { stacked: false }, y: { beginAtZero: true } } }
});
new Chart(document.getElementById('typeChart'), {
  type: 'doughnut',
  data: {
    labels: byType.map(r=>r.type),
    datasets: [{ data: byType.map(r=>r.amt), backgroundColor: ['#10B981','#EF4444','#3B82F6'] }]
  },
  options: { responsive: true, maintainAspectRatio: false }
});
</script>
<?php require_once __DIR__ . '/../partials/bottom.php'; ?>
