<?php
/**
 * Enterprise HRM ERP System - Data Isolation Functions
 * Ensures HR Admin sees only their site, Employee sees only own data
 */

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

/**
 * Check if user is Super Admin
 */
function isSuperAdmin() {
    startSession();
    
    if (!isset($_SESSION['user_id'])) {
        return false;
    }
    
    $roleCode = $_SESSION['role_code'] ?? '';
    
    // If role_code not in session, load from database
    if (empty($roleCode)) {
        try {
            $db = getDB();
            
            // Try to get from role_id first
            if (isset($_SESSION['role_id'])) {
                $stmt = $db->prepare("SELECT role_code FROM roles WHERE role_id = ?");
                $stmt->execute([$_SESSION['role_id']]);
                $role = $stmt->fetch();
                if ($role && !empty($role['role_code'])) {
                    $roleCode = $role['role_code'];
                    $_SESSION['role_code'] = $roleCode;
                }
            }
            
            // If still empty, get from user_id
            if (empty($roleCode)) {
                $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']]);
                $userRole = $stmt->fetch();
                if ($userRole && !empty($userRole['role_code'])) {
                    $roleCode = $userRole['role_code'];
                    $_SESSION['role_code'] = $roleCode;
                    
                    // Also update role_id if not set
                    if (!isset($_SESSION['role_id'])) {
                        $stmt = $db->prepare("SELECT role_id FROM users WHERE user_id = ?");
                        $stmt->execute([$_SESSION['user_id']]);
                        $user = $stmt->fetch();
                        if ($user) {
                            $_SESSION['role_id'] = $user['role_id'];
                        }
                    }
                }
            }
        } catch (Exception $e) {
            error_log("Error loading role_code in isSuperAdmin: " . $e->getMessage());
            return false;
        }
    }
    
    // Debug log (can be removed in production)
    if (empty($roleCode)) {
        error_log("Warning: role_code is still empty for user_id: " . ($_SESSION['user_id'] ?? 'N/A'));
    }
    
    return strtolower($roleCode) === 'super_admin';
}

/**
 * Check if user is HR Admin
 */
function isHRAdmin() {
    startSession();
    
    if (!isset($_SESSION['user_id'])) {
        return false;
    }
    
    $roleCode = $_SESSION['role_code'] ?? '';
    
    // If role_code not in session, load from database
    if (empty($roleCode) && isset($_SESSION['role_id'])) {
        try {
            $db = getDB();
            $stmt = $db->prepare("SELECT role_code FROM roles WHERE role_id = ?");
            $stmt->execute([$_SESSION['role_id']]);
            $role = $stmt->fetch();
            if ($role) {
                $roleCode = $role['role_code'];
                $_SESSION['role_code'] = $roleCode;
            }
        } catch (Exception $e) {
            error_log("Error loading role_code in isHRAdmin: " . $e->getMessage());
        }
    }
    
    return strtolower($roleCode) === 'hr_admin';
}

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

/**
 * Get site filter for queries (data isolation)
 * Returns site_id for HR Admin, null for Super Admin (can see all)
 */
function getSiteFilter() {
    startSession();
    
    // Super Admin can see all sites (no filter)
    if (isSuperAdmin()) {
        // If site selected in session, use that, otherwise null (all sites)
        return $_SESSION['selected_site_id'] ?? null;
    }
    
    // HR Admin can only see their assigned site(s)
    if (isHRAdmin()) {
        $siteId = getCurrentSiteId();
        // If HR Admin has multiple sites, they can switch, but default to primary
        return $siteId;
    }
    
    // Employee - no site filter needed (they see only own data)
    return null;
}

/**
 * Get accessible site IDs for WHERE IN clause
 */
function getAccessibleSiteIdsSQL() {
    $siteIds = getAccessibleSiteIds();
    
    if (empty($siteIds)) {
        return '1=1'; // No restriction (shouldn't happen, but safe fallback)
    }
    
    if (isSuperAdmin() && empty($_SESSION['selected_site_id'])) {
        // Super Admin viewing all sites
        return '1=1';
    }
    
    return 'site_id IN (' . implode(',', array_map('intval', $siteIds)) . ')';
}

/**
 * Get site filter SQL clause
 */
function getSiteFilterSQL($columnName = 'site_id') {
    $siteId = getSiteFilter();
    
    if ($siteId === null) {
        // Super Admin viewing all sites - no filter
        return '1=1';
    }
    
    return $columnName . ' = ' . (int)$siteId;
}

/**
 * Get site filter parameters for prepared statements
 */
function getSiteFilterParams() {
    $siteId = getSiteFilter();
    
    if ($siteId === null) {
        return [];
    }
    
    return [$siteId];
}

/**
 * Check if user can access employee data
 * Employee can only see own data, HR Admin can see their site's employees, Super Admin can see all
 */
function canAccessEmployee($employeeId) {
    startSession();
    
    // Super Admin can access all
    if (isSuperAdmin()) {
        return true;
    }
    
    // Employee can only access own data
    if (isEmployee()) {
        try {
            $db = getDB();
            $stmt = $db->prepare("SELECT employee_id FROM employees WHERE employee_id = ? AND email = ?");
            $stmt->execute([$employeeId, $_SESSION['email'] ?? '']);
            return (bool)$stmt->fetch();
        } catch (Exception $e) {
            return false;
        }
    }
    
    // HR Admin can access employees from their site
    if (isHRAdmin()) {
        try {
            $db = getDB();
            $siteId = getCurrentSiteId();
            $stmt = $db->prepare("SELECT employee_id FROM employees WHERE employee_id = ? AND site_id = ?");
            $stmt->execute([$employeeId, $siteId]);
            return (bool)$stmt->fetch();
        } catch (Exception $e) {
            return false;
        }
    }
    
    return false;
}

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

/**
 * Get accessible site IDs for current user
 * Returns array of site_ids user can access
 */
function getAccessibleSiteIds() {
    startSession();
    
    // Super Admin can access all sites
    if (isSuperAdmin()) {
        try {
            $db = getDB();
            $stmt = $db->prepare("SELECT site_id FROM sites WHERE site_status = 'active'");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_COLUMN);
        } catch (Exception $e) {
            return [];
        }
    }
    
    // HR Admin can access assigned sites
    if (isHRAdmin()) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                SELECT site_id FROM user_sites
                WHERE user_id = ?
            ");
            $stmt->execute([getCurrentUserId()]);
            return $stmt->fetchAll(PDO::FETCH_COLUMN);
        } catch (Exception $e) {
            return [];
        }
    }
    
    // Employee - no site access needed
    return [];
}

/**
 * Check if user can manage HR Admin
 * Only Super Admin can create/manage HR Admins
 */
function canManageHRAdmin() {
    return isSuperAdmin(); // isSuperAdmin() already handles role_code loading
}

/**
 * Check if user can create custom roles
 * Only Super Admin can create custom roles
 */
function canCreateCustomRoles() {
    startSession();
    
    if (!isset($_SESSION['user_id'])) {
        return false;
    }
    
    // Load role_code if not in session
    $roleCode = $_SESSION['role_code'] ?? '';
    
    if (empty($roleCode) && isset($_SESSION['role_id'])) {
        try {
            $db = getDB();
            $stmt = $db->prepare("SELECT role_code FROM roles WHERE role_id = ?");
            $stmt->execute([$_SESSION['role_id']]);
            $role = $stmt->fetch();
            if ($role) {
                $roleCode = $role['role_code'];
                $_SESSION['role_code'] = $roleCode;
            }
        } catch (Exception $e) {
            error_log("Error loading role_code in canCreateCustomRoles: " . $e->getMessage());
            return false;
        }
    }
    
    return strtolower($roleCode) === 'super_admin';
}

