<?php
// list_campaigns.php - Daftar campaign untuk dashboard tracker

$dir = __DIR__ . '/tracking';
if (!is_dir($dir)) {
    echo json_encode([]);
    exit;
}

$files = glob("$dir/camp_*.json");
$campaigns = [];

foreach ($files as $file) {
    $id = basename($file, '.json');
    $data = json_decode(file_get_contents($file), true);
    $time = $data['start_time'] ?? filemtime($file);
    $campaigns[] = [
        'id'   => $id,
        'time' => $time,
        'sent' => $data['sent'] ?? 0
    ];
}

usort($campaigns, fn($a, $b) => $b['time'] <=> $a['time']);

header('Content-Type: application/json');
echo json_encode($campaigns);