<?php
/**
 * Permission Check Helper
 * 
 * Include this file at the top of protected pages to enforce permission checks.
 * Usage: 
 *   require_once __DIR__ . '/../src/Permissions/require_permission.php';
 *   requirePermission('invoices_view');
 * 
 * Permission Keys:
 * - dashboard_view
 * - clients_view, clients_create, clients_edit, clients_delete
 * - proposals_view, proposals_create, proposals_edit, proposals_delete
 * - contracts_view, contracts_create, contracts_edit, contracts_delete
 * - invoices_view, invoices_create, invoices_edit, invoices_delete
 * - templates_view, templates_manage
 * - members_view, members_manage
 */

declare(strict_types=1);

require_once __DIR__ . '/PermissionManager.php';
require_once __DIR__ . '/../Auth/AuthManager.php';
require_once __DIR__ . '/../Billing/PlanLimits.php';
require_once __DIR__ . '/../db.php';

/**
 * Get current workspace context
 */
function getWorkspaceContext(): ?array
{
    if (!AuthManager::isAuthenticated()) {
        return null;
    }

    $user = AuthManager::getCurrentUser();
    $userId = (int)$user['id'];
    $companyId = $_SESSION['current_company_id'] ?? null;

    if (!$companyId) {
        $workspaceParam = $_GET['workspace'] ?? null;
        if ($workspaceParam) {
            $pdo = getPDO();
            if (is_numeric($workspaceParam)) {
                $stmt = $pdo->prepare("SELECT id, username FROM companies WHERE id = ?");
                $stmt->execute([(int)$workspaceParam]);
            } else {
                $stmt = $pdo->prepare("SELECT id, username FROM companies WHERE username = ?");
                $stmt->execute([$workspaceParam]);
            }
            $company = $stmt->fetch();
            $companyId = $company['id'] ?? null;
        }
    }

    if (!$companyId) {
        return null;
    }

    return [
        'user_id' => $userId,
        'company_id' => (int)$companyId,
        'is_owner' => PermissionManager::isOwner($userId, (int)$companyId),
    ];
}

/**
 * Check if current user has a specific permission (non-redirecting)
 */
function hasPermission(string $permission): bool
{
    $context = getWorkspaceContext();
    if (!$context) {
        return false;
    }

    if ($context['is_owner']) {
        return true;
    }

    return PermissionManager::hasPermission($context['user_id'], $context['company_id'], $permission);
}

/**
 * Check if current user can perform an action based on plan limits
 */
function canAddWithinLimits(string $limitKey): bool
{
    $context = getWorkspaceContext();
    if (!$context) {
        return false;
    }

    return PlanLimits::canAdd($context['company_id'], $limitKey);
}

/**
 * Get remaining count for a limit
 */
function getRemainingLimit(string $limitKey): int
{
    $context = getWorkspaceContext();
    if (!$context) {
        return 0;
    }

    return PlanLimits::getRemaining($context['company_id'], $limitKey);
}

/**
 * Check if user has permission, redirect to dashboard with error if not
 */
function requirePermission(string $permission): void
{
    // Ensure user is authenticated
    if (!AuthManager::isAuthenticated()) {
        header('Location: /login.php');
        exit;
    }

    $user = AuthManager::getCurrentUser();
    $userId = (int)$user['id'];

    // Get current company from session
    $companyId = $_SESSION['current_company_id'] ?? null;
    
    if (!$companyId) {
        // Try to get from URL parameter
        $workspaceParam = $_GET['workspace'] ?? null;
        if ($workspaceParam) {
            $pdo = getPDO();
            if (is_numeric($workspaceParam)) {
                $stmt = $pdo->prepare("SELECT id FROM companies WHERE id = ?");
                $stmt->execute([(int)$workspaceParam]);
            } else {
                $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
                $stmt->execute([$workspaceParam]);
            }
            $company = $stmt->fetch();
            $companyId = $company['id'] ?? null;
        }
    }

    if (!$companyId) {
        header('Location: /workspace-plans.php');
        exit;
    }

    // Check if user has permission
    if (!PermissionManager::hasPermission($userId, (int)$companyId, $permission)) {
        // Get workspace slug for redirect
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT username FROM companies WHERE id = ?");
        $stmt->execute([$companyId]);
        $company = $stmt->fetch();
        $workspaceSlug = $company['username'] ?? $companyId;

        // Store error message in session
        $_SESSION['permission_error'] = 'You do not have permission to access this page.';
        
        // Redirect to dashboard
        header('Location: /index.php?workspace=' . urlencode((string)$workspaceSlug));
        exit;
    }
}

/**
 * Check multiple permissions (user needs at least one)
 */
function requireAnyPermission(array $permissions): void
{
    if (!AuthManager::isAuthenticated()) {
        header('Location: /login.php');
        exit;
    }

    $user = AuthManager::getCurrentUser();
    $userId = (int)$user['id'];
    $companyId = $_SESSION['current_company_id'] ?? null;

    if (!$companyId) {
        header('Location: /workspace-plans.php');
        exit;
    }

    foreach ($permissions as $permission) {
        if (PermissionManager::hasPermission($userId, (int)$companyId, $permission)) {
            return; // Has at least one permission
        }
    }

    // No permissions matched
    $pdo = getPDO();
    $stmt = $pdo->prepare("SELECT username FROM companies WHERE id = ?");
    $stmt->execute([$companyId]);
    $company = $stmt->fetch();
    $workspaceSlug = $company['username'] ?? $companyId;

    $_SESSION['permission_error'] = 'You do not have permission to access this page.';
    header('Location: /index.php?workspace=' . urlencode((string)$workspaceSlug));
    exit;
}

/**
 * Check if user is workspace owner
 */
function requireOwner(): void
{
    if (!AuthManager::isAuthenticated()) {
        header('Location: /login.php');
        exit;
    }

    $user = AuthManager::getCurrentUser();
    $userId = (int)$user['id'];
    $companyId = $_SESSION['current_company_id'] ?? null;

    if (!$companyId) {
        header('Location: /workspace-plans.php');
        exit;
    }

    if (!PermissionManager::isOwner($userId, (int)$companyId)) {
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT username FROM companies WHERE id = ?");
        $stmt->execute([$companyId]);
        $company = $stmt->fetch();
        $workspaceSlug = $company['username'] ?? $companyId;

        $_SESSION['permission_error'] = 'Only the workspace owner can access this page.';
        header('Location: /index.php?workspace=' . urlencode((string)$workspaceSlug));
        exit;
    }
}
