<?php
if (!defined('ABSPATH')) exit;

/** Thin HTTP client for the RecordGod /shop API — GET (transient-cached) + POST (bridge-key). */
class RG_API {

    static function base() {
        return rtrim(get_option('rg_base_url', 'https://recordgod.com'), '/');
    }

    /** GET /shop/<path>?args — decoded JSON or null. Cached in a transient for $ttl seconds (0 = no cache). */
    static function get($path, $args = [], $ttl = 120) {
        $url = self::base() . $path . ($args ? '?' . http_build_query($args) : '');
        $key = 'rg_' . md5($url);
        if ($ttl) {
            $hit = get_transient($key);
            if ($hit !== false) return $hit;
        }
        $r = wp_remote_get($url, ['timeout' => 12, 'headers' => ['Accept' => 'application/json']]);
        if (is_wp_error($r) || wp_remote_retrieve_response_code($r) !== 200) return null;
        $data = json_decode(wp_remote_retrieve_body($r), true);
        if ($ttl && $data !== null) set_transient($key, $data, $ttl);
        return $data;
    }

    /** POST JSON to /shop/<path> with the bridge key header. Returns [code, decoded-body]. */
    static function post($path, $body) {
        $r = wp_remote_post(self::base() . $path, [
            'timeout' => 15,
            'headers' => [
                'Content-Type' => 'application/json',
                'X-Bridge-Key' => get_option('rg_bridge_key', ''),
            ],
            'body' => wp_json_encode($body),
        ]);
        if (is_wp_error($r)) return [0, ['error' => $r->get_error_message()]];
        return [wp_remote_retrieve_response_code($r), json_decode(wp_remote_retrieve_body($r), true)];
    }
}
