<?php
session_start();
require_once 'db/config.php';

// 1. Check if the current user is an Admin or HR Manager (e.g., role_id 1 or 2)
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    header('HTTP/1.1 403 Forbidden');
    exit('You do not have permission to perform this action.');
}

// 2. Get the user ID to impersonate
$impersonatedUserId = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
if (!$impersonatedUserId) {
    exit('Invalid user ID provided for impersonation.');
}

// 3. Store the original user's ID if not already impersonating
if (!isset($_SESSION['original_user_id'])) {
    $_SESSION['original_user_id'] = $_SESSION['user_id'];
}

// 4. Switch the session to the new user
$_SESSION['user_id'] = $impersonatedUserId;

// Redirect to the employee's view
header('Location: employee_view.php');
exit;
