<?php

declare(strict_types=1);

/**
 * Shortlink Client — PHP cURL helper.
 *
 * Standalone, dependency-free. Drop on any host and call create_shortlink()
 * to mint a shortlink via the open api.php endpoint.
 */

/**
 * Create a shortlink.
 *
 * @param string               $apiUrl URL of api.php (e.g. 'https://me.ixg.llc/api.php')
 * @param string               $target Destination URL (required, http/https)
 * @param array<string,string> $meta   Optional OG metadata: title, desc, img, code
 *
 * @return array{ok: bool, code?: string, short_url?: string, err?: string}
 */
function create_shortlink(string $apiUrl, string $target, array $meta = []): array
{
    if ($apiUrl === '') {
        return ['ok' => false, 'err' => 'missing api url'];
    }

    if (!filter_var($target, FILTER_VALIDATE_URL) || !preg_match('#^https?://#i', $target)) {
        return ['ok' => false, 'err' => 'invalid url'];
    }

    $params = array_merge([
        'url'   => $target,
        'title' => '',
        'desc'  => '',
        'img'   => '',
        'code'  => '',
    ], $meta);

    $ch = curl_init();
    if ($ch === false) {
        return ['ok' => false, 'err' => 'curl init failed'];
    }

    curl_setopt_array($ch, [
        CURLOPT_URL            => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($params),
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_HTTPHEADER     => ['Accept: application/json'],
    ]);

    $raw  = curl_exec($ch);
    $err  = curl_error($ch);
    $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($raw === false || $err !== '') {
        return ['ok' => false, 'err' => 'curl: ' . ($err !== '' ? $err : 'request failed')];
    }

    $data = json_decode((string) $raw, true);
    if (!is_array($data)) {
        return ['ok' => false, 'err' => "http {$code}: invalid json response"];
    }

    return [
        'ok'        => (bool) ($data['ok'] ?? false),
        'code'      => isset($data['code']) && is_string($data['code']) ? $data['code'] : '',
        'short_url' => isset($data['short_url']) && is_string($data['short_url']) ? $data['short_url'] : '',
        'err'       => isset($data['err']) && is_string($data['err']) ? $data['err'] : '',
    ];
}

// ── CLI usage example ──
if (PHP_SAPI === 'cli') {
    $result = create_shortlink(
        'https://me.ixg.llc/api.php',   // ← your api.php domain
        'https://example.com/long-url', // ← target URL
        ['title' => 'My Page'],
    );

    if ($result['ok'] ?? false) {
        echo '✅ Shortlink: ' . ($result['short_url'] ?? '') . PHP_EOL;
        echo '   Code     : ' . ($result['code'] ?? '') . PHP_EOL;
    } else {
        $err = $result['err'] ?? 'unknown';
        echo '❌ Error: ' . (is_string($err) ? $err : 'unknown') . PHP_EOL;
    }
}
