<?php
$pageTitle = 'Dashboard';
require_once __DIR__ . '/includes/header.php';

// Quick stats
$db = getDB();
$totalMembers = $db->query("SELECT COUNT(*) FROM members WHERE name IS NOT NULL")->fetchColumn();
$totalCards   = $db->query("SELECT COUNT(*) FROM members")->fetchColumn();
$totalSales   = $db->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE type='earn'")->fetchColumn();
$totalPoints  = $db->query("SELECT COALESCE(SUM(points),0) FROM transactions WHERE type='earn'")->fetchColumn();
$redeemedPts  = $db->query("SELECT COALESCE(SUM(points),0) FROM transactions WHERE type='redeem'")->fetchColumn();
$netPoints    = $totalPoints - $redeemedPts;
$todaySales   = $db->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE DATE(created_at)=CURDATE() AND type='earn'")->fetchColumn();

// Recent transactions (10)
$recent = $db->query("
    SELECT t.*, m.name, m.card_code
    FROM transactions t
    JOIN members m ON m.id = t.member_id
    ORDER BY t.created_at DESC LIMIT 10
")->fetchAll();

// Top customers (5)
$topCustomers = $db->query("
    SELECT m.name, m.card_code,
           SUM(CASE WHEN t.type='earn' THEN t.points ELSE 0 END) -
           SUM(CASE WHEN t.type='redeem' THEN t.points ELSE 0 END) AS balance,
           SUM(CASE WHEN t.type='earn' THEN t.amount ELSE 0 END) AS total_spend
    FROM members m
    JOIN transactions t ON t.member_id = m.id
    WHERE m.name IS NOT NULL
    GROUP BY m.id
    ORDER BY total_spend DESC LIMIT 5
")->fetchAll();

// Sales last 7 days for chart
$salesChart = $db->query("
    SELECT DATE(created_at) AS day, SUM(amount) AS total
    FROM transactions
    WHERE type='earn' AND created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    GROUP BY DATE(created_at)
    ORDER BY day
")->fetchAll();
$chartLabels = [];
$chartData   = [];
$map = [];
foreach ($salesChart as $r) $map[$r['day']] = $r['total'];
for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $chartLabels[] = date('M d', strtotime($d));
    $chartData[]   = $map[$d] ?? 0;
}
?>

<!-- Stat Cards -->
<div class="row g-3 mb-4">
  <div class="col-xl-3 col-sm-6">
    <div class="stat-card border-start border-primary border-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="stat-label">Registered Members</div>
          <div class="stat-value"><?= number_format($totalMembers) ?></div>
          <div class="text-muted small"><?= number_format($totalCards) ?> cards total</div>
        </div>
        <div class="stat-icon bg-primary-subtle text-primary">
          <i class="bi bi-people-fill"></i>
        </div>
      </div>
    </div>
  </div>

  <div class="col-xl-3 col-sm-6">
    <div class="stat-card border-start border-success border-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="stat-label">Total Sales</div>
          <div class="stat-value">₱<?= number_format($totalSales, 2) ?></div>
          <div class="text-muted small">Today: ₱<?= number_format($todaySales, 2) ?></div>
        </div>
        <div class="stat-icon bg-success-subtle text-success">
          <i class="bi bi-currency-dollar"></i>
        </div>
      </div>
    </div>
  </div>

  <div class="col-xl-3 col-sm-6">
    <div class="stat-card border-start border-warning border-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="stat-label">Points Earned</div>
          <div class="stat-value"><?= number_format($totalPoints) ?></div>
          <div class="text-muted small">Redeemed: <?= number_format($redeemedPts) ?></div>
        </div>
        <div class="stat-icon bg-warning-subtle text-warning">
          <i class="bi bi-star-fill"></i>
        </div>
      </div>
    </div>
  </div>

  <div class="col-xl-3 col-sm-6">
    <div class="stat-card border-start border-info border-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="stat-label">Active Points</div>
          <div class="stat-value"><?= number_format($netPoints) ?></div>
          <div class="text-muted small">Net unredeemed</div>
        </div>
        <div class="stat-icon bg-info-subtle text-info">
          <i class="bi bi-gem"></i>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Charts + Top Customers -->
<div class="row g-3 mb-4">
  <div class="col-xl-8">
    <div class="card shadow-sm h-100">
      <div class="card-header d-flex align-items-center bg-white">
        <i class="bi bi-graph-up text-primary me-2"></i>
        <span class="fw-semibold">Sales — Last 7 Days</span>
      </div>
      <div class="card-body">
        <canvas id="salesChart" height="120"></canvas>
      </div>
    </div>
  </div>
  <div class="col-xl-4">
    <div class="card shadow-sm h-100">
      <div class="card-header d-flex align-items-center bg-white">
        <i class="bi bi-trophy text-warning me-2"></i>
        <span class="fw-semibold">Top Customers</span>
      </div>
      <div class="card-body p-0">
        <ul class="list-group list-group-flush">
          <?php foreach ($topCustomers as $i => $c): ?>
          <li class="list-group-item d-flex align-items-center gap-3 py-2">
            <span class="badge rounded-pill bg-<?= ['primary','success','warning','info','secondary'][$i] ?? 'secondary' ?>">
              #<?= $i+1 ?>
            </span>
            <div class="flex-grow-1">
              <div class="fw-semibold small"><?= e($c['name'] ?? 'N/A') ?></div>
              <div class="text-muted" style="font-size:.72rem"><?= e($c['card_code']) ?></div>
            </div>
            <div class="text-end">
              <div class="fw-bold small text-warning"><?= number_format($c['balance']) ?> pts</div>
              <div class="text-muted" style="font-size:.72rem">₱<?= number_format($c['total_spend'],0) ?></div>
            </div>
          </li>
          <?php endforeach; ?>
          <?php if (empty($topCustomers)): ?>
          <li class="list-group-item text-muted text-center small py-4">No data yet</li>
          <?php endif; ?>
        </ul>
      </div>
    </div>
  </div>
</div>

<!-- Recent Transactions -->
<div class="card shadow-sm">
  <div class="card-header d-flex align-items-center justify-content-between bg-white">
    <div class="d-flex align-items-center">
      <i class="bi bi-clock-history text-secondary me-2"></i>
      <span class="fw-semibold">Recent Transactions</span>
    </div>
    <a href="<?= BASE_URL ?>/reports.php" class="btn btn-sm btn-outline-primary">View All</a>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0 align-middle">
      <thead class="table-light">
        <tr>
          <th>#</th><th>Member</th><th>Card Code</th>
          <th>Amount</th><th>Points</th><th>Type</th><th>Date</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($recent as $r): ?>
        <tr>
          <td class="text-muted small"><?= $r['id'] ?></td>
          <td class="fw-semibold"><?= e($r['name'] ?? 'Unregistered') ?></td>
          <td><code class="small"><?= e($r['card_code']) ?></code></td>
          <td>₱<?= number_format($r['amount'], 2) ?></td>
          <td><span class="badge bg-<?= $r['type']==='earn'?'success':'info' ?>"><?= number_format($r['points']) ?></span></td>
          <td>
            <span class="badge <?= $r['type']==='earn'?'bg-success-subtle text-success':'bg-info-subtle text-info' ?>">
              <i class="bi bi-<?= $r['type']==='earn'?'plus-circle':'gift' ?> me-1"></i><?= ucfirst($r['type']) ?>
            </span>
          </td>
          <td class="text-muted small"><?= date('M d, Y H:i', strtotime($r['created_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($recent)): ?>
        <tr><td colspan="7" class="text-center text-muted py-4">No transactions yet.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php
$extraJS = '<script>
const labels = ' . json_encode($chartLabels) . ';
const data   = ' . json_encode(array_map('floatval', $chartData)) . ';
new Chart(document.getElementById("salesChart"), {
    type: "bar",
    data: {
        labels,
        datasets: [{
            label: "Sales (₱)",
            data,
            backgroundColor: "rgba(13,110,253,.15)",
            borderColor: "rgba(13,110,253,.8)",
            borderWidth: 2,
            borderRadius: 6,
            fill: true,
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { display: false } },
        scales: {
            y: { beginAtZero: true, ticks: { callback: v => "₱"+v.toLocaleString() } }
        }
    }
});
</script>';
require_once __DIR__ . '/includes/footer.php';
