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

/**
 * Faz 3A.1 — PW Trust License Verify v2 istemcisi.
 *
 * Bu sınıf mevcut lisans davranışını değiştirmez. Yalnızca paralel test
 * ekranı üzerinden yeni PW Trust → Trust2 doğrulama zincirini kontrol eder.
 */
final class PTMS_License_Client_V2 {
    private static $instance = null;
    private $page_slug = 'pw-merchant-api-system-lisans-guvenlik-testi';

    public static function instance() {
        if (self::$instance === null) { self::$instance = new self(); }
        return self::$instance;
    }

    private function __construct() {
        // Lisans Güvenlik Testi yönetim menüsünden kaldırıldı.
        // Trust2 doğrulama sınıfı ve güvenlik kapıları arka planda çalışmaya devam eder.
        add_action('admin_post_ptms_license_v2_test', array($this, 'handle_test'));
    }

    public function register_menu() {
        add_submenu_page(
            'pw-merchant-api-system',
            __('License Security Test', 'pw-merchant-api-system'),
            __('License Security Test', 'pw-merchant-api-system'),
            'manage_options',
            $this->page_slug,
            array($this, 'render_page')
        );
    }

    public function handle_test() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_license_v2_test');

        $result = self::verify();
        if (is_wp_error($result)) {
            set_transient('ptms_license_v2_test_result', array(
                'ok' => false,
                'error' => $result->get_error_message(),
            ), 5 * MINUTE_IN_SECONDS);
        } else {
            set_transient('ptms_license_v2_test_result', self::redact($result), 5 * MINUTE_IN_SECONDS);
        }

        wp_safe_redirect(admin_url('admin.php?page=' . $this->page_slug));
        exit;
    }

    /**
     * @return array|WP_Error
     */
    public static function verify() {
        $installation_id = trim((string) get_option('ptms_trust_installation_id', ''));

        if ($installation_id === '') {
            $refresh = PTMS_License::refresh(true);
            if (is_wp_error($refresh)) { return $refresh; }
            $installation_id = trim((string) get_option('ptms_trust_installation_id', ''));
        }

        if ($installation_id === '') {
            return new WP_Error('ptms_v2_installation_missing', __('Failed to create installation ID. First, renew the license status from the License screen.', 'pw-merchant-api-system'));
        }

        return PTMS_License::signed_request('license-verify-v2.php', array(
            'installation_id' => $installation_id,
        ));
    }

    /**
     * Gerçek özellik kapısı. Açık Feature Token saklanmaz; yalnızca karar kısa süreli cache edilir.
     *
     * @return true|WP_Error
     */
    public static function require_scope($scope, $force = false) {
        // sanitize_key() nokta karakterini kaldırdığı için scope adlarında kullanılamaz.
        // Yalnız küçük harf, rakam, nokta, alt çizgi ve tire kabul edilir.
        $scope = strtolower(trim((string) $scope));
        if (!preg_match('/^[a-z0-9._-]{3,64}$/', $scope)) {
            return new WP_Error('ptms_scope_invalid', __('Invalid feature authorization.', 'pw-merchant-api-system'));
        }

        $allowed = array('google.connect', 'merchant.send', 'merchant.bulk_send', 'merchant.sync');
        if (!in_array($scope, $allowed, true)) {
            return new WP_Error('ptms_scope_invalid', __('Invalid feature authorization.', 'pw-merchant-api-system'));
        }

        $cache_key = 'ptms_scope_gate_' . md5($scope . '|' . PTMS_Core::domain());
        if (!$force) {
            $cached = get_transient($cache_key);
            if (is_array($cached) && array_key_exists('allowed', $cached)) {
                return !empty($cached['allowed'])
                    ? true
                    : new WP_Error('ptms_scope_denied', (string)($cached['message'] ?? __('No valid license entitlements were found for this feature.', 'pw-merchant-api-system')));
            }
        }

        $result = self::verify();
        if (is_wp_error($result)) {
            return new WP_Error(
                'ptms_scope_service_unavailable',
                __('The license security service is currently unavailable. Your current connection and settings are preserved. Please try again soon.', 'pw-merchant-api-system')
            );
        }

        $authorized = !empty($result['authorized']);
        $scopes = isset($result['authorization']['scopes']) && is_array($result['authorization']['scopes'])
            ? array_map('strval', $result['authorization']['scopes'])
            : array();
        $allowed_scope = $authorized && in_array($scope, $scopes, true);

        $message = $allowed_scope
            ? ''
            : __('No valid license authorization was found for this operation. Refresh the license status and try again.', 'pw-merchant-api-system');

        set_transient($cache_key, array(
            'allowed' => $allowed_scope,
            'message' => $message,
            'decision_id' => sanitize_text_field((string)($result['decision_id'] ?? '')),
            'mode' => sanitize_key((string)($result['mode'] ?? ($result['cache']['source'] ?? ''))),
        ), 45);

        return $allowed_scope ? true : new WP_Error('ptms_scope_denied', $message);
    }

    private static function redact(array $result) {
        if (isset($result['authorization']) && is_array($result['authorization'])) {
            unset($result['authorization']['token']);
            $result['authorization']['token_redacted'] = true;
        }
        return $result;
    }

    private function badge_class($ok) {
        return $ok ? 'success' : 'danger';
    }

    public function render_page() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }

        $result = get_transient('ptms_license_v2_test_result');
        delete_transient('ptms_license_v2_test_result');

        $license = PTMS_License::display_data();
        $authorized = is_array($result) && !empty($result['authorized']);
        $mode = is_array($result) ? sanitize_key((string)($result['mode'] ?? '')) : '';
        if ($mode === '' && is_array($result)) {
            $mode = sanitize_key((string)($result['cache']['source'] ?? ''));
        }

        echo '<div class="wrap ptms-wrap"><div class="ptms-shell">';
        echo '<div class="ptms-topbar"><div class="ptms-heading"><div class="ptms-logo-box"><img src="' . esc_url(PTMS_URL . 'assets/img/pw-logo.jpg') . __('" alt="PW Feed"></div><div><div class="ptms-brand">PW Core Standard · PW Feed</div><h1>License Security Test</h1><p>PW Feed → PW Trust → Trust2 verifies the security chain without changing existing Merchant functions.</p></div></div><div class="ptms-top-actions"><span class="ptms-badge">v', 'pw-merchant-api-system') . esc_html(PTMS_VERSION) . '</span><span class="ptms-badge soft">' . esc_html(PTMS_License::label()) . '</span></div></div>';

        echo __('<div class="ptms-card"><h2>Phase 3A.1 — License Client v2</h2><p class="ptms-muted">This test only calls the new license verification service. Google link, product submission, Worker Engine, WooCommerce and existing license flow are not changed.</p>', 'pw-merchant-api-system');
        echo __('<dl class="ptms-details"><dt>Domain name</dt><dd>', 'pw-merchant-api-system') . esc_html(PTMS_Core::domain()) . __('</dd><dt>Installation ID</dt><dd><code>', 'pw-merchant-api-system') . esc_html((string)get_option('ptms_trust_installation_id', __('Not yet created', 'pw-merchant-api-system'))) . '</code></dd><dt>' . esc_html__('Current licence', 'pw-merchant-api-system') . '</dt><dd>' . esc_html((string)($license['type'] ?? '—')) . ' / ' . esc_html((string)($license['status'] ?? '—')) . '</dd></dl>';
        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_license_v2_test">';
        wp_nonce_field('ptms_license_v2_test');
        echo __('<button class="ptms-btn" type="submit">Test Secure License Verification</button></form></div>', 'pw-merchant-api-system');

        if (is_array($result)) {
            if (!empty($result['error'])) {
                echo __('<div class="ptms-alert danger"><strong>Test failed:</strong>', 'pw-merchant-api-system') . esc_html((string)$result['error']) . '</div>';
            } else {
                echo '<div class="ptms-grid four">';
                echo '<div class="ptms-card metric"><span>' . esc_html__('Authorization', 'pw-merchant-api-system') . '</span><strong class="' . esc_attr($authorized ? 'ok' : 'danger') . '">' . esc_html($authorized ? __('Authorized', 'pw-merchant-api-system') : __('Unauthorized', 'pw-merchant-api-system')) . '</strong></div>';
                echo '<div class="ptms-card metric"><span>' . esc_html__('Licence', 'pw-merchant-api-system') . '</span><strong>' . esc_html(strtoupper((string)($result['license']['type'] ?? '—'))) . '</strong></div>';
                echo '<div class="ptms-card metric"><span>' . esc_html__('Status', 'pw-merchant-api-system') . '</span><strong>' . esc_html(strtoupper((string)($result['license']['status'] ?? '—'))) . '</strong></div>';
                echo __('<div class="ptms-card metric"><span>Operating mode</span><strong>', 'pw-merchant-api-system') . esc_html(strtoupper($mode ?: 'ONLINE')) . '</strong></div>';
                echo '</div>';

                $scopes = isset($result['authorization']['scopes']) && is_array($result['authorization']['scopes']) ? $result['authorization']['scopes'] : array();
                echo __('<div class="ptms-card"><h2>Verification result</h2><p><strong>Decision ID:</strong> <code>', 'pw-merchant-api-system') . esc_html((string)($result['decision_id'] ?? '—')) . __('</code></p><p><strong>Feature Token:</strong> Not displayed for security reasons and not saved in the WordPress database.</p>', 'pw-merchant-api-system');
                if ($scopes) {
                    echo __('<h3>Authorized features</h3><ul>', 'pw-merchant-api-system');
                    foreach ($scopes as $scope) { echo '<li><code>' . esc_html((string)$scope) . '</code></li>'; }
                    echo '</ul>';
                }
                echo '<pre style="white-space:pre-wrap;overflow:auto;max-height:420px">' . esc_html(wp_json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) . '</pre></div>';
            }
        }

        echo '<div class="ptms-footer"><div class="ptms-footer-brand"><img src="' . esc_url(PTMS_URL . 'assets/img/pw-logo.jpg') . __('" alt="PW Feed"><div><strong>PW Feed, software, development.</strong><a href="https://www.pwfeed.com" target="_blank" rel="noopener">pwfeed.com</a></div></div><span>PW Core Standard + PW Design System</span></div>', 'pw-merchant-api-system');
        echo '</div></div>';
    }
}
