<?php
header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials (no wildcard when credentials=true)
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require admin authentication
requireAdmin(true);

// Load centralized database connection
require_once __DIR__ . '/includes/Database.php';
try {
    $pdo = Database::getInstance()->getConnection();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database connection failed']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

// Start impersonation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($data['username'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Username is required']);
        exit;
    }

    try {
        // Select only common columns to be schema-safe
        $stmt = $pdo->prepare('SELECT id, username, email FROM users WHERE username = ?');
        $stmt->execute([$data['username']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            http_response_code(404);
            echo json_encode(['success' => false, 'error' => 'User not found']);
            exit;
        }

        // Store original admin and session context (once)
        if (!isset($_SESSION['original_admin_id'])) {
            $_SESSION['original_admin_id'] = $_SESSION['admin_id'] ?? (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null);
            $_SESSION['original_admin_username'] = $_SESSION['admin_username'] ?? ($_SESSION['username'] ?? null);
        }
        $_SESSION['pre_impersonate_user_id'] = $_SESSION['user_id'] ?? null;
        $_SESSION['pre_impersonate_username'] = $_SESSION['username'] ?? null;
        $_SESSION['pre_impersonate_logged_in'] = $_SESSION['logged_in'] ?? false;

        // Set effective user session to impersonated user
        $_SESSION['user_id'] = (int)$user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION["role"] = 'user';
        $_SESSION['email'] = $user['email'] ?? ($_SESSION['email'] ?? null);
        $_SESSION['logged_in'] = true;
        $_SESSION['is_impersonating'] = true;
        $_SESSION['impersonated_user_id'] = (int)$user['id'];

        // Best-effort admin log (ignore failures)
        try {
            $logStmt = $pdo->prepare("INSERT INTO admin_logs (admin_id, action, details) VALUES (:admin_id, :action, :details)");
            $logStmt->execute([
                ':admin_id' => $_SESSION['admin_id'] ?? ($_SESSION['original_admin_id'] ?? null),
                ':action' => 'impersonate_start',
                ':details' => json_encode([
                    'target_user_id' => $user['id'],
                    'target_username' => $user['username']
                ])
            ]);
        } catch (Exception $e) { /* ignore logging failure */ }

        echo json_encode(['success' => true, 'message' => 'Impersonation started']);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Database error']);
    }
    
    exit;
}

// Stop impersonation
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    if (!isset($_SESSION['original_admin_id'])) {
        echo json_encode(['success' => true, 'message' => 'Not impersonating']);
        exit;
    }

    // Log stop event before clearing (best-effort)
    try {
        $logStmt = $pdo->prepare("INSERT INTO admin_logs (admin_id, action, details) VALUES (:admin_id, :action, :details)");
        $logStmt->execute([
            ':admin_id' => $_SESSION['admin_id'] ?? ($_SESSION['original_admin_id'] ?? null),
            ':action' => 'impersonate_stop',
            ':details' => json_encode([
                'impersonated_user_id' => $_SESSION['impersonated_user_id'] ?? ($_SESSION['user_id'] ?? null),
                'impersonated_username' => $_SESSION['username'] ?? null
            ])
        ]);
    } catch (Exception $e) { /* ignore logging failure */ }

    // Restore admin session (effective user back to admin)
    $_SESSION['user_id'] = $_SESSION['original_admin_id'] ?? ($_SESSION['pre_impersonate_user_id'] ?? null);
    $_SESSION['username'] = $_SESSION['original_admin_username'] ?? ($_SESSION['pre_impersonate_username'] ?? null);
    $_SESSION['role'] = 'admin';
    $_SESSION['logged_in'] = true;

    // Clear impersonation data
    unset(
        $_SESSION['original_admin_id'],
        $_SESSION['original_admin_username'],
        $_SESSION['impersonated_user_id'],
        $_SESSION['pre_impersonate_user_id'],
        $_SESSION['pre_impersonate_username'],
        $_SESSION['pre_impersonate_logged_in'],
        $_SESSION['is_impersonating']
    );

    echo json_encode(['success' => true, 'message' => 'Impersonation ended']);
    exit;
}

// Get current impersonation status
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $response = [
        'is_impersonating' => !empty($_SESSION['is_impersonating']),
        'original_admin' => [
            'id' => $_SESSION['original_admin_id'] ?? null,
            'username' => $_SESSION['original_admin_username'] ?? null
        ],
        'current_user' => [
            'id' => $_SESSION['user_id'] ?? null,
            'username' => $_SESSION['username'] ?? null,
            'role' => $_SESSION['role'] ?? null
        ]
    ];
    
    echo json_encode(['success' => true, 'data' => $response]);
    exit;
}

http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Method not allowed']);
