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

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

try {
    $allowedUsers = ['unrealengine_developer', 'unrealengine_admin', 'unrealengine_user1', 'unrealengine_user2'];
    $sharedDataPath = DATA_DIR;
    $setupResults = [];
    
    // Check if shared data exists
    if (!is_dir($sharedDataPath)) {
        echo json_encode(['success' => false, 'message' => 'Shared data folder not found']);
        exit;
    }
    
    // Get list of asset folders in shared data (excluding user folders)
    $assetFolders = [];
    $items = scandir($sharedDataPath);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..' || in_array($item, $allowedUsers)) {
            continue;
        }
        
        $itemPath = $sharedDataPath . '/' . $item;
        if (is_dir($itemPath)) {
            $assetFolders[] = $item;
        }
    }
    
    // Create user-specific folders and copy data
    foreach ($allowedUsers as $username) {
        $userDataPath = $sharedDataPath . '/' . $username;
        
        // Create user data folder if it doesn't exist
        if (!file_exists($userDataPath)) {
            mkdir($userDataPath, 0777, true);
        }
        
        $copiedAssets = [];
        
        // Copy each asset folder to user's data folder
        foreach ($assetFolders as $assetFolder) {
            $sourcePath = $sharedDataPath . '/' . $assetFolder;
            $destPath = $userDataPath . '/' . $assetFolder;
            
            if (!file_exists($destPath)) {
                if (recursiveCopy($sourcePath, $destPath)) {
                    $copiedAssets[] = $assetFolder;
                }
            }
        }
        
        $setupResults[$username] = [
            'userFolder' => $userDataPath,
            'copiedAssets' => $copiedAssets,
            'totalAssets' => count($copiedAssets)
        ];
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'User data folders setup completed',
        'results' => $setupResults,
        'sharedAssets' => $assetFolders
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Setup failed: ' . $e->getMessage()
    ]);
}
?>