<?php

if ( !$user['superAdmin'] ) {
    exit;
}

$userId = $_GET['id'];

$selector    = bin2hex(random_bytes(12));
$token       = bin2hex(random_bytes(32));
$hashedToken = hash('sha256', $token);
$expiry      = date('Y-m-d H:i:s', strtotime('+30 minutes', time()));

include 'get-client-info.php';

$db->insert('auth_token', [
    'selector'   => $selector,
    'token'      => $hashedToken,
    'expiresAt'  => $expiry,
    'userId'     => $userId,
    'consumedAt' => date('Y-m-d H:i:s'),
    'consumedBy' => $user['id'],
    'ip' => $ip,
    'ua' => $ua
]);

setcookie('btbImpersonate', "$selector:$token", time()+(365*24*60*60), '/clients', URL_COOKIES);
header('Location: '.URL_APP_ADMIN);
exit;
?>