<?php

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/Auth/AuthManager.php';

/**
 * Workspace Access Security
 * Ensures users can only access their own workspaces
 */
class WorkspaceSecurity {
    
    /**
     * Validate that the current user can access the requested workspace
     * @param string|null $workspaceParam Workspace parameter from URL
     * @throws Exception If user tries to access unauthorized workspace
     */
    public static function validateWorkspaceAccess(?string $workspaceParam = null): void {
        debug_log("WorkspaceSecurity: validateWorkspaceAccess called with: " . ($workspaceParam ?? 'none'));
        
        // Require authentication via AuthManager
        $user = AuthManager::getCurrentUser();
        if (!$user) {
            header('Location: /login.php');
            exit;
        }
        
        // If no workspace parameter, allow access (user will use current context)
        if (empty($workspaceParam)) {
            debug_log("WorkspaceSecurity: No workspace parameter, allowing access");
            return;
        }
        
        $hasAccess = false;
        $requestedCompany = null;
        try {
            $pdo = getPDO();
            $stmt = $pdo->prepare('
                SELECT c.* FROM user_company_access uca
                JOIN companies c ON c.id = uca.company_id
                WHERE uca.user_id = ? AND c.username = ?
            ');
            $stmt->execute([$user['id'], $workspaceParam]);
            $requestedCompany = $stmt->fetch();
            $hasAccess = (bool) $requestedCompany;
        } catch (Exception $e) {
            $hasAccess = false;
        }
        
        // Also allow access to user's primary company if usernames match
        if (!$hasAccess && !empty($user['company_username']) && $user['company_username'] === $workspaceParam) {
            $hasAccess = true;
        }
        
        if (!$hasAccess) {
            if (!empty($user['company_username'])) {
                header('Location: /index.php?workspace=' . urlencode($user['company_username']));
            } else {
                header('Location: /workspace-plans.php');
            }
            exit;
        }
    }
    
    /**
     * Deny access and redirect
     */
    private static function denyAccess(): void {
        // Clear any sensitive session data
        unset($_SESSION['current_company_id']);
        unset($_SESSION['current_company']);
        
        // Redirect to user's own workspace or dashboard
        if (isset($_SESSION['user_id'])) {
            try {
                $pdo = getPDO();
                $stmt = $pdo->prepare("SELECT u.company_id, c.username FROM users u JOIN companies c ON u.company_id = c.id WHERE u.id = ?");
                $stmt->execute([$_SESSION['user_id']]);
                $userCompany = $stmt->fetch();
                
                if ($userCompany && !empty($userCompany['username'])) {
                    header('Location: /index.php?workspace=' . urlencode($userCompany['username']));
                    exit;
                }
            } catch (Exception $e) {
                // Fall through to default redirect
            }
        }
        
        header('Location: /index.php');
        exit;
    }
    
    /**
     * Get current authenticated user
     */
    public static function getCurrentUser(): ?array {
        return AuthManager::getCurrentUser();
    }
    
    /**
     * Get current workspace
     *
     * If a ?workspace=<slug> parameter is present, resolve that specific
     * company for the current user (who has already been validated in
     * validateWorkspaceAccess). Otherwise, fall back to the default
     * company context from AuthManager.
     */
    public static function getCurrentWorkspace(): ?array {
        $workspaceParam = $_GET['workspace'] ?? null;

        // If a workspace slug is provided, resolve that specific workspace
        if (!empty($workspaceParam)) {
            $user = AuthManager::getCurrentUser();
            if ($user && !empty($user['id'])) {
                try {
                    $pdo = getPDO();
                    $stmt = $pdo->prepare('
                        SELECT c.* FROM user_company_access uca
                        JOIN companies c ON c.id = uca.company_id
                        WHERE uca.user_id = ? AND c.username = ?
                    ');
                    $stmt->execute([(int) $user['id'], $workspaceParam]);
                    $company = $stmt->fetch();
                    if ($company) {
                        return $company;
                    }
                } catch (Exception $e) {
                    // Fall through to default context
                }
            }
        }

        // Fallback: use AuthManager's current company context
        $company = AuthManager::getCurrentCompany();
        return $company ?: null;
    }
}
