<?php
// ============================================================
//  export_users.php — CSV Export
//  Place in: /admin/export_users.php
// ============================================================
require_once 'includes/auth_check.php';

$search        = trim($_GET['search'] ?? '');
$status_filter = $_GET['status'] ?? '';

$where  = [];
$params = [];

if ($search !== '') {
    $where[]  = '(full_name LIKE ? OR username LIKE ? OR email LIKE ?)';
    $like     = "%{$search}%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

if ($status_filter !== '') {
    $where[]  = 'status = ?';
    $params[] = $status_filter;
}

$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$users = db_fetch_all(
    "SELECT id, full_name, username, email, phone, status, email_verified, last_login, created_at
     FROM users $where_sql ORDER BY created_at DESC",
    $params
);

// Log activity
db_execute(
    "INSERT INTO activity_log (admin_id, action, target_type, details, ip_address)
     VALUES (?, 'exported_users_csv', 'system', ?, ?)",
    [
        $current_admin['id'],
        'Exported ' . count($users) . ' users to CSV',
        $_SERVER['REMOTE_ADDR']
    ]
);

// Stream CSV
$filename = 'users_export_' . date('Y-m-d_His') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

$out = fopen('php://output', 'w');
// UTF-8 BOM for Excel compatibility
fwrite($out, "\xEF\xBB\xBF");

fputcsv($out, ['ID', 'Full Name', 'Username', 'Email', 'Phone', 'Status', 'Email Verified', 'Last Login', 'Registered']);

foreach ($users as $u) {
    fputcsv($out, [
        $u['id'],
        $u['full_name'],
        $u['username'],
        $u['email'],
        $u['phone'] ?? '',
        $u['status'],
        $u['email_verified'] ? 'Yes' : 'No',
        $u['last_login'] ?? 'Never',
        $u['created_at'],
    ]);
}

fclose($out);
exit;
