<?php
/**
 * Enterprise HRM ERP System - Site Switcher Handler
 * Allows Super Admin and HR Admin to switch between sites/branches
 */

require_once __DIR__ . '/../includes/init.php';
requireLogin();

$siteId = isset($_GET['site_id']) ? (int)$_GET['site_id'] : null;

if ($siteId !== null) {
    // Validate site exists and user has access
    try {
        $db = getDB();
        
        if (isSuperAdmin()) {
            // Super Admin can switch to any active site
            $stmt = $db->prepare("SELECT site_id, site_name, site_code FROM sites WHERE site_id = ? AND site_status = 'active'");
            $stmt->execute([$siteId]);
            $site = $stmt->fetch();
            
            if ($site) {
                $_SESSION['selected_site_id'] = $siteId;
                $_SESSION['site_id'] = $siteId;
                $_SESSION['site_name'] = $site['site_name'];
                $_SESSION['site_code'] = $site['site_code'];
            } else {
                $_SESSION['error'] = 'Invalid site selected.';
            }
        } elseif (isHRAdmin()) {
            // HR Admin can only switch to their assigned branches
            $stmt = $db->prepare("
                SELECT s.site_id, s.site_name, s.site_code
                FROM user_sites us
                INNER JOIN sites s ON us.site_id = s.site_id
                WHERE us.user_id = ? AND s.site_id = ? AND s.site_status = 'active'
            ");
            $stmt->execute([getCurrentUserId(), $siteId]);
            $site = $stmt->fetch();
            
            if ($site) {
                $_SESSION['site_id'] = $siteId;
                $_SESSION['site_name'] = $site['site_name'];
                $_SESSION['site_code'] = $site['site_code'];
            } else {
                $_SESSION['error'] = 'You do not have access to this branch.';
            }
        } else {
            $_SESSION['error'] = 'You do not have permission to switch branches.';
        }
    } catch (Exception $e) {
        error_log("Error switching site: " . $e->getMessage());
        $_SESSION['error'] = 'Error switching branch.';
    }
} else {
    // Clear site selection (only for Super Admin)
    if (isSuperAdmin()) {
        unset($_SESSION['selected_site_id']);
        $_SESSION['site_id'] = null;
        $_SESSION['site_name'] = 'All Sites';
        $_SESSION['site_code'] = 'ALL';
    } else {
        $_SESSION['error'] = 'Invalid request.';
    }
}

// Redirect back to referrer or specified redirect URL
$redirect = $_GET['redirect'] ?? $_SERVER['HTTP_REFERER'] ?? BASE_URL . '/dashboard.php';
header('Location: ' . $redirect);
exit;

