<?php
/**
 * Enhanced Role-Based Access Control System
 * File: includes/rbac_system.php
 */

class RoleBasedAccessControl {
    private $conn;
    private $user_id;
    private $user_role;
    private $assigned_pages = [];
    
    public function __construct($conn, $user_id = null) {
        $this->conn = $conn;
        $this->user_id = $user_id;
        
        if ($user_id) {
            $this->loadUserRole();
            $this->loadAssignedPages();
        }
    }
    
    /**
     * Load user role information
     */
    private function loadUserRole() {
        $sql = "SELECT u.*, ur.role_name FROM users u 
                INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                WHERE u.user_id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param("i", $this->user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        
        if ($result) {
            $this->user_role = $result['role_name'];
        }
    }
    
    /**
     * Load pages assigned to user's role
     */
    private function loadAssignedPages() {
        // Super Admin gets access to everything
        if ($this->user_role === 'Super Admin') {
            $this->assigned_pages = ['*']; // All pages
            return;
        }
        
        // Get role ID first
        $role_sql = "SELECT role_id FROM user_roles WHERE role_name = ?";
        $role_stmt = $this->conn->prepare($role_sql);
        $role_stmt->bind_param("s", $this->user_role);
        $role_stmt->execute();
        $role_result = $role_stmt->get_result()->fetch_assoc();
        
        if (!$role_result) {
            return;
        }
        
        $role_id = $role_result['role_id'];
        
        // Get assigned pages for this role
        $pages_sql = "SELECT page_name FROM role_page_permissions WHERE role_id = ?";
        $pages_stmt = $this->conn->prepare($pages_sql);
        $pages_stmt->bind_param("i", $role_id);
        $pages_stmt->execute();
        $pages_result = $pages_stmt->get_result();
        
        $this->assigned_pages = [];
        while ($row = $pages_result->fetch_assoc()) {
            $this->assigned_pages[] = $row['page_name'];
        }
        
        // Always include basic pages
        $basic_pages = ['index.php', 'profile.php', 'change_password.php', 'logout.php'];
        $this->assigned_pages = array_merge($this->assigned_pages, $basic_pages);
    }
    
    /**
     * Check if user has access to a specific page
     */
    public function hasPageAccess($page_name) {
        // Super Admin has access to everything
        if ($this->user_role === 'Super Admin' || in_array('*', $this->assigned_pages)) {
            return true;
        }
        
        // Check if page is in assigned pages
        return in_array($page_name, $this->assigned_pages);
    }
    
    /**
     * Get all assigned pages
     */
    public function getAssignedPages() {
        return $this->assigned_pages;
    }
    
    /**
     * Get user role
     */
    public function getUserRole() {
        return $this->user_role;
    }
    
    /**
     * Filter menu configuration based on assigned pages
     */
    public function filterMenuConfig($menuConfig) {
        if ($this->user_role === 'Super Admin' || in_array('*', $this->assigned_pages)) {
            return $menuConfig; // Return full menu for Super Admin
        }
        
        $filteredMenu = [];
        
        foreach ($menuConfig as $item) {
            // Always include headers - we'll filter them later based on content
            if ($item['type'] === 'header') {
                $filteredMenu[] = $item;
                continue;
            }
            
            // For single links
            if ($item['type'] === 'link') {
                if ($this->hasPageAccess($item['url'])) {
                    $filteredMenu[] = $item;
                }
                continue;
            }
            
            // For dropdown menus
            if ($item['type'] === 'dropdown' && isset($item['items'])) {
                $filteredItems = [];
                
                foreach ($item['items'] as $subItem) {
                    if (isset($subItem['url']) && $this->hasPageAccess($subItem['url'])) {
                        $filteredItems[] = $subItem;
                    }
                }
                
                // Only include dropdown if it has accessible items
                if (!empty($filteredItems)) {
                    $item['items'] = $filteredItems;
                    $filteredMenu[] = $item;
                }
            }
        }
        
        // Remove empty headers (headers with no accessible items after them)
        return $this->removeEmptyHeaders($filteredMenu);
    }
    
    /**
     * Remove headers that have no accessible items following them
     */
    private function removeEmptyHeaders($menu) {
        $cleanMenu = [];
        $currentHeader = null;
        $hasItemsAfterHeader = false;
        
        foreach ($menu as $item) {
            if ($item['type'] === 'header') {
                // If we had a previous header, add it only if it had items
                if ($currentHeader && $hasItemsAfterHeader) {
                    $cleanMenu[] = $currentHeader;
                    // Add all accumulated items
                    $hasItemsAfterHeader = false;
                }
                $currentHeader = $item;
            } else {
                // This is an actual menu item
                if ($currentHeader) {
                    $cleanMenu[] = $currentHeader;
                    $currentHeader = null;
                }
                $cleanMenu[] = $item;
                $hasItemsAfterHeader = true;
            }
        }
        
        // Handle the last header
        if ($currentHeader && $hasItemsAfterHeader) {
            $cleanMenu[] = $currentHeader;
        }
        
        return $cleanMenu;
    }
}

/**
 * Page Access Control - Middleware for protecting pages
 * File: includes/page_access_middleware.php
 */

function checkPageAccess($conn, $required_page = null) {
    // Start session if not already started
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        header('Location: login.php');
        exit();
    }
    
    // If no specific page required, just check login
    if (!$required_page) {
        $required_page = basename($_SERVER['PHP_SELF']);
    }
    
    // Initialize RBAC system
    $rbac = new RoleBasedAccessControl($conn, $_SESSION['user_id']);
    
    // Check access
    if (!$rbac->hasPageAccess($required_page)) {
        // Log unauthorized access attempt
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_type, new_values, ip_address, user_agent) 
                   VALUES (?, 'UNAUTHORIZED_ACCESS', 'SECURITY', 'PAGE_ACCESS', ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_data = json_encode(['attempted_page' => $required_page, 'user_role' => $rbac->getUserRole()]);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $log_stmt->bind_param("isss", $_SESSION['user_id'], $log_data, $ip_address, $user_agent);
        $log_stmt->execute();
        
        // Redirect to access denied page or dashboard
        header('Location: access_denied.php');
        exit();
    }
    
    return $rbac;
}

/**
 * Updated Menu Rendering Function
 * File: layouts/menu.php (updated version)
 */

// Include the RBAC system
require_once 'includes/rbac_system.php';

// Get current page
$current_page = basename($_SERVER['PHP_SELF']);

// Initialize RBAC for logged in users
$rbac = null;
$menuItems = [];
$userRole = 'guest';

if (isset($_SESSION['user_id'])) {
    $rbac = new RoleBasedAccessControl($conn, $_SESSION['user_id']);
    $userRole = $rbac->getUserRole();
    
    // Get user details for display
    $user_sql = "SELECT u.*, ur.role_name FROM users u 
                 INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                 WHERE u.user_id = ?";
    $user_stmt = $conn->prepare($user_sql);
    $user_stmt->bind_param("i", $_SESSION['user_id']);
    $user_stmt->execute();
    $user_details = $user_stmt->get_result()->fetch_assoc();
    
    // Include menu configuration
    require_once 'includes/menu_config.php';
    
    // Get full menu config and filter it
    $fullMenuConfig = getMenuConfig($userRole);
    $menuItems = $rbac->filterMenuConfig($fullMenuConfig);
}

/**
 * Enhanced Menu Configuration
 * File: includes/healthcare_menu_config.php (updated)


function getMenuConfig($userRole = 'guest') {
    // Common menu items for all logged-in users
    $commonMenus = [
        [
            'title' => 'Main Menu',
            'type' => 'header'
        ],
        [
            'title' => 'Dashboard',
            'icon' => 'ph-chart-line',
            'url' => 'index.php',
            'type' => 'link'
        ]
    ];
    
    // Healthcare-specific menu structure
    $healthcareMenus = [
        // Patient Management Section
        [
            'title' => 'Patient Management',
            'type' => 'header'
        ],
        [
            'title' => 'Patients',
            'icon' => 'ph-user-circle',
            'type' => 'dropdown',
            'id' => 'patientMenu',
            'items' => [
                ['title' => 'View All Patients', 'url' => 'list_patients.php'],
                ['title' => 'Register New Patient', 'url' => 'register_patient.php'],
                ['title' => 'Patient Search', 'url' => 'patient_search.php'],
                ['title' => 'Patient Records', 'url' => 'patient_records.php'],
                ['title' => 'Medical History', 'url' => 'medical_history.php'],
                ['title' => 'Export Patient Data', 'url' => 'export_patients.php']
            ]
        ],
        [
            'title' => 'Patient Visits',
            'icon' => 'ph-calendar-check',
            'type' => 'dropdown',
            'id' => 'visitsMenu',
            'items' => [
                ['title' => 'All Visits', 'url' => 'list_visits.php'],
                ['title' => 'Register Visit', 'url' => 'register_visit.php'],
                ['title' => 'Visit Queue', 'url' => 'visit_queue.php'],
                ['title' => 'Visit History', 'url' => 'visit_history.php'],
                ['title' => 'Emergency Visits', 'url' => 'emergency_visits.php']
            ]
        ],
        
        // Clinical Operations Section
        [
            'title' => 'Clinical Operations',
            'type' => 'header'
        ],
        [
            'title' => 'Consultations',
            'icon' => 'ph-chat-circle-dots',
            'type' => 'dropdown',
            'id' => 'consultationsMenu',
            'items' => [
                ['title' => 'All Consultations', 'url' => 'list_consultations.php'],
                ['title' => 'Conduct Consultation', 'url' => 'conduct_consultation.php'],
                ['title' => 'Active Consultations', 'url' => 'active_consultations.php'],
                ['title' => 'Consultation Queue', 'url' => 'consultation_queue.php'],
                ['title' => 'Consultation Reports', 'url' => 'consultation_reports.php']
            ]
        ],
        [
            'title' => 'Procedures',
            'icon' => 'ph-syringe',
            'type' => 'dropdown',
            'id' => 'proceduresMenu',
            'items' => [
                ['title' => 'All Procedures', 'url' => 'list_procedures.php'],
                ['title' => 'Perform Procedure', 'url' => 'perform_procedure.php'],
                ['title' => 'Schedule Procedure', 'url' => 'schedule_procedure.php'],
                ['title' => 'Procedure Types', 'url' => 'procedure_types.php'],
                ['title' => 'Procedure History', 'url' => 'procedure_history.php']
            ]
        ],
        
        // Laboratory Section
        [
            'title' => 'Laboratory',
            'type' => 'header'
        ],
        [
            'title' => 'Lab Orders',
            'icon' => 'ph-test-tube',
            'type' => 'dropdown',
            'id' => 'labOrdersMenu',
            'items' => [
                ['title' => 'All Lab Orders', 'url' => 'list_lab_orders.php'],
                ['title' => 'Create Lab Order', 'url' => 'create_lab_order.php'],
                ['title' => 'Pending Orders', 'url' => 'pending_lab_orders.php'],
                ['title' => 'Process Lab Tests', 'url' => 'process_lab_tests.php'],
                ['title' => 'Enter Results', 'url' => 'enter_lab_results.php'],
                ['title' => 'Approve Results', 'url' => 'approve_lab_results.php']
            ]
        ],
        [
            'title' => 'Lab Management',
            'icon' => 'ph-flask',
            'type' => 'dropdown',
            'id' => 'labManagementMenu',
            'items' => [
                ['title' => 'Lab Results', 'url' => 'lab_results.php'],
                ['title' => 'Lab Test Types', 'url' => 'lab_test_types.php'],
                ['title' => 'Lab Reports', 'url' => 'lab_reports.php'],
                ['title' => 'Lab Statistics', 'url' => 'lab_statistics.php']
            ]
        ],
        
        // Financial Management Section
        [
            'title' => 'Financial Management',
            'type' => 'header'
        ],
        [
            'title' => 'Billing & Invoicing',
            'icon' => 'ph-receipt',
            'type' => 'dropdown',
            'id' => 'billingMenu',
            'items' => [
                ['title' => 'All Invoices', 'url' => 'list_invoices.php'],
                ['title' => 'Create Invoice', 'url' => 'create_invoice.php'],
                ['title' => 'Pending Invoices', 'url' => 'pending_invoices.php'],
                ['title' => 'Overdue Invoices', 'url' => 'overdue_invoices.php']
            ]
        ],
        [
            'title' => 'Payments',
            'icon' => 'ph-credit-card',
            'type' => 'dropdown',
            'id' => 'paymentsMenu',
            'items' => [
                ['title' => 'All Payments', 'url' => 'list_payments.php'],
                ['title' => 'Record Payment', 'url' => 'record_payment.php'],
                ['title' => 'M-Pesa Payments', 'url' => 'mpesa_payments.php'],
                ['title' => 'Payment Reports', 'url' => 'payment_reports.php'],
                ['title' => 'Outstanding Balances', 'url' => 'outstanding_balances.php']
            ]
        ],
        
        // Revenue & Credit Section
        [
            'title' => 'Revenue & Credit',
            'type' => 'header'
        ],
        [
            'title' => 'Revenue Tracking',
            'icon' => 'ph-trending-up',
            'type' => 'dropdown',
            'id' => 'revenueMenu',
            'items' => [
                ['title' => 'Daily Revenue', 'url' => 'daily_revenue.php'],
                ['title' => 'Monthly Revenue', 'url' => 'monthly_revenue.php'],
                ['title' => 'Revenue Analysis', 'url' => 'revenue_analysis.php'],
                ['title' => 'Financial Reports', 'url' => 'financial_reports.php']
            ]
        ],
        [
            'title' => 'Credit & Loans',
            'icon' => 'ph-bank',
            'type' => 'dropdown',
            'id' => 'creditMenu',
            'items' => [
                ['title' => 'Facility Credit Score', 'url' => 'facility_credit_score.php'],
                ['title' => 'Credit History', 'url' => 'credit_history.php'],
                ['title' => 'Loan Applications', 'url' => 'facility_loan_applications.php'],
                ['title' => 'Active Loans', 'url' => 'active_facility_loans.php']
            ]
        ],
        
        // System Administration Section
        [
            'title' => 'System Administration',
            'type' => 'header'
        ],
        [
            'title' => 'User Management',
            'icon' => 'ph-users',
            'type' => 'dropdown',
            'id' => 'userManagementMenu',
            'items' => [
                ['title' => 'All Users', 'url' => 'list_users.php'],
                ['title' => 'Add User', 'url' => 'add_user.php'],
                ['title' => 'User Roles', 'url' => 'user_roles.php'],
                ['title' => 'Access Control', 'url' => 'access_control.php'],
                ['title' => 'Role Permissions', 'url' => 'role_permissions.php']
            ]
        ],
        [
            'title' => 'System Settings',
            'icon' => 'ph-gear',
            'type' => 'dropdown',
            'id' => 'systemSettingsMenu',
            'items' => [
                ['title' => 'System Configuration', 'url' => 'system_settings.php'],
                ['title' => 'M-Pesa Configuration', 'url' => 'mpesa_config.php'],
                ['title' => 'Email Configuration', 'url' => 'email_config.php'],
                ['title' => 'Backup & Restore', 'url' => 'backup_restore.php']
            ]
        ],
        [
            'title' => 'Reports & Analytics',
            'icon' => 'ph-chart-bar',
            'type' => 'dropdown',
            'id' => 'reportsMenu',
            'items' => [
                ['title' => 'Patient Statistics', 'url' => 'patient_statistics.php'],
                ['title' => 'Clinical Reports', 'url' => 'clinical_reports.php'],
                ['title' => 'Custom Reports', 'url' => 'custom_reports.php'],
                ['title' => 'Activity Logs', 'url' => 'activity_logs.php']
            ]
        ]
    ];
    
    // Account menu (common for all roles)
    $accountMenu = [
        [
            'title' => 'My Account',
            'type' => 'header'
        ],
        [
            'title' => 'My Profile',
            'icon' => 'ph-user',
            'url' => 'profile.php',
            'type' => 'link'
        ],
        [
            'title' => 'Change Password',
            'icon' => 'ph-lock-key',
            'url' => 'change_password.php',
            'type' => 'link'
        ],
        [
            'title' => 'Logout',
            'icon' => 'ph-sign-out',
            'url' => 'logout.php',
            'type' => 'link',
            'class' => 'text-danger'
        ]
    ];
    
    // Combine menus
    $menu = array_merge($commonMenus, $healthcareMenus, $accountMenu);
    
    return $menu;
}

// Helper functions
function isMenuActive($url, $currentPage = null) {
    if ($currentPage === null) {
        $currentPage = basename($_SERVER['PHP_SELF']);
    }
    return $currentPage === $url;
}

function hasActiveItem($items, $currentPage = null) {
    if ($currentPage === null) {
        $currentPage = basename($_SERVER['PHP_SELF']);
    }
    
    foreach ($items as $item) {
        if (isset($item['url']) && $currentPage === $item['url']) {
            return true;
        }
    }
    return false;
}
*/
/**
 * Access Denied Page
 * File: access_denied.php
 */

function createAccessDeniedPage() {
    return '<?php
session_start();
include "layouts/dbconn.php";

// Check if user is logged in
if (!isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit();
}

// Get user details
$user_id = $_SESSION["user_id"];
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();
?>

<?php include "layouts/main.php"; ?>

<head>
    <?php includeFileWithVariables("layouts/title-meta.php", array("title" => "Access Denied - Healthcare EMR")); ?>
    <?php include "layouts/head-css.php"; ?>
    <style>
        .access-denied-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .access-denied-card {
            background: white;
            border-radius: 20px;
            padding: 3rem;
            text-align: center;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            max-width: 500px;
            margin: 2rem;
        }
        
        .access-denied-icon {
            font-size: 5rem;
            color: #ef4444;
            margin-bottom: 1.5rem;
        }
        
        .access-denied-title {
            font-size: 2rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 1rem;
        }
        
        .access-denied-message {
            color: #6b7280;
            margin-bottom: 2rem;
            line-height: 1.6;
        }
        
        .btn-back {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 50px;
            text-decoration: none;
            font-weight: 600;
            display: inline-block;
            transition: transform 0.2s ease;
        }
        
        .btn-back:hover {
            transform: translateY(-2px);
            color: white;
        }
    </style>
</head>

<body>
    <div class="access-denied-container">
        <div class="access-denied-card">
            <div class="access-denied-icon">
                <i class="ph ph-prohibit"></i>
            </div>
            <h1 class="access-denied-title">Access Denied</h1>
            <p class="access-denied-message">
                Sorry, you dont have permission to access this page. 
                Your role (<strong><?php echo htmlspecialchars($user_details["role_name"]); ?></strong>) 
                does not include access to the requested resource.
            </p>
            <a href="index.php" class="btn-back">
                <i class="ph ph-house me-2"></i>
                Back to Dashboard
            </a>
        </div>
    </div>
</body>
</html>';
}
?>