<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Admin;

use APD\Support\Capabilities;
use APD\Support\CommercialRuntimeConfig;
use APD\Support\RequestData;

defined('ABSPATH') || exit;

final class SupportPage
{
    private const PAGE_SLUG = 'apd-support';

    public function __construct(private readonly CommercialRuntimeConfig $commercialRuntimeConfig)
    {
    }

    public function render() : void
    {
        if (! current_user_can(Capabilities::MANAGE)) {
            wp_die(esc_html__('You are not allowed to access this page.', 'asuka-product-designer'));
        }

        $settings = (new AdminSettings())->all();
        $runtime = $this->commercialRuntimeConfig->build($settings);
        $license = is_array($runtime['license'] ?? null) ? $runtime['license'] : [];
        $entitlements = $this->commercialRuntimeConfig->entitlementsFromLicense($license);
        $plan = sanitize_key((string) ($entitlements['plan'] ?? 'free')) ?: 'free';
        $tokenAvailable = trim((string) ($license['token'] ?? '')) !== '';
        $licenseConfigured = ! empty($license['configured']);
        $eligible = $tokenAvailable && $this->isSupportPlan($plan);
        $theme = sanitize_html_class((string) ($settings['admin_theme'] ?? 'light'));
        $query = RequestData::query();
        $error = sanitize_key((string) ($query['apd_support_error'] ?? ''));
        $planLabel = $this->planLabel($plan);
        ?>
        <div class="wrap apd-admin-shell apd-admin-theme-<?php echo esc_attr($theme); ?> apd-support-center">
            <header class="apd-workspace-header">
                <div>
                    <span class="apd-dashboard-eyebrow"><?php esc_html_e('Customer care', 'asuka-product-designer'); ?></span>
                    <h1><?php esc_html_e('Support center', 'asuka-product-designer'); ?></h1>
                    <p><?php esc_html_e('Open a tracked request with your WordPress site, plugin version, domain, and license context attached automatically.', 'asuka-product-designer'); ?></p>
                </div>
                <div class="apd-support-center__header-actions">
                    <a class="button button-secondary" href="https://portal.asukadev.com/documentation/wordpress" target="_blank" rel="noreferrer">
                        <?php esc_html_e('Browse the WordPress guide', 'asuka-product-designer'); ?>
                    </a>
                </div>
            </header>

            <?php if ($error !== '') : ?>
                <div class="notice notice-error is-dismissible"><p><?php echo esc_html($this->errorMessage($error)); ?></p></div>
            <?php endif; ?>

            <section class="apd-support-access is-<?php echo esc_attr($eligible ? 'active' : ($licenseConfigured ? 'unavailable' : 'locked')); ?>" aria-labelledby="apd-support-access-title">
                <div class="apd-support-access__status" aria-hidden="true">
                    <span><?php echo esc_html($eligible ? __('Active', 'asuka-product-designer') : __('Starter+', 'asuka-product-designer')); ?></span>
                </div>
                <div class="apd-support-access__copy">
                    <span class="apd-dashboard-eyebrow"><?php echo esc_html($planLabel); ?></span>
                    <h2 id="apd-support-access-title">
                        <?php
                        echo esc_html(
                            $eligible
                                ? __('Tracked technical support is included with your plan.', 'asuka-product-designer')
                                : __('Technical support is available from the Starter plan.', 'asuka-product-designer')
                        );
                        ?>
                    </h2>
                    <p>
                        <?php
                        if ($eligible) {
                            esc_html_e('The secure button signs you into the portal for this exact customer. Your license key is never placed in the URL or exposed to the browser.', 'asuka-product-designer');
                        } elseif ($licenseConfigured) {
                            esc_html_e('The current license could not be confirmed as an active Starter, Pro, or Agency plan. Check the license connection, then try again.', 'asuka-product-designer');
                        } else {
                            esc_html_e('Connect a paid license in Settings to create technical requests. Documentation, sales, privacy, and security contacts remain available to everyone.', 'asuka-product-designer');
                        }
                        ?>
                    </p>
                </div>
                <div class="apd-support-access__action">
                    <?php if ($eligible) : ?>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                            <input type="hidden" name="action" value="apd_open_support_center">
                            <?php wp_nonce_field('apd_open_support_center'); ?>
                            <button class="button button-primary" type="submit"><?php esc_html_e('Open secure support center', 'asuka-product-designer'); ?></button>
                        </form>
                        <small><?php esc_html_e('The access link is single-use and expires automatically.', 'asuka-product-designer'); ?></small>
                    <?php elseif ($licenseConfigured) : ?>
                        <a class="button button-primary" href="<?php echo esc_url(admin_url('admin.php?page=apd-settings')); ?>"><?php esc_html_e('Check license settings', 'asuka-product-designer'); ?></a>
                    <?php else : ?>
                        <a class="button button-primary" href="https://portal.asukadev.com/pricing" target="_blank" rel="noreferrer"><?php esc_html_e('Compare support plans', 'asuka-product-designer'); ?></a>
                    <?php endif; ?>
                </div>
            </section>

            <section class="apd-support-options" aria-label="<?php echo esc_attr__('Support options', 'asuka-product-designer'); ?>">
                <article>
                    <span>01</span>
                    <div>
                        <h2><?php esc_html_e('Technical support', 'asuka-product-designer'); ?></h2>
                        <p><?php esc_html_e('Designer loading, product setup, WooCommerce, pricing, exports, assets, or unexpected behavior.', 'asuka-product-designer'); ?></p>
                    </div>
                </article>
                <article>
                    <span>02</span>
                    <div>
                        <h2><?php esc_html_e('Tracked history', 'asuka-product-designer'); ?></h2>
                        <p><?php esc_html_e('Read replies, keep attachments together, and retain existing requests even if a paid plan later expires.', 'asuka-product-designer'); ?></p>
                    </div>
                </article>
                <article>
                    <span>03</span>
                    <div>
                        <h2><?php esc_html_e('Useful diagnostics', 'asuka-product-designer'); ?></h2>
                        <p><?php esc_html_e('Run the built-in checks first so support receives the shortest path to a reliable answer.', 'asuka-product-designer'); ?></p>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=apd-qa-diagnostics')); ?>"><?php esc_html_e('Open QA & Diagnostics', 'asuka-product-designer'); ?></a>
                    </div>
                </article>
            </section>

            <section class="apd-support-public-contact">
                <div>
                    <span class="dashicons dashicons-shield" aria-hidden="true"></span>
                    <div>
                        <h2><?php esc_html_e('Need help before subscribing?', 'asuka-product-designer'); ?></h2>
                        <p><?php esc_html_e('Sales, billing, licensing, privacy, and private security reports remain available without a paid support entitlement.', 'asuka-product-designer'); ?></p>
                    </div>
                </div>
                <div>
                    <a class="button button-secondary" href="https://portal.asukadev.com/contact" target="_blank" rel="noreferrer"><?php esc_html_e('Contact Asuka Designer', 'asuka-product-designer'); ?></a>
                    <a class="button button-secondary" href="mailto:security@asukadev.com"><?php esc_html_e('Report a security issue', 'asuka-product-designer'); ?></a>
                </div>
            </section>
        </div>
        <?php
    }

    public function open() : void
    {
        if (! current_user_can(Capabilities::MANAGE)) {
            wp_die(esc_html__('You are not allowed to open the support center.', 'asuka-product-designer'));
        }

        check_admin_referer('apd_open_support_center');

        $runtime = $this->commercialRuntimeConfig->build();
        $license = is_array($runtime['license'] ?? null) ? $runtime['license'] : [];
        $token = trim((string) ($license['token'] ?? ''));
        if ($token === '') {
            $this->redirectWithError('license_unavailable');
        }

        $body = [
            'product' => 'asuka-designer',
            'audience' => (string) ($license['audience'] ?? 'asuka-designer'),
            'channel' => 'wordpress',
            'domain' => (string) ($license['domain'] ?? ''),
            'instanceId' => (string) ($license['instanceId'] ?? ''),
            'version' => ASUKA_PRODUCT_DESIGNER_VERSION,
        ];
        $response = wp_safe_remote_post(
            $this->commercialRuntimeConfig->apiBaseUrl() . '/v1/support/wordpress/access',
            [
                'timeout' => 15,
                'redirection' => 0,
                'headers' => [
                    'Authorization' => 'Bearer ' . $token,
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                ],
                'body' => wp_json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            ]
        );

        if (is_wp_error($response)) {
            $this->redirectWithError('service_unavailable');
        }

        $status = (int) wp_remote_retrieve_response_code($response);
        $payload = json_decode((string) wp_remote_retrieve_body($response), true);
        if ($status === 403) {
            $this->redirectWithError('starter_required');
        }
        if ($status < 200 || $status >= 300 || ! is_array($payload)) {
            $this->redirectWithError('service_unavailable');
        }

        $accessUrl = trim((string) ($payload['accessUrl'] ?? ''));
        if (! $this->isTrustedSupportUrl($accessUrl)) {
            $this->redirectWithError('invalid_response');
        }

        wp_redirect($accessUrl); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- The URL is restricted to the exact HTTPS support host above.
        exit;
    }

    private function isSupportPlan(string $plan) : bool
    {
        return in_array($plan, ['starter', 'starter-monthly', 'pro', 'pro-monthly', 'agency', 'agency-yearly'], true);
    }

    private function planLabel(string $plan) : string
    {
        return match ($plan) {
            'starter', 'starter-monthly' => __('Starter plan', 'asuka-product-designer'),
            'pro', 'pro-monthly' => __('Pro plan', 'asuka-product-designer'),
            'agency', 'agency-yearly' => __('Agency plan', 'asuka-product-designer'),
            default => __('Free or unverified plan', 'asuka-product-designer'),
        };
    }

    private function errorMessage(string $error) : string
    {
        return match ($error) {
            'starter_required' => __('An active Starter, Pro, or Agency license is required to open a new technical support request.', 'asuka-product-designer'),
            'license_unavailable' => __('The license token is unavailable. Check the license settings and try again.', 'asuka-product-designer'),
            'invalid_response' => __('The support service returned an invalid access link. No redirect was performed.', 'asuka-product-designer'),
            default => __('The support service is temporarily unavailable. Please try again shortly.', 'asuka-product-designer'),
        };
    }

    private function isTrustedSupportUrl(string $url) : bool
    {
        if ($url === '') {
            return false;
        }

        $scheme = strtolower((string) wp_parse_url($url, PHP_URL_SCHEME));
        $host = strtolower((string) wp_parse_url($url, PHP_URL_HOST));
        $port = wp_parse_url($url, PHP_URL_PORT);
        $user = (string) wp_parse_url($url, PHP_URL_USER);
        $pass = (string) wp_parse_url($url, PHP_URL_PASS);
        $path = (string) wp_parse_url($url, PHP_URL_PATH);
        $query = (string) wp_parse_url($url, PHP_URL_QUERY);
        $fragment = (string) wp_parse_url($url, PHP_URL_FRAGMENT);

        return $scheme === 'https'
            && $host === 'portal.asukadev.com'
            && ($port === false || $port === null || (int) $port === 443)
            && $user === ''
            && $pass === ''
            && $query === ''
            && $fragment === ''
            && preg_match('#^/support/access/[A-Za-z0-9_-]{20,}/?$#', $path) === 1;
    }

    private function redirectWithError(string $error) : never
    {
        wp_safe_redirect(add_query_arg('apd_support_error', sanitize_key($error), admin_url('admin.php?page=' . self::PAGE_SLUG)));
        exit;
    }
}
