<?php
/**
 * WC Licensed Product API Client for PHP
 *
 * A simple PHP client for interacting with the WC Licensed Product REST API.
 *
 * Requirements:
 * - PHP 7.4+
 * - cURL extension
 *
 * Usage:
 *   $client = new WcLicensedProductClient('https://your-site.com');
 *   $result = $client->validate('XXXX-XXXX-XXXX-XXXX', 'example.com');
 */

class WcLicensedProductClient
{
    private string $baseUrl;
    private int $timeout;

    /**
     * Constructor
     *
     * @param string $siteUrl Your WordPress site URL (e.g., 'https://example.com')
     * @param int $timeout Request timeout in seconds
     */
    public function __construct(string $siteUrl, int $timeout = 30)
    {
        $this->baseUrl = rtrim($siteUrl, '/') . '/wp-json/wc-licensed-product/v1';
        $this->timeout = $timeout;
    }

    /**
     * Validate a license key for a specific domain
     *
     * @param string $licenseKey The license key to validate
     * @param string $domain The domain to validate against
     * @return array Response data
     * @throws Exception On request failure
     */
    public function validate(string $licenseKey, string $domain): array
    {
        return $this->request('/validate', [
            'license_key' => $licenseKey,
            'domain' => $domain,
        ]);
    }

    /**
     * Get the status of a license
     *
     * @param string $licenseKey The license key to check
     * @return array Response data with status, domain, expiration, etc.
     * @throws Exception On request failure
     */
    public function status(string $licenseKey): array
    {
        return $this->request('/status', [
            'license_key' => $licenseKey,
        ]);
    }

    /**
     * Activate a license on a domain
     *
     * @param string $licenseKey The license key to activate
     * @param string $domain The domain to activate on
     * @return array Response data
     * @throws Exception On request failure
     */
    public function activate(string $licenseKey, string $domain): array
    {
        return $this->request('/activate', [
            'license_key' => $licenseKey,
            'domain' => $domain,
        ]);
    }

    /**
     * Make an API request
     *
     * @param string $endpoint API endpoint path
     * @param array $data Request data
     * @return array Decoded response data
     * @throws Exception On request failure
     */
    private function request(string $endpoint, array $data): array
    {
        $url = $this->baseUrl . $endpoint;

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Accept: application/json',
            ],
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            throw new Exception('cURL error: ' . $error);
        }

        $decoded = json_decode($response, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON response: ' . json_last_error_msg());
        }

        // Add HTTP code to response for easier handling
        $decoded['_http_code'] = $httpCode;

        return $decoded;
    }
}

// =============================================================================
// Usage Examples
// =============================================================================

// Uncomment to run examples:

/*
$client = new WcLicensedProductClient('https://your-wordpress-site.com');

// Example 1: Validate a license
try {
    $result = $client->validate('XXXX-XXXX-XXXX-XXXX', 'myapp.example.com');

    if ($result['valid']) {
        echo "License is valid!\n";
        echo "Status: " . ($result['license']['status'] ?? 'active') . "\n";
        echo "Expires: " . ($result['license']['expires_at'] ?? 'Never') . "\n";
    } else {
        echo "License is not valid: " . ($result['message'] ?? 'Unknown error') . "\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

// Example 2: Check license status
try {
    $status = $client->status('XXXX-XXXX-XXXX-XXXX');

    echo "License Status:\n";
    echo "  Valid: " . ($status['valid'] ? 'Yes' : 'No') . "\n";
    echo "  Status: " . ($status['status'] ?? 'unknown') . "\n";
    echo "  Domain: " . ($status['domain'] ?? 'none') . "\n";
    echo "  Expires: " . ($status['expires_at'] ?? 'Never') . "\n";
    echo "  Activations: " . ($status['activations_count'] ?? 0) . "/" . ($status['max_activations'] ?? 1) . "\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

// Example 3: Activate license on a domain
try {
    $result = $client->activate('XXXX-XXXX-XXXX-XXXX', 'newsite.example.com');

    if ($result['success'] ?? false) {
        echo "License activated successfully!\n";
    } else {
        echo "Activation failed: " . ($result['message'] ?? 'Unknown error') . "\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

// Example 4: Handling rate limits
try {
    $result = $client->validate('XXXX-XXXX-XXXX-XXXX', 'example.com');

    if (($result['_http_code'] ?? 200) === 429) {
        $retryAfter = $result['retry_after'] ?? 60;
        echo "Rate limited. Retry after {$retryAfter} seconds.\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
*/
