<?php
// Export Users as CSV (Excel-friendly)
// Access: Admin only
require_once __DIR__ . '/main/initial.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: admin_login.php');
    exit;
}

$filename = 'users_' . date('Ymd_His') . '.csv';
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');

// Ensure Excel reads as UTF-8
echo "\xEF\xBB\xBF"; // UTF-8 BOM

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

// Header row (Arabic)
fputcsv($out, [
    'رقم الشخص',
    'اسم الشخص',
    'اسم الشركة',
    'الهاتف',
    'تاريخ التسجيل',
    'حالة المسح'
]);

// Fetch users with latest scan status from qrcodes
$sql = 'SELECT u.id, u.name, u.company_name, u.phone, u.created_at,
        (SELECT scanned FROM qrcodes q WHERE q.user_id = u.id ORDER BY q.created_at DESC LIMIT 1) AS scanned
        FROM users u ORDER BY u.id ASC';
$stmt = $con->query($sql);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $status = ((int)($row['scanned'] ?? 0) === 1) ? 'تم المسح' : 'لم يُمسح';
    fputcsv($out, [
        $row['id'],
        $row['name'],
        $row['company_name'],
        $row['phone'],
        $row['created_at'],
        $status
    ]);
}

fclose($out);
exit;
