<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

require_login();

$action = $_GET['action'] ?? '';

// 1. STOP IMPERSONATION
if ($action === 'stop' && isset($_SESSION['admin_user_id'])) {
    $admin_id = $_SESSION['admin_user_id'];
    
    try {
        $stmt = $pdo->prepare("SELECT id, name, role FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin = $stmt->fetch();
        
        if ($admin) {
            $_SESSION['user_id'] = $admin['id'];
            $_SESSION['user_name'] = $admin['name'];
            $_SESSION['role'] = $admin['role'];
            unset($_SESSION['admin_user_id']);
            
            redirect('superadmin.php?tab=users');
        }
    } catch (PDOException $e) {
        die("Error reverting to admin: " . $e->getMessage());
    }
}

// 2. START IMPERSONATION
if (isset($_GET['id'])) {
    // Only admins can start impersonation
    if ($_SESSION['role'] !== 'admin') {
        die("Unauthorized access.");
    }

    $target_user_id = (int)$_GET['id'];
    
    // Don't impersonate yourself
    if ($target_user_id === (int)$_SESSION['user_id']) {
        redirect('superadmin.php?tab=users');
    }

    try {
        $stmt = $pdo->prepare("SELECT id, name, role FROM users WHERE id = ?");
        $stmt->execute([$target_user_id]);
        $user = $stmt->fetch();
        
        if ($user) {
            // Store current admin ID if not already impersonating
            if (!isset($_SESSION['admin_user_id'])) {
                $_SESSION['admin_user_id'] = $_SESSION['user_id'];
            }
            
            // Switch to target user
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['role'] = $user['role'];
            
            redirect('dashboard.php');
        } else {
            die("User not found.");
        }
    } catch (PDOException $e) {
        die("Error starting impersonation: " . $e->getMessage());
    }
}

// Default redirect if nothing happened
redirect('dashboard.php');
