<?php
session_start();
require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/Auth/AuthManager.php';

// Require authentication
AuthManager::requireAuth();

// Get workspace ID from URL
$workspaceId = (int) ($_GET['id'] ?? 0);

if (!$workspaceId) {
    // Redirect to first workspace if no ID provided
    $pdo = getPDO();
    $stmt = $pdo->query("SELECT id FROM companies ORDER BY id LIMIT 1");
    $company = $stmt->fetch();
    if ($company) {
        header('Location: /workspace/' . $company['id']);
        exit;
    }
    die('No workspaces found');
}

// Get workspace data
$pdo = getPDO();
$stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
$stmt->execute([$workspaceId]);
$company = $stmt->fetch();

if (!$company) {
    die('Workspace not found');
}

// Update session with current workspace
$_SESSION['current_company_id'] = $company['id'];
$_SESSION['current_company'] = $company;

// Redirect to main dashboard (without workspace parameter to avoid loops)
header('Location: /index.php');
exit;
?>
