<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal login sebagai pengguna.', 'redirect_url' => null];

require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../includes/session.php';
require_once __DIR__ . '/../../../lib/Auth.php';
require_once __DIR__ . '/../../../includes/functions.php';

if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    $response['message'] = 'Akses ditolak. Hanya admin.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in admin/login_as_user.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

$requestData = json_decode(file_get_contents('php://input'), true);
$targetUserId = filter_var($requestData['user_id'] ?? null, FILTER_VALIDATE_INT);
$originalAdminId = $_SESSION['user_id']; 

if (!$targetUserId) {
    http_response_code(400);
    $response['message'] = 'ID pengguna target tidak valid.';
    echo json_encode($response);
    exit;
}

if ($targetUserId === $originalAdminId) {
    http_response_code(400);
    $response['message'] = 'Anda tidak dapat login sebagai diri sendiri.';
    echo json_encode($response);
    exit;
}

try {
    $auth = new Auth($pdo);
    $targetUser = $auth->getUserById($targetUserId);

    if (!$targetUser) {
        http_response_code(404);
        $response['message'] = 'Pengguna target tidak ditemukan.';
        echo json_encode($response);
        exit;
    }

    $_SESSION['original_admin_id'] = $originalAdminId;
    $_SESSION['original_admin_username'] = $_SESSION['username']; 

    $adminDataToKeep = [
        'original_admin_id' => $_SESSION['original_admin_id'],
        'original_admin_username' => $_SESSION['original_admin_username']
    ];
    $_SESSION = $adminDataToKeep; 

    session_regenerate_id(true);

    $_SESSION['user_id'] = $targetUser['id'];
    $_SESSION['username'] = $targetUser['username'];
    $_SESSION['user_role'] = $targetUser['role'];
    $_SESSION['user_email'] = $targetUser['email'];
    $_SESSION['user_fullname'] = $targetUser['full_name'];
    $_SESSION['user_phone'] = $targetUser['phone_number'];
    $_SESSION['is_logged_in'] = true;
    $_SESSION['is_impersonating'] = true;

    $response['success'] = true;
    $response['message'] = 'Berhasil login sebagai ' . $targetUser['username'];
    $response['redirect_url'] = base_url('dashboard'); 

} catch (\PDOException $e) {
    error_log("Admin Login As User DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("Admin Login As User General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
