<?php
include('../config/db.php');
include('../includes/auth.php');
include('partials/header.php');

// ── Stats ─────────────────────────────────────────────────────────────────────
$today = date('Y-m-d');

$sTotal     = (int)$conn->query('SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL')->fetch_assoc()['c'];
$activeStmt = $conn->prepare('SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL AND start_date <= ? AND end_date >= ?');
$activeStmt->bind_param('ss', $today, $today);
$activeStmt->execute();
$sActive = (int)$activeStmt->get_result()->fetch_assoc()['c'];
$activeStmt->close();

$sCustomers = (int)$conn->query('SELECT COUNT(*) c FROM customers')->fetch_assoc()['c'];

$todayClaimsStmt = $conn->prepare('SELECT COUNT(*) c FROM voucher_claims WHERE DATE(claimed_at)=?');
$todayClaimsStmt->bind_param('s', $today);
$todayClaimsStmt->execute();
$sTodayClaims = (int)$todayClaimsStmt->get_result()->fetch_assoc()['c'];
$todayClaimsStmt->close();

$sClaims    = (int)$conn->query('SELECT COUNT(*) c FROM voucher_claims')->fetch_assoc()['c'];
$sRedeemed  = (int)$conn->query("SELECT COUNT(*) c FROM voucher_claims WHERE status='redeemed'")->fetch_assoc()['c'];
$sPending   = $sClaims - $sRedeemed;
$sRate      = $sClaims > 0 ? round($sRedeemed / $sClaims * 100) : 0;

// ── Recent activity ───────────────────────────────────────────────────────────
$recentActivity = $conn->query("
  SELECT c.name, c.phone, v.event_name, v.type, v.code, vc.status, vc.claimed_at, vc.redeemed_at
  FROM voucher_claims vc
  JOIN customers c ON vc.customer_id = c.id
  JOIN vouchers v ON vc.voucher_id = v.id
  ORDER BY vc.id DESC LIMIT 8
");

// ── Top vouchers by claims ────────────────────────────────────────────────────
$topVouchers = $conn->query("
  SELECT v.event_name, v.type, v.code,
         COUNT(vc.id) AS total_claims,
         SUM(vc.status='redeemed') AS redeemed,
         v.end_date
  FROM vouchers v
  LEFT JOIN vouchers cv ON (cv.id = v.id OR cv.parent_voucher_id = v.id)
  LEFT JOIN voucher_claims vc ON vc.voucher_id = cv.id
  WHERE v.parent_voucher_id IS NULL
  GROUP BY v.id
  ORDER BY total_claims DESC LIMIT 5
");

// ── Claims per day last 7 days ────────────────────────────────────────────────
$dailyData = [];
$stmtC = $conn->prepare('SELECT COUNT(*) c FROM voucher_claims WHERE DATE(claimed_at)=?');
$stmtR = $conn->prepare('SELECT COUNT(*) c FROM voucher_claims WHERE DATE(redeemed_at)=?');
for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $label = date('D', strtotime($d));
    $stmtC->bind_param('s', $d); $stmtC->execute();
    $c = (int)$stmtC->get_result()->fetch_assoc()['c'];
    $stmtR->bind_param('s', $d); $stmtR->execute();
    $r = (int)$stmtR->get_result()->fetch_assoc()['c'];
    $dailyData[] = ['label' => $label, 'claims' => $c, 'redeemed' => $r];
}
$stmtC->close(); $stmtR->close();
?>

<div class="pg-title">Dashboard</div>
<div class="pg-sub">Live overview — <?= date('l, d F Y') ?></div>

<!-- ── Row 1: Core Stats ── -->
<div class="row g-3 mb-3">
  <?php foreach ([
    ['bi-ticket-perforated-fill', 'var(--accent)', $sTotal,      'Total Vouchers'],
    ['bi-circle-fill',            'var(--green)',  $sActive,     'Active Now'],
    ['bi-people-fill',            'var(--blue)',   $sCustomers,  'Registered Users'],
    ['bi-calendar-check',         'var(--yellow)', $sTodayClaims,'Claims Today'],
  ] as [$icon,$color,$val,$lbl]): ?>
  <div class="col-6 col-md-3">
    <div class="stat-card">
      <div class="stat-icon" style="color:<?= $color ?>"><i class="bi <?= $icon ?>"></i></div>
      <div class="stat-val"><?= $val ?></div>
      <div class="stat-lbl"><?= $lbl ?></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- ── Row 2: Claim/Redeem Stats ── -->
<div class="row g-3 mb-4">
  <div class="col-6 col-md-3">
    <div class="stat-card">
      <div class="stat-icon" style="color:var(--blue)"><i class="bi bi-hand-index-thumb-fill"></i></div>
      <div class="stat-val"><?= $sClaims ?></div>
      <div class="stat-lbl">Total Claims</div>
      <div style="font-size:11px;color:var(--muted);margin-top:4px">Users who saved voucher</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="stat-card">
      <div class="stat-icon" style="color:var(--green)"><i class="bi bi-check-circle-fill"></i></div>
      <div class="stat-val"><?= $sRedeemed ?></div>
      <div class="stat-lbl">Redeemed</div>
      <div style="font-size:11px;color:var(--muted);margin-top:4px">Scanned &amp; used at POS</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="stat-card">
      <div class="stat-icon" style="color:var(--yellow)"><i class="bi bi-hourglass-split"></i></div>
      <div class="stat-val"><?= $sPending ?></div>
      <div class="stat-lbl">Pending</div>
      <div style="font-size:11px;color:var(--muted);margin-top:4px">Claimed, not yet used</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="stat-card">
      <div class="stat-icon" style="color:var(--accent)"><i class="bi bi-percent"></i></div>
      <div class="stat-val"><?= $sRate ?>%</div>
      <div class="stat-lbl">Redemption Rate</div>
      <div style="font-size:11px;color:var(--muted);margin-top:4px"><?= $sRedeemed ?> of <?= $sClaims ?></div>
    </div>
  </div>
</div>

<!-- ── Clarification Banner ── -->
<div class="adm-card mb-4" style="background:var(--accent-dim);border-color:rgba(232,160,32,.3);padding:14px 18px">
  <div style="display:flex;align-items:flex-start;gap:12px">
    <i class="bi bi-info-circle-fill" style="color:var(--accent);font-size:18px;flex-shrink:0;margin-top:1px"></i>
    <div style="font-size:13px;line-height:1.6">
      <strong style="color:var(--accent)">Claim vs Redeem explained:</strong>
      A <strong>Claim</strong> = user saves the voucher &amp; gets their QR code.
      A <strong>Redemption</strong> = staff scans the QR at point of sale and marks it used.
      Users can claim a voucher multiple times (up to the <em>Max Per User</em> limit you set on the voucher).
    </div>
  </div>
</div>

<!-- ── Middle Row: Chart + Top Vouchers ── -->
<div class="row g-4 mb-4">
  <div class="col-md-7">
    <div class="adm-card" style="height:100%">
      <div style="font-size:13.5px;font-weight:700;margin-bottom:16px;display:flex;justify-content:space-between;align-items:center">
        <span>Last 7 Days Activity</span>
        <span style="font-size:11px;color:var(--muted);font-weight:400">Claims &amp; Redemptions</span>
      </div>
      <canvas id="chartBar" style="max-height:200px"></canvas>
      <div style="display:flex;gap:18px;margin-top:12px">
        <span style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted)">
          <span style="width:12px;height:12px;border-radius:3px;background:#4b9eff;display:inline-block"></span>Claims
        </span>
        <span style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted)">
          <span style="width:12px;height:12px;border-radius:3px;background:#2dbd87;display:inline-block"></span>Redeemed
        </span>
      </div>
    </div>
  </div>

  <div class="col-md-5">
    <div class="adm-card" style="height:100%;padding:0;overflow:hidden">
      <div class="adm-card-header"><span>Top Vouchers by Claims</span></div>
      <div style="padding:6px 0">
      <?php while ($vr = $topVouchers->fetch_assoc()):
        $pct = $vr['total_claims'] > 0 ? round($vr['redeemed'] / $vr['total_claims'] * 100) : 0;
        $isExp = $vr['end_date'] < $today;
      ?>
      <div style="padding:12px 18px;border-bottom:1px solid rgba(35,40,57,.5)">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
          <div style="min-width:0">
            <div style="font-size:13px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?= htmlspecialchars($vr['event_name']) ?></div>
            <?php if ($vr['type']): ?><div style="font-size:11px;color:var(--muted)"><?= htmlspecialchars($vr['type']) ?></div><?php endif; ?>
          </div>
          <div style="text-align:right;flex-shrink:0;margin-left:10px">
            <div style="font-family:var(--mono);font-size:15px;font-weight:700;color:var(--accent)"><?= $vr['total_claims'] ?></div>
            <div style="font-size:10px;color:var(--muted)">claims</div>
          </div>
        </div>
        <div style="background:var(--bg);border-radius:4px;height:4px;overflow:hidden">
          <div style="background:var(--green);height:100%;width:<?= $pct ?>%;border-radius:4px"></div>
        </div>
        <div style="font-size:10.5px;color:var(--muted);margin-top:4px">
          <?= $vr['redeemed'] ?> redeemed · <?= $pct ?>% rate
          <?= $isExp ? ' · <span style="color:var(--red)">Expired</span>' : '' ?>
        </div>
      </div>
      <?php endwhile; ?>
      </div>
    </div>
  </div>
</div>

<!-- ── Recent Activity ── -->
<div class="adm-card" style="padding:0;overflow:hidden">
  <div class="adm-card-header">
    <span>Recent Activity</span>
    <a href="claims.php" class="btn-ghost" style="font-size:12px;padding:6px 12px">View All <i class="bi bi-arrow-right"></i></a>
  </div>
  <div class="table-responsive">
  <table class="adm-table">
    <thead>
      <tr>
        <th>Customer</th>
        <th>Voucher</th>
        <th>Action</th>
        <th class="d-none d-md-table-cell">When</th>
      </tr>
    </thead>
    <tbody>
    <?php while ($r = $recentActivity->fetch_assoc()):
      $isRedeemed = $r['status'] === 'redeemed';
      $when = $isRedeemed && $r['redeemed_at'] ? $r['redeemed_at'] : $r['claimed_at'];
      $diff = time() - strtotime($when);
      if ($diff < 60) $timeAgo = $diff . 's ago';
      elseif ($diff < 3600) $timeAgo = floor($diff/60) . 'm ago';
      elseif ($diff < 86400) $timeAgo = floor($diff/3600) . 'h ago';
      else $timeAgo = date('d M', strtotime($when));
    ?>
    <tr>
      <td>
        <div style="font-weight:600"><?= htmlspecialchars($r['name']) ?></div>
        <div style="font-size:11.5px;color:var(--muted)"><?= htmlspecialchars($r['phone']) ?></div>
      </td>
      <td>
        <div style="font-size:13px"><?= htmlspecialchars($r['event_name']) ?></div>
        <?php if ($r['type']): ?><div style="font-size:11px;color:var(--muted)"><?= htmlspecialchars($r['type']) ?></div><?php endif; ?>
      </td>
      <td>
        <?php if ($isRedeemed): ?>
          <span class="badge-redeemed"><i class="bi bi-check-circle-fill"></i> Redeemed</span>
        <?php else: ?>
          <span class="badge-pending"><i class="bi bi-bookmark-fill"></i> Claimed</span>
        <?php endif; ?>
      </td>
      <td class="d-none d-md-table-cell" style="font-size:12px;color:var(--muted)"><?= $timeAgo ?></td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const labels   = <?= json_encode(array_column($dailyData, 'label')) ?>;
const claims   = <?= json_encode(array_column($dailyData, 'claims')) ?>;
const redeemed = <?= json_encode(array_column($dailyData, 'redeemed')) ?>;

new Chart(document.getElementById('chartBar'), {
  type: 'bar',
  data: {
    labels,
    datasets: [
      { label:'Claims',   data:claims,   backgroundColor:'rgba(75,158,255,.75)',  borderRadius:5, borderSkipped:false },
      { label:'Redeemed', data:redeemed, backgroundColor:'rgba(45,189,135,.75)', borderRadius:5, borderSkipped:false },
    ]
  },
  options: {
    responsive:true, maintainAspectRatio:true,
    plugins:{ legend:{display:false} },
    scales:{
      x:{ grid:{color:'rgba(255,255,255,.04)'}, ticks:{color:'#6b7394',font:{size:11}} },
      y:{ grid:{color:'rgba(255,255,255,.04)'}, ticks:{color:'#6b7394',font:{size:11},stepSize:1,beginAtZero:true} }
    }
  }
});
</script>

<?php include('partials/footer.php'); ?>
