<?php
$env = [];

// Indlæs .env-fil
$envFile = dirname(__DIR__) . '/.env';
foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
    if (strpos(ltrim($line), '#') === 0) continue;

    $p = explode('=', $line, 2);
    if (count($p) === 2) {
        $env[trim($p[0])] = trim($p[1]);
    }
}

// Hent token fra .env
$token = isset($env['TWITCH_OAUTH'])
    ? preg_replace('/^oauth:/i', '', $env['TWITCH_OAUTH'])
    : '';

if (!$token) {
    echo 'Mangler TWITCH_OAUTH';
    exit;
}

// Kald Twitch validate endpoint
$ch = curl_init('https://id.twitch.tv/oauth2/validate');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['Authorization: OAuth ' . $token],
    CURLOPT_TIMEOUT        => 10,
]);
$res  = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Returnér resultat som JSON
header('Content-Type: application/json');
echo json_encode(
    [
        'http' => $http,
        'data' => json_decode($res, true),
    ],
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
);
