<?php

declare(strict_types=1);

include_once dirname(__DIR__, 2) . '/env.php';
load_env_file(dirname(__DIR__, 2) . '/.env');
include_once __DIR__ . '/../session_guards.php';

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

startUserGuardSession();
if (authenticatedUserSubId() === '') {
    http_response_code(403);
    echo json_encode(['ok' => false, 'err' => 'unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'err' => 'method-not-allowed', 'allow' => 'POST']);
    exit;
}

if (!hasValidSessionCsrf('user_portal', requestCsrfToken())) {
    http_response_code(419);
    echo json_encode(['ok' => false, 'err' => 'invalid-csrf']);
    exit;
}

$longurl = trim((string) ($_POST['longurl'] ?? ''));
$prm     = (string) ($_POST['prm'] ?? '');

if ($longurl === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'err' => 'missing longurl']);
    exit;
}

if (!filter_var($longurl, FILTER_VALIDATE_URL)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'err' => 'invalid longurl']);
    exit;
}

$scheme = strtolower((string) parse_url($longurl, PHP_URL_SCHEME));
if ($scheme !== 'http' && $scheme !== 'https') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'err' => 'unsupported-url-scheme']);
    exit;
}

$host = strtolower((string) parse_url($longurl, PHP_URL_HOST));
if ($host === 'localhost' || $host === '127.0.0.1' || $host === '::1') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'err' => 'blocked-local-url']);
    exit;
}

$apiKey = app_env('IXG_EU_API_KEY', '');
if ($apiKey === '' || $apiKey === null) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'err' => 'api-key-not-configured']);
    exit;
}

$endpoint = 'https://ixg.llc/api.php?longurl=' . rawurlencode($longurl) . '&random_domain=1';

$ch = curl_init($endpoint);
if ($ch === false) {
    error_log('ixgeu: curl_init failed');
    http_response_code(500);
    echo json_encode(['ok' => false, 'err' => 'curl-init-failed']);
    exit;
}

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_HTTPGET         => true,
    CURLOPT_SSL_VERIFYPEER  => true,
    CURLOPT_SSL_VERIFYHOST  => 2,
    CURLOPT_CONNECTTIMEOUT  => 5,
    CURLOPT_TIMEOUT         => 12,
    CURLOPT_FOLLOWLOCATION  => false,
    CURLOPT_USERAGENT       => 'SRP/1.0',
    CURLOPT_HTTPHEADER      => [
        'Authorization: Bearer ' . $apiKey,
        'Accept: application/json',
    ],
]);

$resp = curl_exec($ch);
$cerr = curl_error($ch);
$http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($resp === false || $cerr !== '') {
    error_log('ixgeu: curl error: ' . $cerr);
    http_response_code(502);
    echo json_encode(['ok' => false, 'err' => 'curl-error']);
    exit;
}

$j = json_decode((string) $resp, true);
if (!is_array($j)) {
    error_log('ixgeu: bad JSON from upstream, http=' . $http);
    http_response_code(502);
    echo json_encode(['ok' => false, 'err' => 'bad-upstream-response']);
    exit;
}

// Surface the real upstream rejection (e.g. "Invalid API token") instead of a
// vague "no short URL" — the upstream reports failures via ok=false + error.
$upstreamErr = is_string($j['error'] ?? null) ? $j['error'] : '';
if (($j['ok'] ?? null) === false || $upstreamErr !== '') {
    error_log('ixgeu: upstream API error, http=' . $http . ($upstreamErr !== '' ? ', msg=' . $upstreamErr : ''));
    http_response_code(502);
    echo json_encode(['ok' => false, 'err' => 'upstream-api-error', 'msg' => $upstreamErr]);
    exit;
}

$short = '';
foreach (['short_url', 'shorturl', 'short', 'url', 'link'] as $key) {
    if (isset($j[$key]) && is_string($j[$key]) && filter_var($j[$key], FILTER_VALIDATE_URL) !== false) {
        $short = $j[$key];
        break;
    }
}

if ($short === '') {
    error_log('ixgeu: no short URL in API response, http=' . $http);
    http_response_code(502);
    echo json_encode(['ok' => false, 'err' => 'no-short-url']);
    exit;
}

function rand_token_ixgeu(int $n): string
{
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $len = strlen($alphabet);
    $s = '';
    for ($i = 0; $i < $n; $i++) {
        $s .= $alphabet[random_int(0, $len - 1)];
    }

    return $s;
}

$shim = match ($prm) {
    'b' => 'https://l.facebook.com/l.php?u=' . rawurlencode($short) . '&h=' . rand_token_ixgeu(7) . '&s=1',
    'f' => 'https://l.wl.co/l?u=' . rawurlencode($short),
    default => $short,
};

echo json_encode([['l' => $shim]], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
