<?php
$reportActive = 'vendor';
$pageTitle = 'Vendor 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';

// Summary
$stmt = $pdo->query("SELECT COUNT(*) FROM vendors");
$totalVendors = (int)$stmt->fetchColumn();

$stmt = $pdo->query("SELECT COUNT(*) FROM vendors WHERE approval_status='approved' AND is_active=1");
$activeVendors = (int)$stmt->fetchColumn();

$stmt = $pdo->query("SELECT COUNT(*) FROM vendors WHERE approval_status='pending'");
$pendingVendors = (int)$stmt->fetchColumn();

$stmt = $pdo->query("SELECT COUNT(*) FROM vendors WHERE approval_status='rejected'");
$rejectedVendors = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM vendors WHERE created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$newVendors = (int)$stmt->fetchColumn();

$stmt = $pdo->query("SELECT COALESCE(SUM(wallet_balance),0) FROM vendors");
$totalWalletBalance = (int)$stmt->fetchColumn();

$stmt = $pdo->query("SELECT COALESCE(SUM(total_earnings),0) FROM vendors");
$totalEarnings = (int)$stmt->fetchColumn();

// By approval status
$stmt = $pdo->query("SELECT approval_status, COUNT(*) cnt FROM vendors GROUP BY approval_status");
$byApproval = $stmt->fetchAll(PDO::FETCH_ASSOC);

// By KYC status
$stmt = $pdo->query("SELECT kyc_status, COUNT(*) cnt FROM vendors GROUP BY kyc_status");
$byKyc = $stmt->fetchAll(PDO::FETCH_ASSOC);

// By category
$stmt = $pdo->query("
  SELECT v.category_name, COUNT(*) cnt
  FROM vendors v
  WHERE v.category_id > 0
  GROUP BY v.category_id, v.category_name
  ORDER BY cnt DESC
");
$byCategory = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Top performers (by earnings)
$stmt = $pdo->query("
  SELECT v.vendor_code, v.name, v.phone, v.category_name, v.approval_status, v.total_earnings, v.total_jobs, v.wallet_balance
  FROM vendors v
  ORDER BY v.total_earnings DESC
  LIMIT 20
");
$topVendors = $stmt->fetchAll(PDO::FETCH_ASSOC);

// New vendors in period
$stmt = $pdo->prepare("
  SELECT v.* FROM vendors v
  WHERE v.created_at BETWEEN ? AND ?
  ORDER BY v.created_at DESC
");
$stmt->execute([$dtFrom, $dtTo]);
$newVendorsList = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="page-header">
  <h1>Vendor Report</h1>
  <p class="subtitle">Vendor analytics and performance metrics</p>
</div>

<div class="report-filters">
  <form method="get" class="row g-3 align-items-end">
    <div class="col-md-3"><label class="form-label">From Date</label><input type="date" name="date_from" class="form-control" value="<?php echo htmlspecialchars($dateFrom); ?>"></div>
    <div class="col-md-3"><label class="form-label">To Date</label><input type="date" name="date_to" class="form-control" value="<?php echo htmlspecialchars($dateTo); ?>"></div>
    <div class="col-md-4"><button type="submit" class="btn btn-dark">Apply</button></div>
  </form>
</div>

<div class="report-summary">
  <div class="summary-item"><div class="label">Total Vendors</div><div class="value"><?php echo $totalVendors; ?></div></div>
  <div class="summary-item"><div class="label">Active</div><div class="value text-success"><?php echo $activeVendors; ?></div></div>
  <div class="summary-item"><div class="label">Pending Approval</div><div class="value text-warning"><?php echo $pendingVendors; ?></div></div>
  <div class="summary-item"><div class="label">Rejected</div><div class="value text-danger"><?php echo $rejectedVendors; ?></div></div>
  <div class="summary-item"><div class="label">New (Period)</div><div class="value"><?php echo $newVendors; ?></div></div>
  <div class="summary-item"><div class="label">Total Wallet Balance</div><div class="value">₹<?php echo number_format($totalWalletBalance); ?></div></div>
  <div class="summary-item"><div class="label">Total Earnings (All Time)</div><div class="value">₹<?php echo number_format($totalEarnings); ?></div></div>
</div>

<div class="row g-4">
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">By Approval Status</div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">
            <tbody>
              <?php foreach ($byApproval as $r): ?>
              <tr><td><?php echo ucfirst($r['approval_status']); ?></td><td><?php echo $r['cnt']; ?></td></tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">By KYC Status</div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">
            <tbody>
              <?php foreach ($byKyc as $r): ?>
              <tr><td><?php echo ucfirst(str_replace('_',' ',$r['kyc_status'])); ?></td><td><?php echo $r['cnt']; ?></td></tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">By Category</div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">
            <tbody>
              <?php foreach ($byCategory as $r): ?>
              <tr><td><?php echo htmlspecialchars($r['category_name'] ?: 'Unassigned'); ?></td><td><?php echo $r['cnt']; ?></td></tr>
              <?php endforeach; ?>
              <?php if (empty($byCategory)): ?><tr><td colspan="2" class="text-muted">No data</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="card mt-4">
  <div class="card-header">Top Vendors by Earnings</div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>Code</th><th>Name</th><th>Category</th><th>Status</th><th>Jobs</th><th>Earnings</th><th>Wallet</th></tr></thead>
        <tbody>
          <?php foreach ($topVendors as $v): ?>
          <tr>
            <td><strong><?php echo htmlspecialchars($v['vendor_code']); ?></strong></td>
            <td><?php echo htmlspecialchars($v['name']); ?></td>
            <td><?php echo htmlspecialchars($v['category_name'] ?? '-'); ?></td>
            <td><span class="badge bg-<?php echo $v['approval_status']==='approved'?'success':'warning'; ?>"><?php echo $v['approval_status']; ?></span></td>
            <td><?php echo $v['total_jobs']; ?></td>
            <td>₹<?php echo number_format($v['total_earnings']); ?></td>
            <td>₹<?php echo number_format($v['wallet_balance']); ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="card mt-4">
  <div class="card-header">New Vendors in Selected Period (<?php echo $newVendors; ?>)</div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>Code</th><th>Name</th><th>Phone</th><th>Category</th><th>Status</th><th>Joined</th></tr></thead>
        <tbody>
          <?php foreach ($newVendorsList as $v): ?>
          <tr>
            <td><?php echo htmlspecialchars($v['vendor_code']); ?></td>
            <td><?php echo htmlspecialchars($v['name']); ?></td>
            <td><?php echo htmlspecialchars($v['phone']); ?></td>
            <td><?php echo htmlspecialchars($v['category_name'] ?? '-'); ?></td>
            <td><span class="badge bg-<?php echo $v['approval_status']==='approved'?'success':'warning'; ?>"><?php echo $v['approval_status']; ?></span></td>
            <td><?php echo date('M d, Y', strtotime($v['created_at'])); ?></td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($newVendorsList)): ?><tr><td colspan="6" class="text-muted">No new vendors in period</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/../partials/bottom.php'; ?>
