<?php
session_start();
$page_title = 'QR Scan Activity';
$active_nav = 'qr_scans';
include("includes/header.php");

$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$date_to   = $_GET['date_to']   ?? date('Y-m-d');

$today_count = $conn->prepare("SELECT COUNT(*) FROM qr_scans WHERE restaurant_id=? AND DATE(scanned_at)=CURDATE()");
$today_count->bind_param("i",$__rid); $today_count->execute();
$today_count = $today_count->get_result()->fetch_row()[0];

$week_count = $conn->prepare("SELECT COUNT(*) FROM qr_scans WHERE restaurant_id=? AND scanned_at>=NOW()-INTERVAL 7 DAY");
$week_count->bind_param("i",$__rid); $week_count->execute();
$week_count = $week_count->get_result()->fetch_row()[0];

$total_count = $conn->prepare("SELECT COUNT(*) FROM qr_scans WHERE restaurant_id=?");
$total_count->bind_param("i",$__rid); $total_count->execute();
$total_count = $total_count->get_result()->fetch_row()[0];

$unique_count = $conn->prepare("SELECT COUNT(DISTINCT user_id) FROM qr_scans WHERE restaurant_id=? AND user_id IS NOT NULL");
$unique_count->bind_param("i",$__rid); $unique_count->execute();
$unique_count = $unique_count->get_result()->fetch_row()[0];

$daily = $conn->prepare("SELECT DATE(scanned_at) as day, COUNT(*) as cnt FROM qr_scans WHERE restaurant_id=? AND scanned_at>=NOW()-INTERVAL 14 DAY GROUP BY DATE(scanned_at) ORDER BY day ASC");
$daily->bind_param("i",$__rid); $daily->execute();
$daily_data = $daily->get_result()->fetch_all(MYSQLI_ASSOC);
$daily_map = [];
foreach ($daily_data as $d) $daily_map[$d['day']] = $d['cnt'];
$days_labels = []; $days_vals = [];
for ($i=13; $i>=0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $days_labels[] = date('j M', strtotime($d));
    $days_vals[]   = $daily_map[$d] ?? 0;
}
$max_day = max(array_merge([1], $days_vals));

$q = "SELECT qs.*,u.name as customer_name,u.email as customer_email FROM qr_scans qs LEFT JOIN users u ON qs.user_id=u.id WHERE qs.restaurant_id=? AND DATE(qs.scanned_at) BETWEEN ? AND ? ORDER BY qs.scanned_at DESC LIMIT 200";
$st = $conn->prepare($q); $st->bind_param("iss",$__rid,$date_from,$date_to); $st->execute();
$scans = $st->get_result();
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">QR Scan Activity</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Track every customer who scanned your QR menu</p>
  </div>
  <form method="GET" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
    <input type="date" name="date_from" value="<?php echo $date_from; ?>" style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 10px;font-size:.82rem;font-family:var(--font);outline:none">
    <span style="color:var(--text-muted);font-size:.8rem">to</span>
    <input type="date" name="date_to" value="<?php echo $date_to; ?>" style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 10px;font-size:.82rem;font-family:var(--font);outline:none">
    <button type="submit" class="btn btn-primary btn-sm">Filter</button>
    <a href="qr_scans.php" class="btn btn-secondary btn-sm">Reset</a>
  </form>
</div>

<div class="grid-4" style="margin-bottom:24px">
  <?php foreach ([["Today's Scans",$today_count,'#225AE3','#EEF3FD'],["This Week",$week_count,'#F59E0B','#FFFBEB'],["All Time",$total_count,'#10B981','#F0FDF4'],["Unique Customers",$unique_count,'#8B5CF6','#F5F3FF']] as [$label,$val,$col,$bg]): ?>
  <div class="card" style="padding:18px 20px;border-top:3px solid <?php echo $col; ?>">
    <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px"><?php echo $label; ?></div>
    <div style="font-size:1.55rem;font-weight:800;color:<?php echo $col; ?>"><?php echo number_format($val); ?></div>
  </div>
  <?php endforeach; ?>
</div>

<div class="card" style="margin-bottom:24px">
  <div class="card-header"><h3>Daily Scans — Last 14 Days</h3></div>
  <div class="card-body">
    <div style="display:flex;align-items:flex-end;gap:6px;height:130px;padding-bottom:8px;overflow-x:auto">
      <?php foreach ($days_vals as $i => $v):
        $h = $max_day > 0 ? max(4, round(($v/$max_day)*115)) : 4;
        $it = ($i === 13);
      ?>
      <div style="flex:0 0 auto;min-width:32px;display:flex;flex-direction:column;align-items:center;gap:5px">
        <div style="font-size:.6rem;color:var(--text-muted);font-weight:600"><?php echo $v > 0 ? $v : ''; ?></div>
        <div style="width:28px;height:<?php echo $h; ?>px;background:<?php echo $it?'var(--primary)':'var(--primary-bg)'; ?>;border-radius:5px 5px 0 0"></div>
        <div style="font-size:.58rem;color:<?php echo $it?'var(--primary)':'var(--text-muted)'; ?>;font-weight:<?php echo $it?'700':'500'; ?>;white-space:nowrap"><?php echo $days_labels[$i]; ?></div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header">
    <h3>Scan Log</h3>
    <span style="font-size:.78rem;color:var(--text-muted)"><?php echo $scans->num_rows; ?> records</span>
  </div>
  <?php if ($scans->num_rows === 0): ?>
    <div style="padding:56px;text-align:center;color:var(--text-muted)">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><path d="M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2"/><rect x="7" y="7" width="10" height="10" rx="1"/></svg>
      <p style="font-weight:700;margin-bottom:4px">No scans in this period</p>
    </div>
  <?php else: ?>
    <div class="table-scroll">
<table class="data-table">
    <thead><tr><th>Customer</th><th>Email</th><th>IP Address</th><th>Date & Time</th></tr></thead>
    <tbody>
    <?php while ($s = $scans->fetch_assoc()): ?>
    <tr>
      <td>
        <div style="display:flex;align-items:center;gap:10px">
          <div style="width:32px;height:32px;border-radius:50%;background:var(--primary-bg);display:flex;align-items:center;justify-content:center;font-size:.7rem;font-weight:800;color:var(--primary);flex-shrink:0">
            <?php echo $s['customer_name'] ? strtoupper(substr($s['customer_name'],0,1)) : '?'; ?>
          </div>
          <span style="font-weight:600;font-size:.84rem"><?php echo htmlspecialchars($s['customer_name'] ?? 'Guest'); ?></span>
        </div>
      </td>
      <td style="font-size:.8rem;color:var(--text-muted)"><?php echo htmlspecialchars($s['customer_email'] ?? '—'); ?></td>
      <td style="font-size:.75rem;color:var(--text-muted)"><?php echo htmlspecialchars($s['ip_address'] ?? '—'); ?></td>
      <td style="font-size:.8rem;color:var(--text-muted);white-space:nowrap"><?php echo date('M j, Y g:i A', strtotime($s['scanned_at'])); ?></td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
</div>
  <?php endif; ?>
</div>

<?php include("includes/footer.php"); ?>
