<?php
/**
 * Access Control Helper - Bridge between your existing system and new access control
 */

/**
 * Initialize access control for a page
 * Use this function at the top of your protected pages
 */
function initPageAccess($conn, $required_page = null) {
    // Ensure session is started
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Include necessary files
    include_once 'includes/page_access_control.php';
    
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        header('Location: login.php');
        exit();
    }
    
    // Protect the page
    $pac = protectPage($conn, $required_page);
    
    return $pac;
}

/**
 * Quick check if user can access a page (for conditional displays)
 */
function canAccess($conn, $page_name, $user_id = null) {
    include_once 'includes/page_access_control.php';
    
    $user_id = $user_id ?? $_SESSION['user_id'] ?? null;
    
    if (!$user_id) {
        return false;
    }
    
    $pac = new PageAccessControl($conn, $user_id);
    return $pac->hasPageAccess($page_name);
}

/**
 * Get user's current role and permissions summary
 */
function getUserAccessSummary($conn, $user_id = null) {
    include_once 'includes/page_access_control.php';
    
    $user_id = $user_id ?? $_SESSION['user_id'] ?? null;
    
    if (!$user_id) {
        return null;
    }
    
    $pac = new PageAccessControl($conn, $user_id);
    $assigned_pages = $pac->getAssignedPages();
    
    return [
        'role' => $pac->getRoleName(),
        'assigned_pages' => $assigned_pages,
        'is_super_admin' => in_array('*', $assigned_pages),
        'page_count' => in_array('*', $assigned_pages) ? 'All' : count($assigned_pages)
    ];
}

/**
 * Render access-controlled action buttons
 */
function renderActionButton($conn, $page_name, $button_html, $fallback_text = null) {
    if (canAccess($conn, $page_name)) {
        echo $button_html;
    } elseif ($fallback_text) {
        echo '<span class="text-muted small"><i class="ph-lock me-1"></i>' . htmlspecialchars($fallback_text) . '</span>';
    }
}

/**
 * Generate filtered quick actions based on user access
 */
function getAccessibleQuickActions($conn, $userRole, $user_id = null) {
    include_once 'includes/menu_config.php';
    
    $allQuickActions = getQuickActions($userRole);
    $accessibleActions = [];
    
    foreach ($allQuickActions as $action) {
        if (canAccess($conn, $action['url'], $user_id)) {
            $accessibleActions[] = $action;
        }
    }
    
    return $accessibleActions;
}

/**
 * Display access control status (for debugging/admin purposes)
 */
function showAccessControlStatus($conn, $user_id = null) {
    $summary = getUserAccessSummary($conn, $user_id);
    
    if (!$summary) {
        echo '<div class="alert alert-warning">No access information available</div>';
        return;
    }
    
    echo '<div class="access-control-status" style="background: #f8f9fa; padding: 1rem; border-radius: 8px; margin: 1rem 0;">';
    echo '<h6><i class="ph-shield-check me-2"></i>Access Control Status</h6>';
    echo '<p><strong>Role:</strong> ' . htmlspecialchars($summary['role']) . '</p>';
    echo '<p><strong>Page Access:</strong> ' . ($summary['is_super_admin'] ? 'Full Access (Super Admin)' : $summary['page_count'] . ' pages assigned') . '</p>';
    
    if (!$summary['is_super_admin'] && !empty($summary['assigned_pages'])) {
        echo '<details>';
        echo '<summary>View Assigned Pages (' . count($summary['assigned_pages']) . ')</summary>';
        echo '<ul style="margin: 0.5rem 0; padding-left: 1.5rem;">';
        foreach ($summary['assigned_pages'] as $page) {
            echo '<li><code>' . htmlspecialchars($page) . '</code></li>';
        }
        echo '</ul>';
        echo '</details>';
    }
    echo '</div>';
}

/**
 * Conditional content wrapper
 */
function ifCanAccess($conn, $page_name, $content, $fallback = '') {
    if (canAccess($conn, $page_name)) {
        echo $content;
    } else {
        echo $fallback;
    }
}

/**
 * Protect multiple pages (for pages that require access to multiple resources)
 */
function protectMultiplePages($conn, $required_pages = []) {
    include_once 'includes/page_access_control.php';
    
    if (!isset($_SESSION['user_id'])) {
        header('Location: login.php');
        exit();
    }
    
    $pac = new PageAccessControl($conn, $_SESSION['user_id']);
    
    // Check if user has access to ANY of the required pages
    $hasAccess = false;
    foreach ($required_pages as $page) {
        if ($pac->hasPageAccess($page)) {
            $hasAccess = true;
            break;
        }
    }
    
    if (!$hasAccess) {
        $pac->logAccess(implode(',', $required_pages), 'DENIED');
        header('Location: access_denied.php');
        exit();
    }
    
    $pac->logAccess(implode(',', $required_pages), 'ALLOWED');
    return $pac;
}
?>