<?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';

$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();
}

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

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

$st = $pdo->prepare('SELECT id, email, first_name, last_name, status FROM clients WHERE id = ? AND status = "active"');
$st->execute([$clientId]);
$client = $st->fetch(PDO::FETCH_ASSOC);
if (!$client) { header('Location: ' . route_url(['module'=>'clients']) . '?module=clients&error=client_not_found'); exit; }

$_SESSION['client_id'] = (int)$client['id'];
$_SESSION['client_email'] = $client['email'] ?? '';
$_SESSION['client_name'] = trim(($client['first_name'] ?? '') . ' ' . ($client['last_name'] ?? ''));
$_SESSION['client_first_name'] = $client['first_name'] ?? '';
$_SESSION['client_last_name'] = $client['last_name'] ?? '';
$_SESSION['client_status'] = 'active';
$_SESSION['impersonation_mode'] = 'staff_to_client';
$_SESSION['impersonated_by'] = $uid;

$redirect = module_url('client_portal/dashboard.php');
header('Location: ' . $redirect);
exit;
?>
