<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

$action   = $_GET['action'] ?? '';
$targetId = (int)($_GET['user_id'] ?? 0);

// EXIT — restaurer l'admin sans vérification (on est en mode impersonation)
if ($action === 'exit') {
    if (!empty($_SESSION['admin_original_id'])) {
        $_SESSION['user_id']     = (int)$_SESSION['admin_original_id'];
        $_SESSION['auth_method'] = 'password';
        unset($_SESSION['admin_impersonating']);
        unset($_SESSION['admin_original_id']);
        unset($_SESSION['admin_original_name']);
    }
    header("Location: admin.php"); exit;
}

// LOGIN — vérifier que c'est bien un admin
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

if ($action === 'login' && $targetId) {
    $_SESSION['admin_original_id']   = $_SESSION['user_id'];
    $_SESSION['admin_original_name'] = $user['username'];
    $_SESSION['user_id']             = $targetId;
    $_SESSION['auth_method']         = 'password';
    $_SESSION['admin_impersonating'] = true;
    header("Location: index.php"); exit;
}

header("Location: admin_users.php"); exit;
?>
