﻿<?php

/**
 * Ovion Market WordPress license client template.
 *
 * Drop this into a plugin/theme package and instantiate it from the admin boot.
 * It caches checks daily and never hard-breaks public runtime output.
 */
class Ovion_Market_License_Client
{
    private string $api_base;
    private string $product_slug;
    private string $product_version;
    private string $option_key;

    public function __construct(string $api_base, string $product_slug, string $product_version)
    {
        $this->api_base = rtrim($api_base, '/');
        $this->product_slug = $product_slug;
        $this->product_version = $product_version;
        $this->option_key = 'ovion_license_'.$product_slug;
    }

    public function license_key(): string
    {
        return trim((string) get_option($this->option_key, ''));
    }

    public function save_license_key(string $license_key): void
    {
        update_option($this->option_key, sanitize_text_field($license_key), false);
        delete_transient($this->option_key.'_check');
    }

    public function activate(): array
    {
        return $this->post('/api/licenses/activate', $this->payload());
    }

    public function deactivate(): array
    {
        $response = $this->post('/api/licenses/deactivate', $this->payload());
        delete_transient($this->option_key.'_check');

        return $response;
    }

    public function check(bool $force = false): array
    {
        $cache_key = $this->option_key.'_check';
        if (! $force) {
            $cached = get_transient($cache_key);
            if (is_array($cached)) {
                return $cached;
            }
        }

        $response = $this->post('/api/licenses/check', $this->payload());
        set_transient($cache_key, $response, DAY_IN_SECONDS);

        return $response;
    }

    public function update_check(): array
    {
        return $this->post('/api/licenses/update-check', $this->payload());
    }

    private function payload(): array
    {
        return [
            'license_key' => $this->license_key(),
            'product_slug' => $this->product_slug,
            'product_version' => $this->product_version,
            'site_url' => home_url('/'),
            'domain' => wp_parse_url(home_url('/'), PHP_URL_HOST),
            'installation_uuid' => $this->installation_uuid(),
            'environment' => wp_get_environment_type(),
            'client' => 'wordpress',
        ];
    }

    private function installation_uuid(): string
    {
        $key = $this->option_key.'_installation_uuid';
        $uuid = (string) get_option($key, '');
        if ($uuid === '') {
            $uuid = wp_generate_uuid4();
            update_option($key, $uuid, false);
        }

        return $uuid;
    }

    private function post(string $path, array $payload): array
    {
        if ($payload['license_key'] === '') {
            return ['valid' => false, 'status' => 'missing', 'message' => 'Enter a license key.'];
        }

        $response = wp_remote_post($this->api_base.$path, [
            'timeout' => 15,
            'headers' => ['Accept' => 'application/json'],
            'body' => $payload,
        ]);

        if (is_wp_error($response)) {
            return ['valid' => false, 'status' => 'unreachable', 'message' => $response->get_error_message()];
        }

        $body = json_decode((string) wp_remote_retrieve_body($response), true);

        return is_array($body) ? $body : ['valid' => false, 'status' => 'invalid_response', 'message' => 'Invalid license server response.'];
    }
}
