<?php
declare(strict_types=1);
require __DIR__ . '/config.php';
require_login();

$leads = [];
if (is_file(LEAD_STORE)) {
    $json = file_get_contents(LEAD_STORE);
    $decoded = json_decode($json ?: '[]', true);
    if (is_array($decoded)) {
        $leads = $decoded;
    }
}

if (isset($_GET['export']) && $_GET['export'] === 'json') {
    header('Content-Type: application/json; charset=utf-8');
    header('Content-Disposition: attachment; filename="colorjet-leads-' . date('Ymd-His') . '.json"');
    echo json_encode($leads, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="colorjet-leads-' . date('Ymd-His') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID', 'Type', 'Created At', 'Page', 'Source', 'IP', 'Data JSON']);
    foreach ($leads as $lead) {
        fputcsv($out, [
            $lead['id'] ?? '',
            $lead['type'] ?? '',
            $lead['created_at'] ?? '',
            $lead['page'] ?? '',
            $lead['source'] ?? '',
            $lead['ip'] ?? '',
            json_encode($lead['data'] ?? [], JSON_UNESCAPED_UNICODE),
        ]);
    }
    fclose($out);
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>COLORJET Lead Dashboard</title>
<link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
<main>
<section class="page-hero">
<div class="container">
<span class="eyebrow">Lead Dashboard</span>
<h1>COLORJET Website Leads</h1>
<p>Total saved leads: <?= count($leads) ?></p>
<div class="cta-row">
<a class="btn btn-primary" href="?export=csv">Export CSV</a>
<a class="btn btn-glass" href="?export=json">Export JSON</a>
<a class="btn btn-orange" href="logout.php">Logout</a>
</div>
</div>
</section>
<section class="section">
<div class="container">
<div class="lead-table-wrap">
<table>
<thead>
<tr><th>ID</th><th>Type</th><th>Date</th><th>Page</th><th>Lead Data</th></tr>
</thead>
<tbody>
<?php if (!$leads): ?>
<tr><td colspan="5">No lead found yet.</td></tr>
<?php endif; ?>
<?php foreach ($leads as $lead): ?>
<tr>
<td><?= h((string)($lead['id'] ?? '')) ?></td>
<td><?= h((string)($lead['type'] ?? '')) ?></td>
<td><?= h((string)($lead['created_at'] ?? '')) ?></td>
<td><?= h((string)($lead['page'] ?? '')) ?></td>
<td><pre><?= h(json_encode($lead['data'] ?? [], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</section>
</main>
</body>
</html>
