<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

// Debug-safe error logging
ini_set('display_errors', '0');
ini_set('log_errors', '1');
if (!ini_get('error_log')) {
    ini_set('error_log', __DIR__ . '/php-error.log');
}

// -------------------
// Include DB config
// -------------------
require_once __DIR__ . '/../unified_config.php';
if (function_exists('db')) {
    $conn = db();
} elseif (isset($conn) && $conn instanceof mysqli) {
    // ok
} else {
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Database connection not configured"]);
    exit;
}

// -------------------
// Read POST data
// -------------------
$data = json_decode(file_get_contents("php://input"), true);
$admin_email = trim($data['admin_email'] ?? '');
$client_email = trim($data['client_email'] ?? '');

// Validate
if (!$admin_email || !$client_email) {
    http_response_code(400);
    echo json_encode(["success" => false, "message" => "admin_email and client_email are required"]);
    exit;
}

// -------------------
// Verify admin email exists
// -------------------
$stmt = $conn->prepare("SELECT * FROM adminlogins WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $admin_email);
$stmt->execute();
$admin = $stmt->get_result()->fetch_assoc();

if (!$admin) {
    http_response_code(401);
    echo json_encode(["success" => false, "message" => "Invalid admin email"]);
    exit;
}

// -------------------
// Fetch client info
// -------------------
$stmt2 = $conn->prepare("SELECT * FROM loginusers WHERE email = ? LIMIT 1");
$stmt2->bind_param("s", $client_email);
$stmt2->execute();
$client = $stmt2->get_result()->fetch_assoc();

if (!$client) {
    http_response_code(404);
    echo json_encode(["success" => false, "message" => "Client not found"]);
    exit;
}

// -------------------
// Start session as client
// -------------------
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$_SESSION['clogin'] = $client['email'];
$_SESSION['client_id'] = $client['id'];
$_SESSION['admin_impersonate'] = true;

// -------------------
// Return client info
// -------------------
echo json_encode([
    "success" => true,
    "message" => "Logged in as client successfully",
    "user" => [
        "id" => (int)$client['id'],
        "email" => $client['email'],
        "first_name" => $client['first_name'],
        "last_name" => $client['last_name'],
        "uid" => $client['uid'],
        "email_confirmed" => (int)$client['email_confirmed']
    ]
]);
exit;
?>
