<?php
/**
 * Enterprise HRM ERP System - Data Isolation Helper Functions
 * Helper functions to update all modules with data isolation
 */

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

/**
 * Get WHERE clause for site-based data isolation
 * Returns array with ['where' => 'SQL clause', 'params' => [params]]
 */
function getSiteIsolationWhere($tableAlias = '') {
    $prefix = $tableAlias ? $tableAlias . '.' : '';
    
    if (isSuperAdmin()) {
        $siteFilter = getSiteFilter();
        if ($siteFilter) {
            return [
                'where' => $prefix . 'site_id = ?',
                'params' => [$siteFilter]
            ];
        }
        // Super Admin viewing all sites
        return ['where' => '1=1', 'params' => []];
    }
    
    if (isHRAdmin()) {
        $accessibleSiteIds = getAccessibleSiteIds();
        if (empty($accessibleSiteIds)) {
            return ['where' => '1=0', 'params' => []]; // No access
        }
        if (count($accessibleSiteIds) === 1) {
            return [
                'where' => $prefix . 'site_id = ?',
                'params' => [$accessibleSiteIds[0]]
            ];
        }
        $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
        return [
            'where' => $prefix . "site_id IN ($placeholders)",
            'params' => $accessibleSiteIds
        ];
    }
    
    // Employee - no site filter (they see only own data via other checks)
    return ['where' => '1=1', 'params' => []];
}

/**
 * Get employee filter for employee-specific data
 * Returns WHERE clause and params for employee data access
 */
function getEmployeeIsolationWhere($tableAlias = '', $employeeIdColumn = 'employee_id') {
    $prefix = $tableAlias ? $tableAlias . '.' : '';
    
    if (isEmployee()) {
        // Employee can only see own data
        try {
            $db = getDB();
            $stmt = $db->prepare("SELECT employee_id FROM employees WHERE email = ? LIMIT 1");
            $stmt->execute([$_SESSION['email'] ?? '']);
            $empId = $stmt->fetchColumn();
            
            if ($empId) {
                return [
                    'where' => $prefix . $employeeIdColumn . ' = ?',
                    'params' => [$empId]
                ];
            }
            return ['where' => '1=0', 'params' => []]; // No employee record found
        } catch (Exception $e) {
            return ['where' => '1=0', 'params' => []];
        }
    }
    
    // HR Admin and Super Admin - use site filter
    return getSiteIsolationWhere($tableAlias);
}

