<?php
// api/members_export.php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

requireRole('any');

// Fetch all members
$stmt = $pdo->query("SELECT full_name, email, phone, address, unit, branch, date_joined, status, experiences FROM members ORDER BY full_name ASC");
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="members_export_' . date('Y-m-d') . '.csv"');

// Open output stream
$output = fopen('php://output', 'w');

// Write header row
fputcsv($output, ['full_name', 'email', 'phone', 'address', 'unit', 'branch', 'date_joined', 'status', 'experiences']);

// Write data rows
foreach ($members as $member) {
    fputcsv($output, $member);
}

fclose($output);
exit;
