<?php
$reportActive = 'payment';
$pageTitle = 'Payment & 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');
$dtFrom = $dateFrom . ' 00:00:00';
$dtTo = $dateTo . ' 23:59:59';

// Commission: 20% platform, 80% vendor (from lead_price when picked)
// Completed jobs: lead_price = 100%, platform commission = 20% (debit from wallet), vendor earning = 80% (earning_amount in job)

$stmt = $pdo->prepare("
  SELECT j.id, j.earning_amount, j.payment_mode, l.lead_price, l.customer_name, v.vendor_code, v.name vendor_name, c.name category_name
  FROM jobs j
  JOIN leads l ON l.id=j.lead_id
  JOIN vendors v ON v.id=j.vendor_id
  LEFT JOIN categories c ON c.id=l.category_id
  WHERE j.status='completed' AND j.completed_at BETWEEN ? AND ?
  ORDER BY j.completed_at DESC
");
$stmt->execute([$dtFrom, $dtTo]);
$completedJobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalLeadValue = 0;
$totalPlatformCommission = 0;
$totalVendorEarning = 0;
$onlineTotal = 0;
$codTotal = 0;

foreach ($completedJobs as $j) {
  $leadPrice = (int)$j['lead_price'];
  $commission = (int)round($leadPrice * 0.2);  // 20% platform
  $vendorEarning = (int)$j['earning_amount'];   // 80% vendor
  $totalLeadValue += $leadPrice;
  $totalPlatformCommission += $commission;
  $totalVendorEarning += $vendorEarning;
  if (strtolower($j['payment_mode'] ?? '') === 'cod') {
    $codTotal += $vendorEarning;
  } else {
    $onlineTotal += $vendorEarning;
  }
}

// Razorpay recharge (user adds money to wallet)
$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 from wallet debits (lead picks)
$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]);
$platformCommissionActual = (int)$stmt->fetchColumn();
?>
<div class="page-header">
  <h1>Payment & Commission Report</h1>
  <p class="subtitle">20% Platform Commission | 80% Vendor Earning — per lead</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"><button type="submit" class="btn btn-dark">Apply</button></div>
  </form>
</div>

<div class="card mb-4 p-4">
  <div class="row g-4">
    <div class="col-md-4">
      <div class="border rounded-3 p-4 text-center">
        <div class="text-muted small mb-1">Total Lead Value (100%)</div>
        <div class="fs-3 fw-bold">₹<?php echo number_format($totalLeadValue); ?></div>
        <div class="small mt-2"><?php echo count($completedJobs); ?> completed jobs</div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="border rounded-3 p-4 text-center border-warning">
        <div class="text-warning small mb-1">Platform Commission (20%)</div>
        <div class="fs-3 fw-bold text-warning">₹<?php echo number_format($totalPlatformCommission); ?></div>
        <div class="small mt-2">Your revenue</div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="border rounded-3 p-4 text-center border-success">
        <div class="text-success small mb-1">Vendor Earning (80%)</div>
        <div class="fs-3 fw-bold text-success">₹<?php echo number_format($totalVendorEarning); ?></div>
        <div class="small mt-2">Online: ₹<?php echo number_format($onlineTotal); ?> | COD: ₹<?php echo number_format($codTotal); ?></div>
      </div>
    </div>
  </div>
</div>

<div class="row g-4 mb-4">
  <div class="col-lg-6">
    <div class="card">
      <div class="card-header">Commission Split (Pie)</div>
      <div class="card-body">
        <div class="chart-container"><canvas id="commissionChart"></canvas></div>
      </div>
    </div>
  </div>
  <div class="col-lg-6">
    <div class="card">
      <div class="card-header">Payment Mode</div>
      <div class="card-body">
        <div class="chart-container"><canvas id="paymentModeChart"></canvas></div>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header">Job-wise Commission Breakdown</div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>Job</th><th>Vendor</th><th>Customer</th><th>Lead Price</th><th>Commission 20%</th><th>Vendor 80%</th><th>Mode</th></tr></thead>
        <tbody>
          <?php foreach ($completedJobs as $j): 
            $lp = (int)$j['lead_price'];
            $comm = (int)round($lp * 0.2);
            $vend = (int)$j['earning_amount'];
          ?>
          <tr>
            <td>#<?php echo $j['id']; ?></td>
            <td><?php echo htmlspecialchars($j['vendor_code']); ?></td>
            <td><?php echo htmlspecialchars($j['customer_name']); ?></td>
            <td>₹<?php echo number_format($lp); ?></td>
            <td class="text-warning">₹<?php echo number_format($comm); ?></td>
            <td class="text-success">₹<?php echo number_format($vend); ?></td>
            <td><span class="badge bg-<?php echo (strtolower($j['payment_mode']??'')==='cod')?'secondary':'primary'; ?>"><?php echo $j['payment_mode']??'online'; ?></span></td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($completedJobs)): ?><tr><td colspan="7" class="text-muted">No completed jobs in period</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="card mt-4">
  <div class="card-header">Razorpay Recharge (User Wallet Top-up)</div>
  <div class="card-body">
    <div class="row align-items-center">
      <div class="col-md-4">
        <div class="fs-3 fw-bold text-success">₹<?php echo number_format($razorpayRecharge); ?></div>
        <div class="text-muted small">Total recharge via Razorpay in period</div>
      </div>
      <div class="col-md-8">
        <p class="mb-0 small text-muted">Users add money to wallet via Razorpay. This credit is used when they pick leads (20% deducted). Platform commission comes from this flow.</p>
      </div>
    </div>
  </div>
</div>

<script>
new Chart(document.getElementById('commissionChart'), {
  type: 'doughnut',
  data: {
    labels: ['Platform 20%', 'Vendor 80%'],
    datasets: [{ data: [<?php echo $totalPlatformCommission; ?>, <?php echo $totalVendorEarning; ?>], backgroundColor: ['#F59E0B','#10B981'] }]
  },
  options: { responsive: true, maintainAspectRatio: false }
});
new Chart(document.getElementById('paymentModeChart'), {
  type: 'doughnut',
  data: {
    labels: ['Online', 'COD'],
    datasets: [{ data: [<?php echo $onlineTotal; ?>, <?php echo $codTotal; ?>], backgroundColor: ['#3B82F6','#64748b'] }]
  },
  options: { responsive: true, maintainAspectRatio: false }
});
</script>
<?php require_once __DIR__ . '/../partials/bottom.php'; ?>
