<?php
declare(strict_types=1);

require_once __DIR__ . '/authz.php';

/* Start impersonation (Admin → lower role), READ-ONLY */
function elms_start_impersonation(int $targetUserId, string $reason): bool {
  if (!elms_is_any(['super_admin','admin'])) return false;

  $db = elms_db();

  // Fetch target user payload (only the fields we need in session)
  $st = $db->prepare("SELECT id, username, role_code, full_name, email FROM elms_users WHERE id=? AND is_active=1 LIMIT 1");
  $st->bind_param('i', $targetUserId);
  $st->execute();
  $u = $st->get_result()->fetch_assoc();
  $st->close();
  if (!$u) return false;

  // Record impersonation row
  $adminId = elms_user_id();
  $ro = 1;
  $st = $db->prepare("INSERT INTO elms_impersonations (admin_user_id, target_user_id, reason, is_readonly) VALUES (?,?,?,?)");
  $st->bind_param('iisi', $adminId, $targetUserId, $reason, $ro);
  $st->execute();
  $impId = $db->insert_id;
  $st->close();

  // Save original + impersonated in session
  $_SESSION['impersonate'] = [
    'enabled'  => true,
    'readonly' => true,
    'imp_id'   => $impId,
    'admin_id' => $adminId,
    'reason'   => $reason,
  ];
  $_SESSION['elms_user_backup'] = $_SESSION['elms_user'] ?? null;
  $_SESSION['elms_user'] = [
    'id'        => (int)$u['id'],
    'username'  => (string)$u['username'],
    'role_code' => (string)$u['role_code'],
    'full_name' => (string)($u['full_name'] ?? ''),
    'email'     => (string)($u['email'] ?? ''),
  ];

  elms_audit('impersonate.start', 'user', (string)$targetUserId, ['reason'=>$reason, 'readonly'=>true]);
  return true;
}

/* Stop impersonation */
function elms_stop_impersonation(): void {
  if (empty($_SESSION['impersonate'])) return;
  $impId = (int)($_SESSION['impersonate']['imp_id'] ?? 0);

  if ($impId > 0) {
    $db = elms_db();
    $st = $db->prepare("UPDATE elms_impersonations SET ended_at=NOW() WHERE id=? LIMIT 1");
    $st->bind_param('i', $impId);
    $st->execute();
    $st->close();
  }

  $_SESSION['impersonate'] = null;
  if (isset($_SESSION['elms_user_backup'])) {
    $_SESSION['elms_user'] = $_SESSION['elms_user_backup'];
    unset($_SESSION['elms_user_backup']);
  }
  elms_audit('impersonate.stop', null, null, []);
}
