<?php
declare(strict_types=1);

/** Exporta em CSV os leads que batem com os filtros atuais do painel. */

require __DIR__ . '/auth.php';
admin_require_login();

function q_date_export(string $key, string $fallback): string
{
    $v = (string) ($_GET[$key] ?? '');
    return preg_match('/^\d{4}-\d{2}-\d{2}$/', $v) === 1 ? $v : $fallback;
}

$filters = [
    'from' => q_date_export('from', gmdate('Y-m-d', strtotime('-29 days'))),
    'to' => q_date_export('to', gmdate('Y-m-d')),
    'q' => trim((string) ($_GET['q'] ?? '')),
    'status' => in_array($_GET['status'] ?? '', ['ok', 'failed'], true) ? (string) $_GET['status'] : '',
    'ftd' => in_array($_GET['ftd'] ?? '', ['0', '1'], true) ? (string) $_GET['ftd'] : '',
    'origin' => in_array($_GET['origin'] ?? '', ['landing', 'crm'], true) ? (string) $_GET['origin'] : '',
];

$filename = 'leads_' . $filters['from'] . '_' . $filters['to'] . '.csv';

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

$out = fopen('php://output', 'w');
// BOM para o Excel abrir os acentos corretamente.
fwrite($out, "\xEF\xBB\xBF");

fputcsv($out, [
    'data', 'data_crm', 'origem', 'nome', 'first_name', 'last_name', 'email', 'telefone',
    'pais', 'idioma', 'funil', 'source', 'ip', 'envio', 'http', 'erro',
    'uid', 'status_crm', 'afiliado', 'ftd', 'ftd_em', 'sincronizado_em',
], ';');

// Páginas de 500 para não carregar a base inteira na memória.
$offset = 0;
do {
    $rows = store_list_leads($filters, 500, $offset);
    foreach ($rows as $l) {
        fputcsv($out, [
            (string) $l['created_at'],
            (string) ($l['crm_created_at'] ?? ''),
            (string) $l['origin'],
            (string) $l['name'],
            (string) $l['first_name'],
            (string) $l['last_name'],
            (string) $l['email'],
            (string) $l['phone'],
            (string) $l['country'],
            (string) ($l['lang'] ?? ''),
            (string) ($l['funnel_name'] ?? ''),
            (string) ($l['source'] ?? ''),
            (string) ($l['ip'] ?? ''),
            (string) $l['send_status'],
            (string) ($l['http_code'] ?? ''),
            (string) ($l['error'] ?? ''),
            (string) ($l['uid'] ?? ''),
            (string) ($l['status_title'] ?? ''),
            (string) ($l['affiliate_name'] ?? ''),
            (int) $l['ftd'] === 1 ? 'sim' : 'nao',
            (string) ($l['ftd_time'] ?? ''),
            (string) ($l['synced_at'] ?? ''),
        ], ';');
    }
    $offset += 500;
} while (count($rows) === 500);

fclose($out);
