<?php
/**
 * Enterprise HRM ERP System - Multi-Tenant Functions
 * Each HR Admin = Separate Tenant
 * Super Admin = Can see all tenants
 */

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

// getAccessibleSiteIds() is now in functions.php to avoid duplication

/**
 * Get current site ID (with Super Admin support)
 * Super Admin can switch sites via GET parameter
 * This function overrides the one in auth.php
 */
if (!function_exists('getCurrentSiteId')) {
    function getCurrentSiteId() {
        startSession();
        
        // Super Admin can switch sites
        if (isSuperAdmin()) {
            if (isset($_GET['site_id']) && is_numeric($_GET['site_id'])) {
                $requestedSiteId = (int)$_GET['site_id'];
                
                // Verify site exists and is active
                try {
                    $db = getDB();
                    $stmt = $db->prepare("SELECT site_id FROM sites WHERE site_id = ? AND site_status = 'active'");
                    $stmt->execute([$requestedSiteId]);
                    if ($stmt->fetch()) {
                        $_SESSION['site_id'] = $requestedSiteId;
                        // Update site name and code in session
                        $stmt = $db->prepare("SELECT site_name, site_code FROM sites WHERE site_id = ?");
                        $stmt->execute([$requestedSiteId]);
                        $site = $stmt->fetch();
                        if ($site) {
                            $_SESSION['site_name'] = $site['site_name'];
                            $_SESSION['site_code'] = $site['site_code'];
                        }
                    }
                } catch (Exception $e) {
                    error_log("Error switching site: " . $e->getMessage());
                }
            }
        }
        
        // Return current site_id from session
        return isset($_SESSION['site_id']) ? $_SESSION['site_id'] : null;
    }
}

/**
 * Check if user can access a specific site
 */
function canAccessSite($siteId) {
    if (!$siteId) {
        return false;
    }
    
    startSession();
    
    // Super Admin can access all sites
    if (isSuperAdmin()) {
        return true;
    }
    
    // Check if site is in accessible sites
    $accessibleSites = getAccessibleSiteIds();
    return in_array($siteId, $accessibleSites);
}

// getSiteFilter() is now in functions.php to avoid duplication

/**
 * Require site access (redirect if cannot access)
 */
function requireSiteAccess($siteId) {
    if (!canAccessSite($siteId)) {
        $_SESSION['error'] = 'You do not have permission to access this site.';
        header('Location: ' . BASE_URL . '/dashboard.php');
        exit;
    }
}

// isSuperAdmin() is now in functions.php to avoid duplication

/**
 * Is HR Admin
 */
function isHRAdmin() {
    startSession();
    $roleCode = strtolower($_SESSION['role_code'] ?? '');
    return in_array($roleCode, ['super_admin', 'hr_admin']);
}

