<?php
require_once dirname(__DIR__) . '/config.php';
require_once 'session_manager.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$asset = $_GET['asset'] ?? '';

if (empty($asset)) {
    echo json_encode([]);
    exit;
}

// Detect user session and get user-specific data path
detectAndStartUserSession();
$userDataPath = getCurrentUserDataPath();

if (!$userDataPath) {
    echo json_encode([]);
    exit;
}

$dataDir = rtrim($userDataPath, '/');
$assetFolder = $dataDir . '/' . $asset;

try {
    if (!is_dir($assetFolder)) {
        echo json_encode([]);
        exit;
    }
    
    $datasets = [];
    $assetDirectories = scandir($assetFolder);
    
    foreach ($assetDirectories as $dataset) {
        if ($dataset === '.' || $dataset === '..') continue;
        
        $datasetPath = $assetFolder . '/' . $dataset;
        $combinedFile = $datasetPath . '/Combined_data.json';
        $candleFile = $datasetPath . '/candle_data.json';
        
        if (is_dir($datasetPath) && (file_exists($combinedFile) || file_exists($candleFile))) {
            $datasets[] = $dataset;
        }
    }
    
    // Sort datasets (newest first)
    usort($datasets, function($a, $b) {
        return strcmp($b, $a);
    });
    
    echo json_encode($datasets);
    
} catch (Exception $e) {
    echo json_encode([]);
}
?>