<?php
/**
 * Common Admin Access Check
 * Include this file at the top of admin pages (after init.php)
 */

// Ensure user is logged in
requireLogin();

// Get role_code from session or database
$roleCode = $_SESSION['role_code'] ?? '';

// Always ensure role_code is loaded (refresh from database if needed)
if (isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        
        // If role_code is empty or role_id exists, refresh from database
        if (empty($roleCode) || isset($_SESSION['role_id'])) {
            if (isset($_SESSION['role_id'])) {
                $stmt = $db->prepare("SELECT role_code FROM roles WHERE role_id = ?");
                $stmt->execute([$_SESSION['role_id']]);
            } else {
                // Get from user's current role
                $stmt = $db->prepare("
                    SELECT r.role_code 
                    FROM users u
                    INNER JOIN roles r ON u.role_id = r.role_id
                    WHERE u.user_id = ?
                ");
                $stmt->execute([$_SESSION['user_id']]);
            }
            
            $role = $stmt->fetch();
            if ($role && !empty($role['role_code'])) {
                $roleCode = $role['role_code'];
                $_SESSION['role_code'] = $roleCode;
            }
        }
    } catch (Exception $e) {
        error_log("Error loading role_code in check_admin_access: " . $e->getMessage());
    }
}

// Check if user has admin access (super_admin or hr_admin)
// Temporarily allow all logged-in users (for development/testing)
// TODO: In production, uncomment the strict check below

// Strict check (commented for now - uncomment in production):
/*
if (!empty($roleCode) && !in_array($roleCode, ['super_admin', 'hr_admin'])) {
    $_SESSION['error'] = 'You do not have permission to access this resource.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}
*/

// Temporary: Allow all logged-in users (for development)
// This ensures all users can access admin pages during development
// Remove this in production and uncomment the check above

