<?php
$reportActive = 'wallet';
$pageTitle = 'Wallet & Commission 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');
$vendor_id = (int)($_GET['vendor_id'] ?? 0);
$dtFrom = $dateFrom . ' 00:00:00';
$dtTo = $dateTo . ' 23:59:59';

// Platform totals
$platformCommission = (int)$pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='debit' AND ref_type='lead' AND created_at BETWEEN ? AND ?")->execute([$dtFrom, $dtTo]) ?: 0;
$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();

$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();

$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]);
$rechargeTotal = (int)$stmt->fetchColumn();

// Per-vendor breakdown
$where = ["t.created_at BETWEEN ? AND ?"];
$params = [$dtFrom, $dtTo];
if ($vendor_id) { $where[] = "t.vendor_id=?"; $params[] = $vendor_id; }

$stmt = $pdo->prepare("
  SELECT v.id, v.vendor_code, v.name, v.wallet_balance, v.total_earnings, v.total_jobs,
    COALESCE(SUM(CASE WHEN t.type='credit' THEN t.amount ELSE 0 END),0) credits,
    COALESCE(SUM(CASE WHEN t.type='debit' THEN t.amount ELSE 0 END),0) debits,
    COALESCE(SUM(CASE WHEN t.type='earning' THEN t.amount ELSE 0 END),0) earnings
  FROM vendors v
  LEFT JOIN wallet_transactions t ON t.vendor_id=v.id AND t.created_at BETWEEN ? AND ?
  " . ($vendor_id ? " WHERE v.id=?" : "") . "
  GROUP BY v.id, v.vendor_code, v.name, v.wallet_balance, v.total_earnings, v.total_jobs
  ORDER BY earnings DESC
");
$stmt->execute($vendor_id ? [$dtFrom, $dtTo, $vendor_id] : [$dtFrom, $dtTo]);
$vendorBreakdown = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Daily platform commission chart
$stmt = $pdo->prepare("
  SELECT DATE(created_at) d, COALESCE(SUM(amount),0) amt
  FROM wallet_transactions WHERE type='debit' AND ref_type='lead' AND created_at BETWEEN ? AND ?
  GROUP BY DATE(created_at) ORDER BY d
");
$stmt->execute([$dtFrom, $dtTo]);
$dailyCommission = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="page-header">
  <h1>Wallet & Commission Report</h1>
  <p class="subtitle">Vendor earnings view — 20% platform, 80% vendor</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">Vendor ID</label><input type="number" name="vendor_id" class="form-control" value="<?php echo $vendor_id ?: ''; ?>" placeholder="All"></div>
    <div class="col-md-2"><button type="submit" class="btn btn-dark">Apply</button></div>
  </form>
</div>

<div class="report-summary">
  <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-success">₹<?php echo number_format($vendorEarnings); ?></div></div>
  <div class="summary-item"><div class="label">Razorpay Recharge</div><div class="value">₹<?php echo number_format($rechargeTotal); ?></div></div>
</div>

<div class="row g-4 mb-4">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header">Daily Platform Commission</div>
      <div class="card-body">
        <div class="chart-container"><canvas id="commissionChart"></canvas></div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">Split</div>
      <div class="card-body">
        <div class="chart-container"><canvas id="splitChart"></canvas></div>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header">Vendor-wise Earnings (Period)</div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>Vendor</th><th>Credits</th><th>Debits</th><th>Earnings</th><th>Current Balance</th><th>Total Jobs</th></tr></thead>
        <tbody>
          <?php foreach ($vendorBreakdown as $v): ?>
          <tr>
            <td><strong><?php echo htmlspecialchars($v['vendor_code']); ?></strong> <?php echo htmlspecialchars($v['name']); ?></td>
            <td class="text-success">₹<?php echo number_format((int)$v['credits']); ?></td>
            <td class="text-danger">₹<?php echo number_format((int)$v['debits']); ?></td>
            <td class="text-primary fw-semibold">₹<?php echo number_format((int)$v['earnings']); ?></td>
            <td>₹<?php echo number_format((int)$v['wallet_balance']); ?></td>
            <td><?php echo $v['total_jobs']; ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
const dailyComm = <?php echo json_encode($dailyCommission); ?>;
new Chart(document.getElementById('commissionChart'), {
  type: 'bar',
  data: { labels: dailyComm.map(r=>r.d), datasets: [{ label: 'Commission ₹', data: dailyComm.map(r=>r.amt), backgroundColor: 'rgba(245,158,11,0.7)', borderRadius: 4 }] },
  options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true } } }
});
new Chart(document.getElementById('splitChart'), {
  type: 'doughnut',
  data: { labels: ['Platform 20%', 'Vendor 80%'], datasets: [{ data: [<?php echo $platformCommission; ?>, <?php echo $vendorEarnings; ?>], backgroundColor: ['#F59E0B','#10B981'] }] },
  options: { responsive: true, maintainAspectRatio: false }
});
</script>
<?php require_once __DIR__ . '/../partials/bottom.php'; ?>
