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

class SessionManager {
    private static $instance = null;
    private $allowedUsers = [
        'unrealengine_developer',
        'unrealengine_admin', 
        'unrealengine_user1',
        'unrealengine_user2'
    ];
    
    private function __construct() {
        $this->initializeUserFolders();
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function initializeUserFolders() {
        foreach ($this->allowedUsers as $username) {
            $userImagePath = IMG_DIR . "/chart-img/{$username}/";
            if (!file_exists($userImagePath)) {
                mkdir($userImagePath, 0777, true);
            }
            
            $userDataPath = DATA_DIR . "/{$username}/";
            if (!file_exists($userDataPath)) {
                mkdir($userDataPath, 0777, true);
            }
        }
    }
    
    public function startUserSession($username) {
        if (!in_array($username, $this->allowedUsers)) {
            return false;
        }
        
        session_name('TRADING_SESSION_' . strtoupper($username));
        session_start();
        
        $_SESSION['username'] = $username;
        $_SESSION['logged_in'] = true;
        
        return true;
    }
    
    public function getCurrentUserImagePath() {
        if (isset($_SESSION['username'])) {
            return IMG_DIR . "/chart-img/{$_SESSION['username']}/";
        }
        return null;
    }
    
    public function getCurrentUserDataPath() {
        if (isset($_SESSION['username'])) {
            return DATA_DIR . "/{$_SESSION['username']}/";
        }
        return null;
    }
    
    public function getUserDataPath($username = null) {
        $user = $username ?: ($_SESSION['username'] ?? null);
        if ($user && in_array($user, $this->allowedUsers)) {
            return DATA_DIR . "/{$user}/";
        }
        return null;
    }
    
    public function destroyUserSession() {
        $_SESSION = array();
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        session_destroy();
        return true;
    }
}

function startUserSession($username) {
    $sessionManager = SessionManager::getInstance();
    return $sessionManager->startUserSession($username);
}

function detectAndStartUserSession() {
    $allowedUsers = ['unrealengine_developer', 'unrealengine_admin', 'unrealengine_user1', 'unrealengine_user2'];
    
    foreach ($allowedUsers as $username) {
        if (session_status() === PHP_SESSION_ACTIVE) {
            session_write_close();
        }
        
        session_name('TRADING_SESSION_' . strtoupper($username));
        session_start();
        
        if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true && 
            isset($_SESSION['username']) && $_SESSION['username'] === $username) {
            return true;
        }
    }
    
    session_name('PHPSESSID');
    session_start();
    return false;
}

function getUserDataPath($username = null) {
    $sessionManager = SessionManager::getInstance();
    return $sessionManager->getUserDataPath($username);
}

function getCurrentUserDataPath() {
    $sessionManager = SessionManager::getInstance();
    return $sessionManager->getCurrentUserDataPath();
}

function copySharedDataToUserFolders() {
    $sharedDataPath = DATA_DIR;
    $allowedUsers = ['unrealengine_developer', 'unrealengine_admin', 'unrealengine_user1', 'unrealengine_user2'];
    
    if (!is_dir($sharedDataPath)) {
        return false;
    }
    
    foreach ($allowedUsers as $username) {
        $userDataPath = DATA_DIR . "/{$username}/";
        
        if (!file_exists($userDataPath)) {
            mkdir($userDataPath, 0777, true);
        }
        
        $items = scandir($sharedDataPath);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..' || in_array($item, $allowedUsers)) {
                continue;
            }
            
            $sourcePath = $sharedDataPath . '/' . $item;
            $destPath = $userDataPath . $item;
            
            if (is_dir($sourcePath) && !file_exists($destPath)) {
                recursiveCopy($sourcePath, $destPath);
            }
        }
    }
    
    return true;
}

function recursiveCopy($src, $dst) {
    $dir = opendir($src);
    @mkdir($dst, 0777, true);
    
    while (($file = readdir($dir)) !== false) {
        if ($file != '.' && $file != '..') {
            if (is_dir($src . '/' . $file)) {
                recursiveCopy($src . '/' . $file, $dst . '/' . $file);
            } else {
                copy($src . '/' . $file, $dst . '/' . $file);
            }
        }
    }
    
    closedir($dir);
}

// Handle AJAX requests for current user info
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (isset($input['action']) && $input['action'] === 'getCurrentUser') {
        detectAndStartUserSession();
        
        header('Content-Type: application/json');
        echo json_encode([
            'username' => $_SESSION['username'] ?? null,
            'logged_in' => $_SESSION['logged_in'] ?? false
        ]);
        exit;
    }
}
?>