<?php
// inc/functions.php
function send_json($data){
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function get_post_data(){
    // Support both form-urlencoded and raw json
    $data = $_POST;
    if(empty($data)){
        $raw = file_get_contents('php://input');
        $json = json_decode($raw, true);
        if(is_array($json)) $data = $json;
    }
    return $data;
}

function create_api_token($bytes = 32){
    try {
        return bin2hex(random_bytes($bytes)); // 64 chars for 32 bytes
    } catch (Exception $e) {
        return bin2hex(openssl_random_pseudo_bytes($bytes));
    }
}

function get_bearer_token(){
    // check Authorization header for Bearer token
    $headers = null;
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
    } elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        if (isset($requestHeaders['Authorization'])) {
            $headers = trim($requestHeaders['Authorization']);
        }
    }
    if (!empty($headers) && preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
        return $matches[1];
    }
    return null;
}
?>
