<?php
/**
 * Enterprise HRM ERP System - Role-Based Access Control
 * Data Isolation: HR Admin sees only their data, Employee sees only self
 */

if (!defined('HRM_ACCESS')) {
    die('Direct access not allowed');
}

/**
 * Get HR Admin's user_id (for data isolation)
 * Returns the user_id of the HR Admin who owns/manages the data
 */
function getHRAdminUserId() {
    startSession();
    
    // If current user is HR Admin, return their user_id
    $roleCode = strtolower($_SESSION['role_code'] ?? '');
    if ($roleCode === 'hr_admin') {
        return $_SESSION['user_id'];
    }
    
    // If Super Admin, return null (can see all)
    if ($roleCode === 'super_admin') {
        return null; // No filter for Super Admin
    }
    
    // For employees, return null (they see only their own data via employee_id filter)
    return null;
}

/**
 * Get employee filter for queries
 * Returns WHERE clause and params for employee filtering based on role
 */
function getEmployeeFilter($employeeIdColumn = 'employee_id') {
    startSession();
    $roleCode = strtolower($_SESSION['role_code'] ?? '');
    
    // Super Admin - can see all employees (no filter, or filter by site if selected)
    if ($roleCode === 'super_admin') {
        $siteId = getCurrentSiteId();
        if ($siteId) {
            return [
                'where' => "site_id = ?",
                'params' => [$siteId]
            ];
        }
        return ['where' => '1=1', 'params' => []];
    }
    
    // HR Admin - can only see employees in their site
    if ($roleCode === 'hr_admin') {
        $siteId = getCurrentSiteId();
        if ($siteId) {
            return [
                'where' => "site_id = ?",
                'params' => [$siteId]
            ];
        }
        return ['where' => '1=0', 'params' => []]; // No access if no site
    }
    
    // Employee - can only see their own data
    if ($roleCode === 'employee') {
        $employeeId = getCurrentEmployeeId();
        if ($employeeId) {
            return [
                'where' => "{$employeeIdColumn} = ?",
                'params' => [$employeeId]
            ];
        }
        return ['where' => '1=0', 'params' => []]; // No access if no employee record
    }
    
    // Default: no access
    return ['where' => '1=0', 'params' => []];
}

/**
 * Get current employee ID from session
 * For employees, this links their user account to their employee record
 */
function getCurrentEmployeeId() {
    startSession();
    
    // Check if already in session
    if (isset($_SESSION['employee_id'])) {
        return $_SESSION['employee_id'];
    }
    
    // Try to find employee record linked to current user
    if (isset($_SESSION['user_id'])) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                SELECT employee_id FROM employees 
                WHERE user_id = ? AND employment_status = 'active'
                LIMIT 1
            ");
            $stmt->execute([$_SESSION['user_id']]);
            $employee = $stmt->fetch();
            
            if ($employee) {
                $_SESSION['employee_id'] = $employee['employee_id'];
                return $employee['employee_id'];
            }
        } catch (Exception $e) {
            error_log("Error getting employee ID: " . $e->getMessage());
        }
    }
    
    return null;
}

/**
 * Check if user is Employee role
 */
function isEmployee() {
    startSession();
    $roleCode = strtolower($_SESSION['role_code'] ?? '');
    return $roleCode === 'employee';
}

/**
 * Require employee access (redirect if not employee)
 */
function requireEmployeeAccess() {
    if (!isEmployee()) {
        $_SESSION['error'] = 'You do not have permission to access this resource.';
        header('Location: ' . BASE_URL . '/dashboard.php');
        exit;
    }
}

/**
 * Get data filter based on role
 * Combines site filter and employee filter
 */
function getDataFilter($siteIdColumn = 'site_id', $employeeIdColumn = null) {
    startSession();
    $roleCode = strtolower($_SESSION['role_code'] ?? '');
    
    // Super Admin - filter by site if selected
    if ($roleCode === 'super_admin') {
        $siteId = getCurrentSiteId();
        if ($siteId) {
            return [
                'where' => "{$siteIdColumn} = ?",
                'params' => [$siteId]
            ];
        }
        return ['where' => '1=1', 'params' => []];
    }
    
    // HR Admin - filter by their site only
    if ($roleCode === 'hr_admin') {
        $siteId = getCurrentSiteId();
        if ($siteId) {
            $where = "{$siteIdColumn} = ?";
            $params = [$siteId];
            
            // If employee filter needed, add it
            if ($employeeIdColumn) {
                // HR Admin can see all employees in their site, so no employee filter
            }
            
            return ['where' => $where, 'params' => $params];
        }
        return ['where' => '1=0', 'params' => []];
    }
    
    // Employee - filter by their employee_id only
    if ($roleCode === 'employee') {
        $employeeId = getCurrentEmployeeId();
        if ($employeeId && $employeeIdColumn) {
            return [
                'where' => "{$employeeIdColumn} = ?",
                'params' => [$employeeId]
            ];
        }
        return ['where' => '1=0', 'params' => []];
    }
    
    // Default: no access
    return ['where' => '1=0', 'params' => []];
}

/**
 * Check if user can access specific employee data
 */
function canAccessEmployee($employeeId) {
    startSession();
    $roleCode = strtolower($_SESSION['role_code'] ?? '');
    
    // Super Admin can access all
    if ($roleCode === 'super_admin') {
        return true;
    }
    
    // HR Admin can access employees in their site
    if ($roleCode === 'hr_admin') {
        try {
            $db = getDB();
            $siteId = getCurrentSiteId();
            $stmt = $db->prepare("SELECT employee_id FROM employees WHERE employee_id = ? AND site_id = ?");
            $stmt->execute([$employeeId, $siteId]);
            return $stmt->fetch() !== false;
        } catch (Exception $e) {
            return false;
        }
    }
    
    // Employee can only access their own data
    if ($roleCode === 'employee') {
        $currentEmployeeId = getCurrentEmployeeId();
        return $currentEmployeeId == $employeeId;
    }
    
    return false;
}

