<?php
/**
 * Universal Workspace Security Include
 * Add this line to the top of any page that needs workspace protection:
 * require_once __DIR__ . '/../src/secure_workspace.php';
 */

require_once __DIR__ . '/WorkspaceSecurity.php';
require_once __DIR__ . '/TenantDB.php';
require_once __DIR__ . '/debug_logger.php';
require_once __DIR__ . '/workspace_logger.php';

debug_log("secure_workspace.php: Loading...");

// Validate workspace access - prevents unauthorized URL access
$workspaceParam = $_GET['workspace'] ?? null;
debug_log("secure_workspace.php: Validating workspace: " . ($workspaceParam ?? 'none'));

WorkspaceSecurity::validateWorkspaceAccess($workspaceParam);

debug_log("secure_workspace.php: Workspace validation passed");

// Set global variables for backward compatibility
$company = WorkspaceSecurity::getCurrentWorkspace();
$user = WorkspaceSecurity::getCurrentUser();
$companyId = $company['id'] ?? null;

error_log("DEBUG secure_workspace: Company data: " . json_encode($company));
error_log("DEBUG secure_workspace: User data: " . json_encode($user));
error_log("DEBUG secure_workspace: Company ID: " . ($companyId ?? 'null'));

// Set tenant context for all database operations
if ($companyId) {
    TenantDB::setTenant($companyId);
    error_log("DEBUG secure_workspace: Tenant context set to $companyId");
} else {
    error_log("DEBUG secure_workspace: No company ID found - tenant context not set");
}
