<?php
// Allow cross-origin requests (CORS)
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Include database configuration
require_once 'config.php';  // This should be your DB connection file

$conn = getDbConnection();  // Connect to the MySQL database

// Get the Authorization header (Bearer token)
$headers = getallheaders();
if (!isset($headers['Authorization'])) {
    echo json_encode(array("status" => "error", "message" => "Authorization header missing"));
    exit();
}

// Extract the token from the header
$authHeader = $headers['Authorization'];
if (strpos($authHeader, "Bearer ") !== 0) {
    echo json_encode(array("status" => "error", "message" => "Invalid Authorization header format"));
    exit();
}
$token = trim(str_replace("Bearer ", "", $authHeader));

// Validate the token length
if (strlen($token) !== 32) {  // Assuming a 32-character token
    echo json_encode(array("status" => "error", "message" => "Invalid token"));
    exit();
}

// Query the database for the user with the given token
$stmt = $conn->prepare("SELECT real_name, username FROM users WHERE token = ?");
if ($stmt === false) {
    echo json_encode(array("status" => "error", "message" => "Database query error"));
    exit();
}

$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    // Token not found
    echo json_encode(array("status" => "error", "message" => "Invalid token"));
} else {
    // Fetch the user details
    $user = $result->fetch_assoc();
    echo json_encode(array(
        "status" => "success",
        "data" => array(
            "real_name" => $user['real_name'],
            "username" => $user['username']
        )
    ));
}

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

