<?php
require_once __DIR__ . '/../includes/config.php';
header('Content-Type: application/json');

$leads      = readJSON(LEADS_FILE);
$gallery    = readJSON(GALLERY_FILE);
$packages   = readJSON(PACKAGES_FILE);
$sponsorship = readJSON(SPONSORSHIP_FILE);

$today = date('Y-m-d');
$weekStart = date('Y-m-d', strtotime('monday this week'));

$todayLeads = 0;
$weekLeads = 0;
$exhibitorLeads = 0;
$visitorLeads = 0;
$sponsorLeads = 0;
$newsletterLeads = 0;
$contactLeads = 0;

foreach ($leads as $lead) {
    $date = $lead['submitted_at'] ?? '';
    if (strpos($date, $today) === 0) $todayLeads++;
    if ($date >= $weekStart) $weekLeads++;

    $type = $lead['type'] ?? '';
    if ($type === 'exhibitor') $exhibitorLeads++;
    elseif ($type === 'visitor') $visitorLeads++;
    elseif ($type === 'sponsor') $sponsorLeads++;
    elseif ($type === 'newsletter') $newsletterLeads++;
    elseif ($type === 'contact') $contactLeads++;
}

echo json_encode([
    'success'                => true,
    'total_leads'            => count($leads),
    'exhibitor_leads'        => $exhibitorLeads,
    'visitor_leads'          => $visitorLeads,
    'sponsor_leads'          => $sponsorLeads,
    'newsletter_leads'       => $newsletterLeads,
    'contact_leads'          => $contactLeads,
    'total_gallery'          => count($gallery),
    'total_packages'         => count(array_filter($packages, fn($p) => !empty($p['active']))),
    'total_sponsorship_tiers'=> count(array_filter($sponsorship, fn($t) => !empty($t['active']))),
    'today_leads'            => $todayLeads,
    'this_week_leads'        => $weekLeads
]);
exit;
