<?php
/**
 * PUQ Vanity Shop — server-side proxy/cache (one of two files).
 * Companion: index.html (the landing page + JS that calls this).
 *
 * Drop BOTH files into the web root of any marketing domain. The page's JS
 * calls THIS file (same origin); this file talks to your WHMCS module API
 * (server-to-server, holding the shared key) and caches the answers so a
 * flood of identical lookups never hammers WHMCS.
 *
 * ─────────────────────────────────────────────────────────────────────────
 *  CONFIGURE THESE THREE VALUES (identical on every domain you deploy to):
 * ───────────────────────────────────────────────────────────────────────── */

const WHMCS_URL   = 'https://whmcs.example.com';   // your WHMCS base URL (no trailing slash)
const API_KEY     = 'PASTE-KEY-FROM-MODULE-PAGE';  // PUQ Web Hosting → Vanity widget → API key
const PRODUCT_ID  = 0;                             // the vanity product id (pid) — see the module page

/* ───────────────────────────── nothing to edit below ──────────────────── */

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$out = function (array $a, int $code = 200) {
    if ($code !== 200) http_response_code($code);
    echo json_encode($a, JSON_UNESCAPED_UNICODE);
    exit;
};

if (API_KEY === '' || API_KEY === 'PASTE-KEY-FROM-MODULE-PAGE' || (int) PRODUCT_ID <= 0
    || WHMCS_URL === '' || WHMCS_URL === 'https://whmcs.example.com') {
    $out(['status' => 'error', 'msg' => 'Widget not configured — edit WHMCS_URL, API_KEY and PRODUCT_ID at the top of proxy.php.'], 500);
}

$apiBase = rtrim(WHMCS_URL, '/') . '/modules/servers/puqWebHosting/vanity_api.php';

/** Server-to-server GET → decoded JSON (adds the key; key never reaches the browser). */
$callWhmcs = function (array $params) use ($apiBase) {
    $params['key'] = API_KEY;
    $params['pid'] = (int) PRODUCT_ID;
    $url = $apiBase . '?' . http_build_query($params);
    $raw = false;
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 8,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_USERAGENT      => 'PUQ-Vanity-Shop/1.0',
        ]);
        $raw = curl_exec($ch);
        curl_close($ch);
    } else {
        $raw = @file_get_contents($url, false, stream_context_create(['http' => ['timeout' => 8]]));
    }
    if ($raw === false || $raw === '') return ['status' => 'error', 'msg' => 'Upstream unreachable'];
    $j = json_decode($raw, true);
    return is_array($j) ? $j : ['status' => 'error', 'msg' => 'Bad upstream response'];
};

$api = (string) ($_GET['api'] ?? '');

if ($api === 'bootstrap') {
    // Shared file cache (across all visitors) — domains/ids change rarely, so
    // this is what really shields the WHMCS API. TTL 5 min.
    $cacheFile = sys_get_temp_dir() . '/puq_vanity_boot_' . (int) PRODUCT_ID . '.json';
    if (is_file($cacheFile) && (time() - (int) @filemtime($cacheFile)) < 300) {
        $cached = @file_get_contents($cacheFile);
        if ($cached !== false && $cached !== '') { echo $cached; exit; }
    }
    $r = $callWhmcs(['action' => 'bootstrap']);
    if (($r['status'] ?? '') === 'success') {
        @file_put_contents($cacheFile, json_encode($r, JSON_UNESCAPED_UNICODE), LOCK_EX);
    }
    $out($r);
}

if ($api === 'check') {
    $name   = (string) ($_GET['name'] ?? '');
    $domain = strtolower(trim((string) ($_GET['domain'] ?? '')));
    // Cheap local guard so obviously-bad input never costs an upstream call.
    if ($domain === '' || strlen($name) > 80 || strlen($domain) > 253) {
        $out(['status' => 'error', 'msg' => 'bad request']);
    }
    if (!preg_match('/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/', strtolower(trim($name)))) {
        $out(['status' => 'success', 'available' => false, 'state' => 'invalid', 'reason' => 'letters, digits, hyphens only']);
    }
    // Per-visitor session cache (TTL 60s) — repeated identical checks are free.
    if (session_status() === PHP_SESSION_NONE) @session_start();
    $key = md5(strtolower(trim($name)) . '|' . $domain);
    $hit = $_SESSION['puq_vanity_chk'][$key] ?? null;
    if (is_array($hit) && (time() - (int) ($hit['t'] ?? 0)) < 60) {
        echo json_encode($hit['r'], JSON_UNESCAPED_UNICODE); exit;
    }
    $r = $callWhmcs(['action' => 'check', 'name' => $name, 'domain' => $domain]);
    if (($r['status'] ?? '') === 'success') {
        $_SESSION['puq_vanity_chk'][$key] = ['t' => time(), 'r' => $r];
    }
    $out($r);
}

$out(['status' => 'error', 'msg' => 'unknown api'], 400);
