<?php
require_once 'session_manager.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['assetName'])) {
    echo json_encode(['success' => false, 'message' => 'Asset name is required']);
    exit;
}

$assetName = $input['assetName'];

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

if (!$userDataPath) {
    echo json_encode(['success' => false, 'message' => 'User session not found']);
    exit;
}

$dataDir = rtrim($userDataPath, '/');

try {
    // Check if data directory exists
    if (!is_dir($dataDir)) {
        echo json_encode(['success' => false, 'message' => 'Data directory not found']);
        exit;
    }
    
    // Try exact match first, then simplified format
    $assetFolder = $dataDir . '/' . $assetName;
    $searchedName = $assetName;
    
    if (!is_dir($assetFolder)) {
        // Try simplified format
        $simplifiedAssetName = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $assetName));
        $assetFolder = $dataDir . '/' . $simplifiedAssetName;
        $searchedName = $simplifiedAssetName;
    }
    
    if (!is_dir($assetFolder)) {
        // Scan for available directories
        $availableDirs = array_filter(scandir($dataDir), function($dir) use ($dataDir) {
            return $dir !== '.' && $dir !== '..' && is_dir($dataDir . '/' . $dir);
        });
        
        echo json_encode([
            'success' => true, 
            'datasets' => [], 
            'message' => 'No folder found for asset',
            'searchedFor' => $searchedName,
            'availableFolders' => array_values($availableDirs),
            'username' => $_SESSION['username'] ?? 'unknown'
        ]);
        exit;
    }
    
    // Get all folders inside the asset folder
    $datasets = [];
    $assetDirectories = scandir($assetFolder);
    
    foreach ($assetDirectories as $dataset) {
        if ($dataset === '.' || $dataset === '..') continue;
        
        $datasetPath = $assetFolder . '/' . $dataset;
        if (is_dir($datasetPath)) {
            $datasets[] = $dataset;
        }
    }
    
    // Sort datasets by name (newest first if they contain timestamps)
    usort($datasets, function($a, $b) {
        // If datasets contain timestamps, sort by date (newest first)
        if (preg_match('/\d{2}-\d{2}-\d{4}/', $a) && preg_match('/\d{2}-\d{2}-\d{4}/', $b)) {
            return strcmp($b, $a); // Reverse order for newest first
        }
        return strcmp($a, $b);
    });
    
    echo json_encode([
        'success' => true,
        'datasets' => $datasets,
        'assetFolder' => basename($assetFolder),
        'totalDatasets' => count($datasets)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error scanning directories: ' . $e->getMessage()
    ]);
}
?>