<?php
//Developer: core tech web designTechnology
// Admin "Login as User" - Impersonate a user account

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

// Load config
$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (!file_exists($config_path)) {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}
include($config_path);

// Verify current user is admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized. Admin access required.']);
    exit();
}

// Validate request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$target_user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;

if ($target_user_id <= 0) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid user ID']);
    exit();
}

// Don't allow impersonating yourself
if ($target_user_id == $_SESSION['user_id']) {
    echo json_encode(['status' => '0', 'msg' => 'You cannot impersonate yourself']);
    exit();
}

try {
    // Verify target user exists
    $stmt = $pdo->prepare("SELECT id, username, email FROM users WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $target_user_id]);
    $target_user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$target_user) {
        echo json_encode(['status' => '0', 'msg' => 'User not found']);
        exit();
    }

    // Store admin's original session data so we can switch back
    $_SESSION['admin_impersonating'] = true;
    $_SESSION['admin_original_user_id'] = $_SESSION['user_id'];
    $_SESSION['admin_original_email'] = $_SESSION['user_email'] ?? '';

    // Switch session to target user
    $_SESSION['user_id'] = $target_user['id'];
    $_SESSION['user_email'] = $target_user['email'];
    $_SESSION['logged_in'] = true;
    $_SESSION['verified'] = true;
    $_SESSION['is_admin'] = 0; // Act as regular user

    echo json_encode([
        'status' => '1',
        'msg' => 'Now logged in as ' . $target_user['username'],
        'redirect' => $site_data['web_url'] . '/user/dashboard'
    ]);

} catch (PDOException $e) {
    error_log("Login as user error: " . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'Database error occurred']);
}
