<?php
require_once 'db.php';
session_start();
if (!isset($_SESSION['user'])) { header('Location: login.php'); exit; }

$role = $_SESSION['user']['role'] ?? 'member';

// ===== Filters =====
$keyword  = trim($_GET['q'] ?? '');
$location = trim($_GET['loc'] ?? '');
$page     = max(1, (int)($_GET['page'] ?? 1));
$perPage  = 20;
$offset   = ($page - 1) * $perPage;

$conds  = ['status = 1']; // Active only
$params = []; $types = '';

if ($keyword !== '') {
  $conds[] = '(full_name LIKE ? OR staff_number LIKE ? OR email LIKE ? OR phone LIKE ?)';
  $kw = "%{$keyword}%";
  array_push($params, $kw, $kw, $kw, $kw);
  $types .= 'ssss';
}
if ($location !== '') {
  $conds[] = 'location = ?';
  $params[] = $location; $types .= 's';
}
$where = 'WHERE '.implode(' AND ', $conds);

// ===== Count =====
$sqlCount = "SELECT COUNT(*) c FROM members $where";
$stmt = $conn->prepare($sqlCount);
if ($types) $stmt->bind_param($types, ...$params);
$stmt->execute();
$total = (int)$stmt->get_result()->fetch_assoc()['c'];
$stmt->close();

// ===== Rows =====
$sqlRows = "
  SELECT id, full_name, staff_number, email, phone, location, official_member_since
  FROM members
  $where
  ORDER BY full_name ASC
  LIMIT ? OFFSET ?
";
$paramsRows = $params; $typesRows = $types.'ii';
$paramsRows[] = $perPage; $paramsRows[] = $offset;

$stmt = $conn->prepare($sqlRows);
$stmt->bind_param($typesRows, ...$paramsRows);
$stmt->execute();
$res  = $stmt->get_result();
$rows = $res->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ===== Locations (distinct from members) =====
$locs = [];
$q = $conn->query("SELECT DISTINCT location FROM members WHERE COALESCE(location,'')<>'' ORDER BY location");
if ($q) while ($r = $q->fetch_assoc()) $locs[] = $r['location'];

$totalPages = max(1, (int)ceil($total / $perPage));

ob_start();
?>
<style>
.card{background:#fff;border:1px solid #e5e7eb;border-radius:10px}
.card-header{padding:12px 14px;border-bottom:1px solid #f0f0f0;font-weight:600}
.card-body{padding:12px 14px}
.table{width:100%;border-collapse:separate;border-spacing:0}
.table th,.table td{padding:10px 12px;border-bottom:1px solid #f0f0f0;vertical-align:middle}
.table thead th{background:#f8fafc;font-size:12px;text-transform:uppercase;letter-spacing:.02em;color:#4b5563}
.table tbody tr:hover{background:#fafafa}
.input,.select{padding:8px;border:1px solid #d1d5db;border-radius:8px}
.btn{border:1px solid #d1d5db;background:#fff;border-radius:8px;padding:6px 10px;font-size:13px;cursor:pointer}
.btn-primary{background:#2563eb;color:#fff;border-color:#2563eb}
.btn-light{background:#f3f4f6}
.badge{display:inline-block;padding:3px 8px;border-radius:9999px;font-size:12px}
.toolbar{display:flex;gap:8px;flex-wrap:wrap;margin:10px 0}
.pager{display:flex;gap:6px;flex-wrap:wrap;margin-top:12px}
.pager a{padding:6px 10px;border:1px solid #d1d5db;border-radius:8px;text-decoration:none;color:#111}
.pager a.active{background:#2563eb;color:#fff;border-color:#2563eb}
.small{font-size:12px;color:#6b7280}
</style>

<div class="content">
  <h2>📊 Active Users Report</h2>

  <div class="card" style="margin:12px 0;">
    <div class="card-body">
      <form method="get" class="toolbar">
        <input class="input" type="text" name="q" placeholder="Cari nama / staff no / email / phone" value="<?= htmlspecialchars($keyword) ?>" style="min-width:260px">
        <select class="select" name="loc">
          <option value="">Semua Lokasi</option>
          <?php foreach ($locs as $loc): ?>
            <option value="<?= htmlspecialchars($loc) ?>" <?= $loc===$location?'selected':'' ?>><?= htmlspecialchars($loc) ?></option>
          <?php endforeach; ?>
        </select>
        <button class="btn btn-primary" type="submit">Filter</button>
        <?php if (($role ?? '') === 'admin'): ?>
          <a class="btn btn-light" href="report-active-users-export.php?<?= http_build_query(['q'=>$keyword,'loc'=>$location]) ?>">Export CSV</a>
        <?php endif; ?>
      </form>

      <div class="small">Total Active: <strong><?= number_format($total) ?></strong></div>
    </div>
  </div>

  <div class="card">
    <div class="card-body" style="padding:0">
      <table class="table">
        <thead>
          <tr>
            <th style="width:60px">#</th>
            <th>Full Name</th>
            <th>Staff No</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Location</th>
            <th style="width:160px">Official Since</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="7"><em class="small">Tiada rekod.</em></td></tr>
          <?php else: $i=$offset+1; foreach ($rows as $r): ?>
            <tr>
              <td><?= $i++ ?></td>
              <td><?= htmlspecialchars($r['full_name']) ?></td>
              <td><?= htmlspecialchars($r['staff_number']) ?></td>
              <td><a href="mailto:<?= htmlspecialchars($r['email']) ?>"><?= htmlspecialchars($r['email']) ?></a></td>
              <td><a href="tel:<?= htmlspecialchars($r['phone']) ?>"><?= htmlspecialchars($r['phone']) ?></a></td>
              <td><?= htmlspecialchars($r['location']) ?></td>
              <td><?= $r['official_member_since'] ? date('d/m/Y', strtotime($r['official_member_since'])) : '-' ?></td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="pager">
    <?php for ($p=1; $p<=$totalPages; $p++): 
      $qs = $_GET; $qs['page']=$p; $href='?'.http_build_query($qs); ?>
      <a href="<?= $href ?>" class="<?= $p===$page?'active':'' ?>"><?= $p ?></a>
    <?php endfor; ?>
  </div>
</div>

<?php
$content = ob_get_clean();
include 'layout.php';
