<?php
/**
 * Sysadmin "View as user" controller.
 *
 *   POST id=NN              -> start impersonating that user
 *   POST stop=1             -> stop, return to sysadmin session
 *
 * After successful start, redirects:
 *   - to /dashboard.php       if target is internal
 *   - to /client/dashboard.php?slug=... if target is client
 */
require_once __DIR__ . '/../includes/config.php';
$me = require_login('internal');

// While impersonating, current_user() is the target — authorise against the real sysadmin behind it
// so a sysadmin can hop straight from one user to another without stopping first.
$adminId = is_impersonating() ? (int) impersonator_id() : (int) $me['id'];
if (!user_has_role($adminId, 'sysadmin')) {
    http_response_code(403); exit('Only sysadmin can impersonate.');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('/admin/users.php');
}
csrf_check_or_die();

if (!empty($_POST['stop'])) {
    if (is_impersonating()) {
        $imp = impersonator_id();
        audit_log('user.impersonate.stop', 'user', impersonator_id(), null, null, $imp);
    }
    end_impersonation();
    flash('success', 'Impersonation ended.');
    redirect('/dashboard.php');
}

$id = (int) ($_POST['id'] ?? 0);
if (!$id) { flash('error', 'Pick a user to impersonate.'); redirect('/admin/users.php'); }

$stmt = db()->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$target = $stmt->fetch();
if (!$target) { flash('error', 'User not found.'); redirect('/admin/users.php'); }

audit_log('user.impersonate.start', 'user', $id, null, ['target_email' => $target['email']]);

if (is_impersonating()) {
    // Already impersonating → hop straight to another user. The session was already regenerated
    // when impersonation began, so just swap the target (a 2nd session_regenerate in one request
    // drops the session under strict mode). The original sysadmin (_impersonator_uid) is kept.
    $_SESSION['uid']            = (int) $target['id'];
    $_SESSION['user_type']      = $target['user_type'];
    $_SESSION['client_id']      = $target['client_id'] ?? null;
    $_SESSION['must_change_pw'] = false;
    $_SESSION['last_activity']  = time();
} else {
    begin_impersonation($id);
}

if ($target['user_type'] === 'client') {
    $slug = db()->prepare('SELECT login_slug FROM client_branding WHERE client_id = ?');
    $slug->execute([$target['client_id']]);
    $slug = $slug->fetchColumn();
    redirect('/client/overall.php?slug=' . urlencode((string) $slug));
}
redirect('/dashboard.php');
