<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/auth.php';

$leads = readJSON(LEADS_FILE);
$filename = 'kenya-expo-leads-' . date('Y-m-d') . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

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

// BOM for Excel
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

// Headers
fputcsv($output, ['ID', 'Name', 'Email', 'Phone', 'Company', 'Country', 'Type', 'Interest', 'Sector', 'Job Title', 'Website', 'Budget', 'Source', 'Message', 'IP Address', 'Submitted At']);

foreach ($leads as $lead) {
    fputcsv($output, [
        $lead['id'] ?? '',
        $lead['name'] ?? '',
        $lead['email'] ?? '',
        $lead['phone'] ?? '',
        $lead['company'] ?? '',
        $lead['country'] ?? '',
        $lead['type'] ?? '',
        $lead['interest'] ?? '',
        $lead['sector'] ?? '',
        $lead['job_title'] ?? '',
        $lead['website'] ?? '',
        $lead['budget'] ?? '',
        $lead['source'] ?? '',
        $lead['message'] ?? '',
        $lead['ip'] ?? '',
        $lead['submitted_at'] ?? ''
    ]);
}

fclose($output);
exit;
