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

$response = ['success' => false, 'message' => ''];

try {
    $dataDir = '../data';
    
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Get list of available assets
        if (!is_dir($dataDir)) {
            mkdir($dataDir, 0755, true);
        }
        
        $assets = [];
        $directories = scandir($dataDir);
        
        foreach ($directories as $dir) {
            if ($dir !== '.' && $dir !== '..' && is_dir($dataDir . '/' . $dir)) {
                $assets[] = $dir;
            }
        }
        
        $response['success'] = true;
        $response['assets'] = $assets;
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Create new asset folder
        $asset = $_POST['asset'] ?? '';
        
        if (empty($asset)) {
            throw new Exception('Asset name is required');
        }
        
        $assetDir = $dataDir . '/' . $asset;
        
        if (is_dir($assetDir)) {
            $response['success'] = true;
            $response['message'] = 'Asset folder already exists';
        } else {
            if (mkdir($assetDir, 0755, true)) {
                $response['success'] = true;
                $response['message'] = 'Asset folder created successfully';
            } else {
                throw new Exception('Failed to create asset folder');
            }
        }
    }
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>