<?php

/**
 * POST /api/is.gd.php
 *
 * Shorten URL via is.gd simple API (format=simple).
 * Requires active user session + CSRF token.
 *
 * POST body:
 *   longurl — URL to shorten (required)
 *   prm     — shim prefix: 'b' = facebook, 'f' = whatsapp
 */

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');

// ── Auth ──────────────────────────────────────────────────────────────────────
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;
}

// ── Input ─────────────────────────────────────────────────────────────────────
$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;
}

// ── is.gd simple API ──────────────────────────────────────────────────────────
$endpoint = 'https://is.gd/create.php?' . http_build_query([
    'format' => 'json',
    'url'    => $longurl,
], '', '&', PHP_QUERY_RFC3986);

$ch = curl_init($endpoint);

if ($ch === false) {
    http_response_code(502);
    echo json_encode(['ok' => false, 'err' => 'curl-init-failed']);
    exit;
}

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 8,
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
]);

$body  = curl_exec($ch);
$errNo = curl_errno($ch);
$http  = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($body === false || $errNo !== 0) {
    http_response_code(502);
    echo json_encode(['ok' => false, 'err' => 'upstream-unreachable']);
    exit;
}

$short = trim((string) $body);

// is.gd returns plain-text error: "Error: ..."
if ($short === '' || stripos($short, 'error') === 0) {
    http_response_code(502);
    echo json_encode(['ok' => false, 'err' => 'upstream-api-error']);
    exit;
}

// format=json returns {"shorturl": "https://is.gd/xxxx"}
$json = json_decode($short, true);
if (is_array($json) && isset($json['shorturl']) && is_string($json['shorturl'])) {
    $short = $json['shorturl'];
}

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

// ── Shim (Facebook / WhatsApp wrapper) ────────────────────────────────────────
$shim = match ($prm) {
    'b' => 'https://l.facebook.com/l.php?u=' . rawurlencode($short) . '&h=' . bin2hex(random_bytes(4)) . '&s=1',
    'f' => 'https://l.wl.co/l?u=' . rawurlencode($short),
    default => $short,
};

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