<?php
require __DIR__ . '/config.php';

header('Content-Type: application/json');

$conn = getDbConnection();

// ✅ Step 1: Check if Authorization header is present
$headers = getallheaders();
if (!isset($headers['Authorization'])) {
    echo json_encode(["success" => false, "status" => "error", "message" => "Missing Authorization Token"]);
    exit();
}

$authHeader = trim($headers['Authorization']);
$token = str_replace("Bearer ", "", $authHeader);

// ✅ Step 2: Validate token
$stmt = $conn->prepare("SELECT user_id, real_name, username, org_id FROM users WHERE token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if ($user) {
    echo json_encode([
        "success" => true,
        "status" => "success",
        "message" => "User details retrieved",
        "data" => $user
    ]);
} else {
    echo json_encode([
        "success" => false,
        "status" => "error",
        "message" => "Invalid or expired token"
    ]);
}

$conn->close();
?>
