<?php
/**
 * Check Page Access Helper
 * Checks if user has access to a page based on database permissions
 */

/**
 * Check if current user has access to a specific page
 * @param string $page_url The page URL to check (e.g., 'list_procedures.php')
 * @param mysqli $conn Database connection
 * @return bool True if user has access, false otherwise
 */
function hasPageAccess($page_url, $conn) {
    // Must be logged in
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['role_id'])) {
        return false;
    }
    
    $user_id = $_SESSION['user_id'];
    $role_id = $_SESSION['role_id'];
    $role_code = $_SESSION['role_code'] ?? '';
    
    // Super Admin has access to everything
    if ($role_code === 'SUPER_ADMIN') {
        return true;
    }
    
    // Normalize page URL (remove leading slash, handle query strings)
    $page_url = ltrim($page_url, '/');
    $page_url = basename($page_url); // Get just the filename
    
    // Check if page exists in menu_items and user's role has permission
    $check_sql = "SELECT COUNT(*) as has_access
                  FROM menu_items mi
                  INNER JOIN role_permissions rp ON mi.menu_id = rp.menu_id
                  WHERE mi.menu_url = ? 
                  AND rp.role_id = ?
                  AND rp.can_view = 1
                  AND mi.is_active = 1";
    
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param("si", $page_url, $role_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    
    return ($result['has_access'] > 0);
}

/**
 * Require page access - redirects if user doesn't have access
 * @param string $page_url The page URL to check
 * @param mysqli $conn Database connection
 */
function requirePageAccess($page_url, $conn) {
    if (!hasPageAccess($page_url, $conn)) {
        // Get role-specific dashboard URL
        $role_code = $_SESSION['role_code'] ?? '';
        $dashboard_url = getRoleDashboardUrl($role_code);
        
        $_SESSION['error'] = "You do not have permission to access this page.";
        header("Location: $dashboard_url");
        exit();
    }
}

/**
 * Get role-specific dashboard URL
 */
function getRoleDashboardUrl($role_code) {
    $dashboard_map = [
        'SUPER_ADMIN' => 'index.php',
        'HOSPITAL_ADMIN' => 'admin_dashboard.php',
        'ENT_CONSULTANT' => 'doctor_dashboard.php',
        'ENT_DOCTOR' => 'doctor_dashboard.php',
        'RESIDENT_DOCTOR' => 'resident_dashboard.php',
        'HEAD_NURSE' => 'nursing_dashboard.php',
        'ENT_NURSE' => 'nursing_dashboard.php',
        'AUDIOLOGIST' => 'audiologist_dashboard.php',
        'LAB_TECHNICIAN' => 'lab_dashboard.php',
        'RECEPTIONIST' => 'reception_dashboard.php',
        'BILLING_CLERK' => 'billing_dashboard.php',
        'MEDICAL_RECORDS' => 'records_dashboard.php',
        'PATIENT' => 'patient_portal.php'
    ];
    
    return $dashboard_map[$role_code] ?? 'index.php';
}
