<?php

namespace Licenzo\Modules\EDD;

use Licenzo\Model\Product;
use Licenzo\Model\ProductVariation;
use Licenzo\Services\Integrations\ProviderAliasService;

if (!defined('ABSPATH')) {
    exit;
}

class EddProductMappingService
{
    const NONCE_ACTION = 'licenzo_edd_product_mapping_save';
    const NONCE_NAME = 'licenzo_edd_product_mapping_nonce';

    const META_ENABLE_SYNC = '_licenzo_sync_enabled';
    const META_LICENZO_PRODUCT_ID = '_licenzo_product_id';
    const META_LICENZO_PRODUCT_STATUS = '_licenzo_product_status';
    const META_LICENZO_PRODUCT_LINK = '_licenzo_product_link';
    const META_DEFAULT_CYCLE = '_licenzo_default_cycle';
    const META_DEFAULT_MAX_ACTIVATIONS = '_licenzo_default_max_activations';
    const META_DEFAULT_TRIAL_DAYS = '_licenzo_default_trial_days';
    const META_DEFAULT_SUPPORT_FOR = '_licenzo_default_support_for';
    const META_DEFAULT_SUPPORT_UNIT = '_licenzo_default_support_unit';

    const META_LAST_SYNC_STATUS = '_licenzo_last_sync_status';
    const META_LAST_SYNC_MESSAGE = '_licenzo_last_sync_message';
    const META_LAST_SYNC_AT = '_licenzo_last_sync_at';

    public function register(): void
    {
        if (!is_admin()) {
            return;
        }

        add_action('add_meta_boxes', [$this, 'addMetaBox']);
        add_action('save_post_download', [$this, 'saveMapping'], 100, 2);
    }

    public function addMetaBox(): void
    {
        add_meta_box(
            'licenzo_edd_product_mapping',
            __('Licenzo Product Mapping', 'licenzo'),
            [$this, 'renderMetaBox'],
            'download',
            'normal',
            'high'
        );
    }

    public function renderMetaBox($post): void
    {
        $downloadId = (int) $post->ID;
        $syncEnabled = get_post_meta($downloadId, static::META_ENABLE_SYNC, true);
        $isSyncEnabled = in_array($syncEnabled, ['1', 'yes', 1, true], true);

        $linkedProduct = $this->findLinkedLicenzoProduct($downloadId);
        $hasVariablePricing = edd_has_variable_prices($downloadId);
        $eddPrices = $hasVariablePricing && edd_get_variable_prices($downloadId) ?: [];

        wp_nonce_field(static::NONCE_ACTION, static::NONCE_NAME);

        $this->renderSyncToggle($isSyncEnabled);

        echo '<div id="licenzo-edd-mapping-fields" style="' . ($isSyncEnabled ? '' : 'display:none;') . '">';

        $this->renderSyncStatus($downloadId, $linkedProduct);
        $this->renderDefaultFields($downloadId);

        if ($hasVariablePricing && !empty($eddPrices)) {
            $this->renderVariablePricingMappings($downloadId, $eddPrices, $linkedProduct);
        }

        echo '</div>';

        $this->renderInlineScript();
    }

    public function saveMapping($postId, $post): void
    {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (!current_user_can('edit_post', $postId)) {
            return;
        }

        $hasLicenzoNonce = isset($_POST[static::NONCE_NAME])
            && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST[static::NONCE_NAME])), static::NONCE_ACTION);

        if ($hasLicenzoNonce) {
            $syncEnabled = isset($_POST['licenzo_sync_enabled']) ? '1' : '0';
            update_post_meta($postId, static::META_ENABLE_SYNC, $syncEnabled);

            if ($syncEnabled !== '1') {
                update_post_meta($postId, static::META_LAST_SYNC_STATUS, 'disabled');
                update_post_meta($postId, static::META_LAST_SYNC_MESSAGE, __('Sync is disabled.', 'licenzo'));
                return;
            }

            $defaults = $this->sanitizeDefaults($_POST);
            foreach ($defaults as $metaKey => $metaValue) {
                update_post_meta($postId, $metaKey, $metaValue);
            }

            if (isset($_POST['licenzo_product_link'])) {
                $link = esc_url_raw(wp_unslash($_POST['licenzo_product_link']));
                if (!empty($link)) {
                    update_post_meta($postId, static::META_LICENZO_PRODUCT_LINK, $link);
                }
            }
        }

        if (!$this->isSyncEnabled($postId)) {
            return;
        }

        if (!$this->findLinkedLicenzoProduct($postId)) {
            if (!$hasLicenzoNonce) {
                return;
            }
        }

        $defaults = $this->getStoredDefaults($postId);

        try {
            $this->syncProduct($postId, $post, $defaults, $hasLicenzoNonce);
        } catch (\Throwable $e) {
            update_post_meta($postId, static::META_LAST_SYNC_STATUS, 'error');
            update_post_meta($postId, static::META_LAST_SYNC_MESSAGE, $e->getMessage());
            update_post_meta($postId, static::META_LAST_SYNC_AT, gmdate('Y-m-d H:i:s'));
        }
    }

    private function isSyncEnabled(int $postId): bool
    {
        return in_array(get_post_meta($postId, static::META_ENABLE_SYNC, true), ['1', 'yes', 1, true], true);
    }

    private function getStoredDefaults(int $postId): array
    {
        $allowedCycles = ['onetime', 'lifetime', 'weekly', 'monthly', 'yearly'];
        $allowedUnits = ['day', 'week', 'month', 'year'];

        $cycle = get_post_meta($postId, static::META_DEFAULT_CYCLE, true) ?: 'monthly';
        $supportUnit = get_post_meta($postId, static::META_DEFAULT_SUPPORT_UNIT, true) ?: 'year';

        return [
            static::META_DEFAULT_CYCLE            => in_array($cycle, $allowedCycles, true) ? $cycle : 'monthly',
            static::META_DEFAULT_MAX_ACTIVATIONS  => max(1, (int) (get_post_meta($postId, static::META_DEFAULT_MAX_ACTIVATIONS, true) ?: 1)),
            static::META_DEFAULT_TRIAL_DAYS       => max(0, (int) get_post_meta($postId, static::META_DEFAULT_TRIAL_DAYS, true)),
            static::META_DEFAULT_SUPPORT_FOR      => max(0, (int) (get_post_meta($postId, static::META_DEFAULT_SUPPORT_FOR, true) ?: 1)),
            static::META_DEFAULT_SUPPORT_UNIT     => in_array($supportUnit, $allowedUnits, true) ? $supportUnit : 'year',
        ];
    }

    private function syncProduct(int $downloadId, $post, array $defaults, bool $hasPostOverrides): void
    {
        $productName = get_the_title($downloadId);
        $storedLink = get_post_meta($downloadId, static::META_LICENZO_PRODUCT_LINK, true);
        $productLink = !empty($storedLink) ? esc_url_raw($storedLink) : get_permalink($downloadId);

        $product = $this->findLinkedLicenzoProduct($downloadId);

        if (!$product) {
            $product = Product::create([
                'uuid'         => wp_generate_uuid4(),
                'name'         => $productName,
                'slug'         => sanitize_title($productName),
                'type'         => $this->hasVariablePricing($downloadId) ? Product::TYPE_VARIATION : Product::TYPE_SINGLE,
                'status'       => Product::STATUS_ACTIVE,
                'provider'     => Product::PROVIDER_EDD,
                'provider_id'  => (string) $downloadId,
                'product_link' => $productLink,
            ]);
        } else {
            $product->name = $productName;
            $product->product_link = $productLink;
            $product->type = $this->hasVariablePricing($downloadId) ? Product::TYPE_VARIATION : Product::TYPE_SINGLE;
            $product->save();
        }

        update_post_meta($downloadId, static::META_LICENZO_PRODUCT_ID, $product->id);
        update_post_meta($downloadId, static::META_LICENZO_PRODUCT_STATUS, $product->status);
        update_post_meta($downloadId, static::META_LICENZO_PRODUCT_LINK, $productLink);

        $this->syncVariations($downloadId, $product, $defaults, $hasPostOverrides);

        update_post_meta($downloadId, static::META_LAST_SYNC_STATUS, 'success');
        update_post_meta($downloadId, static::META_LAST_SYNC_MESSAGE, __('Synced successfully.', 'licenzo'));
        update_post_meta($downloadId, static::META_LAST_SYNC_AT, gmdate('Y-m-d H:i:s'));
    }

    private function syncVariations(int $downloadId, Product $product, array $defaults, bool $hasPostOverrides): void
    {
        $hasVariablePricing = $this->hasVariablePricing($downloadId);
        $eddPrices = $hasVariablePricing && edd_get_variable_prices($downloadId) ?: [];

        if ($hasVariablePricing && !empty($eddPrices)) {
            $processedPriceIds = [];

            foreach ($eddPrices as $priceId => $priceOption) {
                $priceId = (int) $priceId;
                $processedPriceIds[] = (string) $priceId;

                $amount = isset($priceOption['amount']) ? (float) $priceOption['amount'] : 0;
                $variationName = isset($priceOption['name']) ? sanitize_text_field($priceOption['name']) : "Price Option {$priceId}";

                $variation = ProductVariation::where('product_id', $product->id)
                    ->where('provider_id', (string) $priceId)
                    ->first();

                $resolved = $this->resolveVariationSettings($priceId, $variation, $defaults, $hasPostOverrides);

                $variationData = [
                    'product_id'       => $product->id,
                    'name'             => $variationName,
                    'provider_id'      => (string) $priceId,
                    'regular_price'    => $amount,
                    'sale_price'       => null,
                    'billing_cycle'    => $resolved['cycle'],
                    'max_activations'  => $resolved['max_activations'],
                    'trial_days'       => $resolved['trial_days'],
                    'support_for'      => $resolved['support_for'],
                    'support_for_unit' => $resolved['support_unit'],
                ];

                if ($variation) {
                    $variation->fill($variationData);
                    $variation->save();
                } else {
                    $variationData['uuid'] = wp_generate_uuid4();
                    ProductVariation::create($variationData);
                }
            }

            ProductVariation::where('product_id', $product->id)
                ->whereNotIn('provider_id', $processedPriceIds)
                ->delete();
        } else {
            $eddPrice = (float) edd_get_download_price($downloadId) ?: 0;
            $variation = ProductVariation::where('product_id', $product->id)->first();

            $resolved = $this->resolveVariationSettings(null, $variation, $defaults, $hasPostOverrides);

            $variationData = [
                'product_id'       => $product->id,
                'name'             => $product->name,
                'provider_id'      => (string) $downloadId,
                'regular_price'    => $eddPrice,
                'sale_price'       => null,
                'billing_cycle'    => $resolved['cycle'],
                'max_activations'  => $resolved['max_activations'],
                'trial_days'       => $resolved['trial_days'],
                'support_for'      => $resolved['support_for'],
                'support_for_unit' => $resolved['support_unit'],
            ];

            if ($variation) {
                $variation->fill($variationData);
                $variation->save();
            } else {
                $variationData['uuid'] = wp_generate_uuid4();
                $variation = ProductVariation::create($variationData);
            }

            ProductVariation::where('product_id', $product->id)
                ->where('id', '!=', $variation->id)
                ->delete();
        }
    }

    /**
     * Resolve variation licence settings with 3-tier fallback:
     *   1. $_POST overrides (only when Licenzo meta box submitted)
     *   2. Existing stored variation (preserves previous config on non-Licenzo saves)
     *   3. Stored defaults from post_meta
     */
    private function resolveVariationSettings(
        ?int $priceId,
        ?ProductVariation $existing,
        array $defaults,
        bool $hasPostOverrides
    ): array {
        if ($hasPostOverrides && $priceId !== null) {
            $post = $this->getVariationOverridesFromPost($priceId);
            return [
                'cycle'           => $post['cycle'] ?: ($existing->billing_cycle ?? $defaults[static::META_DEFAULT_CYCLE] ?? 'monthly'),
                'max_activations' => $post['max_activations'] !== '' ? (int) $post['max_activations'] : ($existing->max_activations ?? (int) ($defaults[static::META_DEFAULT_MAX_ACTIVATIONS] ?? 1)),
                'trial_days'      => $post['trial_days'] !== '' ? (int) $post['trial_days'] : ($existing->trial_days ?? (int) ($defaults[static::META_DEFAULT_TRIAL_DAYS] ?? 0)),
                'support_for'     => $post['support_for'] !== '' ? (int) $post['support_for'] : ($existing->support_for ?? (int) ($defaults[static::META_DEFAULT_SUPPORT_FOR] ?? 1)),
                'support_unit'    => $post['support_unit'] ?: ($existing->support_for_unit ?? $defaults[static::META_DEFAULT_SUPPORT_UNIT] ?? 'year'),
            ];
        }

        if ($existing) {
            return [
                'cycle'           => $existing->billing_cycle ?? $defaults[static::META_DEFAULT_CYCLE] ?? 'monthly',
                'max_activations' => $existing->max_activations ?? (int) ($defaults[static::META_DEFAULT_MAX_ACTIVATIONS] ?? 1),
                'trial_days'      => $existing->trial_days ?? (int) ($defaults[static::META_DEFAULT_TRIAL_DAYS] ?? 0),
                'support_for'     => $existing->support_for ?? (int) ($defaults[static::META_DEFAULT_SUPPORT_FOR] ?? 1),
                'support_unit'    => $existing->support_for_unit ?? $defaults[static::META_DEFAULT_SUPPORT_UNIT] ?? 'year',
            ];
        }

        return [
            'cycle'           => $defaults[static::META_DEFAULT_CYCLE] ?? 'monthly',
            'max_activations' => (int) ($defaults[static::META_DEFAULT_MAX_ACTIVATIONS] ?? 1),
            'trial_days'      => (int) ($defaults[static::META_DEFAULT_TRIAL_DAYS] ?? 0),
            'support_for'     => (int) ($defaults[static::META_DEFAULT_SUPPORT_FOR] ?? 1),
            'support_unit'    => $defaults[static::META_DEFAULT_SUPPORT_UNIT] ?? 'year',
        ];
    }

    private function findLinkedLicenzoProduct(int $downloadId): ?Product
    {
        return Product::whereIn('provider', ProviderAliasService::eddAliases())
            ->where('provider_id', (string) $downloadId)
            ->with('variations')
            ->first();
    }

    private function hasVariablePricing(int $downloadId): bool
    {
        return edd_has_variable_prices($downloadId);
    }

    private function sanitizeDefaults(array $post): array
    {
        $allowedCycles = ['onetime', 'lifetime', 'weekly', 'monthly', 'yearly'];
        $allowedUnits = ['day', 'week', 'month', 'year'];

        $cycle = isset($post['licenzo_default_cycle']) ? sanitize_key($post['licenzo_default_cycle']) : 'monthly';
        $supportUnit = isset($post['licenzo_default_support_unit']) ? sanitize_key($post['licenzo_default_support_unit']) : 'year';

        return [
            static::META_DEFAULT_CYCLE => in_array($cycle, $allowedCycles, true) ? $cycle : 'monthly',
            static::META_DEFAULT_MAX_ACTIVATIONS => max(1, (int) ($post['licenzo_default_max_activations'] ?? 1)),
            static::META_DEFAULT_TRIAL_DAYS => max(0, (int) ($post['licenzo_default_trial_days'] ?? 0)),
            static::META_DEFAULT_SUPPORT_FOR => max(0, (int) ($post['licenzo_default_support_for'] ?? 1)),
            static::META_DEFAULT_SUPPORT_UNIT => in_array($supportUnit, $allowedUnits, true) ? $supportUnit : 'year',
        ];
    }

    private function getVariationOverridesFromPost(int $priceId): array
    {
        $prefix = 'licenzo_variation_' . $priceId . '_';

        // Nonce verified in saveMapping() before this method is called.
        return [
            'cycle'           => isset($_POST[$prefix . 'cycle']) ? sanitize_key(wp_unslash($_POST[$prefix . 'cycle'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
            'max_activations' => isset($_POST[$prefix . 'max_activations']) ? sanitize_text_field(wp_unslash($_POST[$prefix . 'max_activations'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
            'trial_days'      => isset($_POST[$prefix . 'trial_days']) ? sanitize_text_field(wp_unslash($_POST[$prefix . 'trial_days'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
            'support_for'     => isset($_POST[$prefix . 'support_for']) ? sanitize_text_field(wp_unslash($_POST[$prefix . 'support_for'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
            'support_unit'    => isset($_POST[$prefix . 'support_unit']) ? sanitize_key(wp_unslash($_POST[$prefix . 'support_unit'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
        ];
    }

    private function renderSyncToggle(bool $isSyncEnabled): void
    {
        echo '<p>';
        echo '<label>';
        echo '<input type="checkbox" name="licenzo_sync_enabled" value="1" ' . checked($isSyncEnabled, true, false) . ' />';
        echo ' ' . esc_html__('Enable Licenzo sync for this download', 'licenzo');
        echo '</label>';
        echo '</p>';
    }

    private function renderSyncStatus(int $downloadId, ?Product $linkedProduct): void
    {
        $lastStatus = get_post_meta($downloadId, static::META_LAST_SYNC_STATUS, true);
        $lastMessage = get_post_meta($downloadId, static::META_LAST_SYNC_MESSAGE, true);
        $lastAt = get_post_meta($downloadId, static::META_LAST_SYNC_AT, true);

        if ($linkedProduct) {
            echo '<div class="licenzo-sync-status" style="background:#f0fdf4;border:1px solid #bbf7d0;padding:8px 12px;margin:10px 0;border-radius:4px;">';
            echo '<strong>' . esc_html__('Linked to Licenzo Product:', 'licenzo') . '</strong> ';
            echo esc_html($linkedProduct->name) . ' <code>(ID: ' . esc_html($linkedProduct->id) . ')</code>';
            if ($lastAt) {
                echo '<br><small>' . esc_html__('Last synced:', 'licenzo') . ' ' . esc_html($lastAt) . '</small>';
            }
            echo '</div>';
        } elseif ($lastStatus === 'error') {
            echo '<div class="licenzo-sync-status" style="background:#fef2f2;border:1px solid #fecaca;padding:8px 12px;margin:10px 0;border-radius:4px;">';
            echo '<strong>' . esc_html__('Sync error:', 'licenzo') . '</strong> ' . esc_html($lastMessage);
            echo '</div>';
        } else {
            echo '<div class="licenzo-sync-status" style="background:#eff6ff;border:1px solid #bfdbfe;padding:8px 12px;margin:10px 0;border-radius:4px;">';
            echo esc_html__('A Licenzo product will be created when you save this download.', 'licenzo');
            echo '</div>';
        }
    }

    private function renderDefaultFields(int $downloadId): void
    {
        $allowedCycles = [
            'onetime'  => __('One-time', 'licenzo'),
            'lifetime' => __('Lifetime', 'licenzo'),
            'weekly'   => __('Weekly', 'licenzo'),
            'monthly'  => __('Monthly', 'licenzo'),
            'yearly'   => __('Yearly', 'licenzo'),
        ];
        $allowedUnits = [
            'day'   => __('Day(s)', 'licenzo'),
            'week'  => __('Week(s)', 'licenzo'),
            'month' => __('Month(s)', 'licenzo'),
            'year'  => __('Year(s)', 'licenzo'),
        ];

        $cycle = get_post_meta($downloadId, static::META_DEFAULT_CYCLE, true) ?: 'monthly';
        $maxActivations = (int) (get_post_meta($downloadId, static::META_DEFAULT_MAX_ACTIVATIONS, true) ?: 1);
        $trialDays = (int) get_post_meta($downloadId, static::META_DEFAULT_TRIAL_DAYS, true);
        $supportFor = (int) (get_post_meta($downloadId, static::META_DEFAULT_SUPPORT_FOR, true) ?: 1);
        $supportUnit = get_post_meta($downloadId, static::META_DEFAULT_SUPPORT_UNIT, true) ?: 'year';
        $productLink = get_post_meta($downloadId, static::META_LICENZO_PRODUCT_LINK, true) ?: get_permalink($downloadId);

        echo '<h4 style="margin:15px 0 8px;">' . esc_html__('Default License Settings', 'licenzo') . '</h4>';
        echo '<table class="form-table licenzo-edd-defaults"><tbody>';

        echo '<tr><th><label>' . esc_html__('Billing Cycle', 'licenzo') . '</label></th><td>';
        echo '<select name="licenzo_default_cycle">';
        foreach ($allowedCycles as $value => $label) {
            echo '<option value="' . esc_attr($value) . '"' . selected($cycle, $value, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';

        echo '<tr><th><label>' . esc_html__('Max Activations', 'licenzo') . '</label></th><td>';
        echo '<input type="number" name="licenzo_default_max_activations" value="' . esc_attr($maxActivations) . '" min="1" step="1" style="width:80px;" />';
        echo '</td></tr>';

        echo '<tr><th><label>' . esc_html__('Trial Days', 'licenzo') . '</label></th><td>';
        echo '<input type="number" name="licenzo_default_trial_days" value="' . esc_attr($trialDays) . '" min="0" step="1" style="width:80px;" />';
        echo '</td></tr>';

        echo '<tr><th><label>' . esc_html__('Support Duration', 'licenzo') . '</label></th><td>';
        echo '<input type="number" name="licenzo_default_support_for" value="' . esc_attr($supportFor) . '" min="0" step="1" style="width:80px;margin-right:4px;" />';
        echo '<select name="licenzo_default_support_unit">';
        foreach ($allowedUnits as $value => $label) {
            echo '<option value="' . esc_attr($value) . '"' . selected($supportUnit, $value, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';

        echo '<tr><th><label>' . esc_html__('Product Link', 'licenzo') . '</label></th><td>';
        echo '<input type="url" name="licenzo_product_link" value="' . esc_attr($productLink) . '" class="regular-text" />';
        echo '</td></tr>';

        echo '</tbody></table>';
    }

    private function renderVariablePricingMappings(int $downloadId, array $eddPrices, ?Product $linkedProduct): void
    {
        echo '<h4 style="margin:15px 0 8px;">' . esc_html__('Price Option Overrides', 'licenzo') . '</h4>';
        echo '<p class="description">' . esc_html__('Override default settings per price option. Leave blank to use defaults above.', 'licenzo') . '</p>';

        $allowedCycles = [
            ''         => __('— Use Default —', 'licenzo'),
            'onetime'  => __('One-time', 'licenzo'),
            'lifetime' => __('Lifetime', 'licenzo'),
            'weekly'   => __('Weekly', 'licenzo'),
            'monthly'  => __('Monthly', 'licenzo'),
            'yearly'   => __('Yearly', 'licenzo'),
        ];

        echo '<table class="widefat fixed striped"><thead><tr>';
        echo '<th>' . esc_html__('Price Option', 'licenzo') . '</th>';
        echo '<th>' . esc_html__('Billing Cycle', 'licenzo') . '</th>';
        echo '<th>' . esc_html__('Max Activations', 'licenzo') . '</th>';
        echo '<th>' . esc_html__('Trial Days', 'licenzo') . '</th>';
        echo '</tr></thead><tbody>';

        foreach ($eddPrices as $priceId => $priceOption) {
            $priceId = (int) $priceId;
            $optionName = isset($priceOption['name']) ? sanitize_text_field($priceOption['name']) : "Option {$priceId}";
            $optionAmount = isset($priceOption['amount']) ? number_format((float) $priceOption['amount'], 2) : '0.00';
            $prefix = 'licenzo_variation_' . $priceId . '_';

            $existingVariation = null;
            if ($linkedProduct) {
                $existingVariation = $linkedProduct->variations->firstWhere('provider_id', (string) $priceId);
            }

            $currentCycle = $existingVariation ? ($existingVariation->billing_cycle ?? '') : '';
            $currentMaxActivations = $existingVariation ? ($existingVariation->max_activations ?? '') : '';
            $currentTrialDays = $existingVariation ? ($existingVariation->trial_days ?? '') : '';

            echo '<tr>';
            echo '<td><strong>' . esc_html($optionName) . '</strong><br><small>' . esc_html($optionAmount) . '</small></td>';

            echo '<td><select name="' . esc_attr($prefix . 'cycle') . '">';
            foreach ($allowedCycles as $value => $label) {
                echo '<option value="' . esc_attr($value) . '"' . selected($currentCycle, $value, false) . '>' . esc_html($label) . '</option>';
            }
            echo '</select></td>';

            echo '<td><input type="number" name="' . esc_attr($prefix . 'max_activations') . '" value="' . esc_attr($currentMaxActivations) . '" min="1" step="1" style="width:60px;" placeholder="—" /></td>';
            echo '<td><input type="number" name="' . esc_attr($prefix . 'trial_days') . '" value="' . esc_attr($currentTrialDays) . '" min="0" step="1" style="width:60px;" placeholder="—" /></td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
    }

    private function renderInlineScript(): void
    {
        ?>
        <script>
        (function() {
            var checkbox = document.querySelector('input[name="licenzo_sync_enabled"]');
            var fields = document.getElementById('licenzo-edd-mapping-fields');
            if (checkbox && fields) {
                checkbox.addEventListener('change', function() {
                    fields.style.display = this.checked ? '' : 'none';
                });
            }
        })();
        </script>
        <?php
    }
}
