<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

/* ===============================
   VALIDATE USER ID
================================ */
$userId = (int)($_GET['id'] ?? 0);
if ($userId < 1) {
    flash('err', 'Invalid user.');
    redirect('customers.php');
}

/* ===============================
   LOAD TARGET USER
================================ */
$st = $conn->prepare("
    SELECT *
    FROM users
    WHERE id = ?
      AND banned = 'no'
      AND status = 'active'
    LIMIT 1
");
$st->bind_param("i", $userId);
$st->execute();
$user = $st->get_result()->fetch_assoc();

if (!$user) {
    flash('err', 'User not found or not allowed.');
    redirect('customers.php');
}

/* ===============================
   STORE ADMIN SESSION
================================ */
if (!isset($_SESSION['admin_impersonator'])) {
    $_SESSION['admin_impersonator'] = current_user()['id'];
}

/* ===============================
   SWITCH SESSION USER
================================ */
session_regenerate_id(true); // prevent fixation
$_SESSION['user'] = $user;

/* ===============================
   AUDIT LOG (OPTIONAL BUT RECOMMENDED)
================================ */
$meta = json_encode([
    'impersonated_user_id' => $user['id'],
    'admin_id' => $_SESSION['admin_impersonator']
]);

$ip = client_ip();

$log = $conn->prepare("
    INSERT INTO audit_logs (actor_id, action, meta, ip)
    VALUES (?, 'ADMIN_IMPERSONATE', ?, ?)
");
$log->bind_param("iss", $_SESSION['admin_impersonator'], $meta, $ip);
$log->execute();

/* ===============================
   REDIRECT AS CUSTOMER
================================ */
redirect('/customer/dashboard.php');
