<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(dirname(__DIR__)))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

$clientId = (int)($_GET['client_id'] ?? 0);
if ($clientId <= 0) { header('Location: ' . route_url(['module'=>'clients','error'=>'invalid_client'])); exit; }

$db = Database::getInstance();
$pdo = $db->getConnection();

function userHasPermissionByName(PDO $pdo, string $permName, int $userId): bool {
    $st = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
    $st->execute([$userId, $permName]);
    return (bool)$st->fetchColumn();
}
function isAdminRole(PDO $pdo, int $userId): bool {
    if ($userId <= 0) return false;
    $stmt = $pdo->prepare("SELECT 1 FROM user_roles ur INNER JOIN roles r ON ur.role_id = r.id WHERE ur.user_id = ? AND r.name = 'admin' LIMIT 1");
    $stmt->execute([$userId]);
    return (bool)$stmt->fetchColumn();
}

$userId = (int)($_SESSION['user_id'] ?? 0);
if (!$userId || (!isAdminRole($pdo, $userId) && !userHasPermissionByName($pdo, 'clients.webtrader_login', $userId))) {
    header('Location: ' . route_url(['module'=>'clients','error'=>'forbidden']));
    exit;
}

$stmt = $pdo->prepare("SELECT id, status FROM clients WHERE id = ? LIMIT 1");
$stmt->execute([$clientId]);
$client = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$client || ($client['status'] ?? '') !== 'active') { header('Location: ' . route_url(['module'=>'clients','error'=>'inactive_client'])); exit; }

$_SESSION['impersonator_user_id'] = $userId;
$_SESSION['client_id'] = $clientId;

header('Location: ' . module_url('webtrader/client_access.php'));
exit;
?>
