<?php
require_once 'db.php';
session_start();
if (!isset($_SESSION['user']) || ($_SESSION['user']['role'] ?? '') !== 'admin') {
  http_response_code(403); exit('Admins only');
}

$keyword  = trim($_GET['q'] ?? '');
$location = trim($_GET['loc'] ?? '');

$conds=['status=1']; $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);

$sql="SELECT full_name,staff_number,email,phone,location,official_member_since FROM members $where ORDER BY full_name ASC";
$stmt=$conn->prepare($sql);
if ($types!=='') $stmt->bind_param($types, ...$params);
$stmt->execute(); $res=$stmt->get_result();

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=active_users.csv');
$fp=fopen('php://output','w');
fputcsv($fp, ['Full Name','Staff Number','Email','Phone','Location','Official Member Since']);
while($row=$res->fetch_assoc()){
  $row['official_member_since'] = $row['official_member_since'] ? date('Y-m-d', strtotime($row['official_member_since'])) : '';
  fputcsv($fp, $row);
}
fclose($fp);
