<?php
// ✅ Tell the browser it's JSON
header('Content-Type: application/json');

// ✅ CORS Headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

include_once __DIR__ . '/config.php';

$response = ["success" => false, "message" => "Something went wrong"];

// ✅ Get user ID from GET or POST
$id = $_GET['id'] ?? $_POST['id'] ?? null;

if (!$id) {
    $response = ["success" => false, "message" => "User ID is required"];
    echo json_encode($response, JSON_PRETTY_PRINT);
    exit;
}

// ✅ Prepare statement to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM loginusers WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    $user = $result->fetch_assoc();

    // Remove sensitive fields
    unset($user['password'], $user['emailToken'], $user['mail_otp']);

    $response = [
        "success" => true,
        "message" => "✅ User fetched successfully",
        "data"    => $user
    ];
} else {
    $response = ["success" => false, "message" => "❌ User not found"];
}

$stmt->close();
$conn->close();

// ✅ Encode in JSON format
echo json_encode($response, JSON_PRETTY_PRINT);
?>
