<?php
/**
 * 247ChatMate — Core Settings Partial
 *
 * Phase 5-A-12
 * Checkpoint: ADMINSETTINGDECLUTTER5A12LOCK
 *
 * Purpose:
 * - Renders the main business, lead, licence and widget setup fields.
 *
 * Responsibility:
 * - Keep the main settings form calmer and easier to scan.
 * - Group existing saved fields into focused UI sections.
 *
 * Does:
 * - Render existing input names, IDs and saved values.
 * - Keep the existing custom save handler intact.
 * - Keep widget display and page targeting controls available.
 *
 * Does not:
 * - Save settings directly.
 * - Change option names.
 * - Change licence, trial, registry, widget, chip, phone, lead routing or WhatsApp handoff logic.
 * - Add remote calls or entitlement decisions.
 */

defined('ABSPATH') || exit;

$setup_weekly_summary_notice_key = isset($_GET['matewa_weekly_summary_notice'])
    ? sanitize_key(wp_unslash($_GET['matewa_weekly_summary_notice']))
    : '';
$setup_weekly_summary_notice_messages = [
    'test_sent'         => 'Test weekly summary email was sent to the Lead destination inbox.',
    'test_queued'       => 'The test weekly summary could not send immediately, so it was saved in the fallback mail queue for retry.',
    'test_failed'       => 'The test weekly summary email could not be sent. Check the site mail setup and try again.',
    'missing_recipient' => 'Add a Lead destination inbox before sending a test weekly summary.',
    'unknown_action'    => 'Weekly summary action was not recognised. No email was sent.',
];
$setup_weekly_summary_notice_message = $setup_weekly_summary_notice_messages[$setup_weekly_summary_notice_key] ?? '';
$setup_weekly_summary_notice_type    = in_array($setup_weekly_summary_notice_key, ['test_sent'], true) ? 'success' : 'warning';

$matewa_fallback_mail_notice_key = isset($_GET['matewa_fallback_mail_notice'])
    ? sanitize_key(wp_unslash($_GET['matewa_fallback_mail_notice']))
    : '';
$matewa_fallback_mail_notice_messages = [
    'retry_sent'    => 'Queued email retry completed. At least one saved email was sent.',
    'retry_none'    => 'No queued emails were waiting to retry.',
    'retry_failed'  => 'Retry attempted, but at least one queued email still could not be sent.',
    'unknown_action'=> 'Fallback mail action was not recognised.',
];
$matewa_fallback_mail_notice_message = $matewa_fallback_mail_notice_messages[$matewa_fallback_mail_notice_key] ?? '';
$matewa_fallback_mail_notice_type = in_array($matewa_fallback_mail_notice_key, ['retry_sent', 'retry_none'], true) ? 'success' : 'warning';
$matewa_fallback_mail_queue_count = function_exists('matewa_fallback_mail_queue_count') ? matewa_fallback_mail_queue_count() : 0;
$matewa_fallback_mail_status_label = function_exists('matewa_fallback_mail_status_label') ? matewa_fallback_mail_status_label() : 'Mail route ready.';
$matewa_fallback_mail_last_error = function_exists('matewa_fallback_mail_last_error_label') ? matewa_fallback_mail_last_error_label() : '';
$matewa_setup_key_notice_key = isset($_GET['matewa_setup_key_notice'])
    ? sanitize_key(wp_unslash($_GET['matewa_setup_key_notice']))
    : '';
$matewa_setup_key_panel_should_open = '' !== $matewa_setup_key_notice_key;

// AGENCYSETUPKEYDROPDOWNRENDERFIX1:
// The client-site setup key panel is a collapsed support/agency utility on Setup.
// Keep a defensive include here so the panel still renders if load order changes.
if (!function_exists('matewa_agency_client_setup_key_render_panel') && defined('MATEWA_PLUGIN_DIR')) {
    $matewa_setup_key_module = MATEWA_PLUGIN_DIR . 'includes/agency-client-setup-key.php';
    if (is_readable($matewa_setup_key_module)) {
        require_once $matewa_setup_key_module;
    }
}

$matewa_show_setup_remote_key_panel = function_exists('matewa_agency_client_setup_key_render_panel');
$matewa_support_step_number = $matewa_show_setup_remote_key_panel ? '6' : '5';
$matewa_display_pages_step_number = $matewa_show_setup_remote_key_panel ? '7' : '6';
$matewa_language_controls_allowed = function_exists('matewa_is_pro') ? matewa_is_pro() : false;
$matewa_i18n_languages = [];
$matewa_i18n_languages_file = defined('MATEWA_PLUGIN_DIR') ? MATEWA_PLUGIN_DIR . 'public/i18n/languages.json' : '';
if ($matewa_i18n_languages_file && is_readable($matewa_i18n_languages_file)) {
    $matewa_i18n_raw = json_decode((string) file_get_contents($matewa_i18n_languages_file), true);
    if (is_array($matewa_i18n_raw)) {
        foreach ($matewa_i18n_raw as $matewa_lang_code => $matewa_lang_meta) {
            if (!is_array($matewa_lang_meta)) {
                continue;
            }
            $matewa_code = strtolower(str_replace('_', '-', sanitize_text_field((string) ($matewa_lang_meta['code'] ?? $matewa_lang_code))));
            if ('en' === $matewa_code) {
                continue;
            }
            if ('' === $matewa_code) {
                continue;
            }
            $matewa_i18n_languages[$matewa_code] = [
                'code'        => $matewa_code,
                'englishName' => sanitize_text_field((string) ($matewa_lang_meta['englishName'] ?? $matewa_code)),
                'nativeName'  => sanitize_text_field((string) ($matewa_lang_meta['nativeName'] ?? ($matewa_lang_meta['englishName'] ?? $matewa_code))),
                'flagEmoji'   => sanitize_text_field((string) ($matewa_lang_meta['flagEmoji'] ?? '')),
                'flagFile'    => sanitize_file_name((string) ($matewa_lang_meta['flag'] ?? '')),
                'flagExists'   => '' !== sanitize_file_name((string) ($matewa_lang_meta['flag'] ?? '')) && file_exists(dirname($matewa_i18n_languages_file) . '/flags/' . sanitize_file_name((string) ($matewa_lang_meta['flag'] ?? ''))),
            ];
        }
    }
}
$matewa_selected_default_language = isset($widget_default_language) ? strtolower(str_replace('_', '-', (string) $widget_default_language)) : 'auto';
if ('en' === $matewa_selected_default_language) {
    $matewa_selected_default_language = 'en-gb';
}
$matewa_selected_visible_languages = [];
foreach (explode(',', isset($widget_visible_languages) ? (string) $widget_visible_languages : '') as $matewa_visible_language_code) {
    $matewa_visible_language_code = strtolower(str_replace('_', '-', trim($matewa_visible_language_code)));
    if ('en' === $matewa_visible_language_code) {
        $matewa_visible_language_code = 'en-gb';
    }
    if ('' !== $matewa_visible_language_code) {
        $matewa_selected_visible_languages[$matewa_visible_language_code] = true;
    }
}
?>

<div class="matewa-settings-card matewa-core-settings-shell" id="matewa-core-settings-section">
    <div class="matewa-core-settings-heading">
        <span class="matewa-section-kicker">Setup</span>
        <h2><?php echo esc_html($settings_heading); ?></h2>
        <p class="description">
            <?php echo esc_html($settings_description); ?>
        </p>
    </div>


    <div class="matewa-core-settings-grid" aria-label="Main setup sections">
        <section class="matewa-core-settings-panel" aria-labelledby="matewa-business-basics-heading">
            <div class="matewa-core-panel-heading">
                <span class="matewa-panel-step">1</span>
                <div>
                    <h3 id="matewa-business-basics-heading">Business basics</h3>
                    <p>Set the business details, WhatsApp number, inbox and key details your widget needs.</p>
                </div>
            </div>

            <div class="matewa-field-stack">
                <div class="matewa-field-row">
                    <label class="matewa-field-label" for="matewa_number">WhatsApp number</label>
                    <div class="matewa-field-control">
                        <input
                            type="text"
                            id="matewa_number"
                            name="matewa_number"
                            class="regular-text"
                            value="<?php echo esc_attr($number); ?>"
                            placeholder="e.g. 447900123456"
                        />
                        <p class="description">Use full international format, for example 447900123456.</p>
                    </div>
                </div>

                <div class="matewa-field-row">
                    <label class="matewa-field-label" for="matewa_marketing_email">Account email</label>
                    <div class="matewa-field-control">
                        <input
                            type="email"
                            id="matewa_marketing_email"
                            name="matewa_marketing_email"
                            class="regular-text"
                            value="<?php echo esc_attr($marketing_email); ?>"
                            placeholder="e.g. hello@yourbusiness.com"
                        />
                        <p class="description">Used for account, product and trial messages. It is not the lead inbox.</p>
                    </div>
                </div>

                <div class="matewa-field-row">
                    <label class="matewa-field-label" for="matewa_business_name">Business name</label>
                    <div class="matewa-field-control">
                        <input
                            type="text"
                            id="matewa_business_name"
                            name="matewa_business_name"
                            class="regular-text"
                            value="<?php echo esc_attr($business); ?>"
                        />
                        <p class="description">Shown inside the widget experience.</p>
                    </div>
                </div>

                <div class="matewa-field-row">
                    <label class="matewa-field-label" for="matewa_industry">Industry</label>
                    <div class="matewa-field-control">
                        <input
                            type="text"
                            id="matewa_industry"
                            name="matewa_industry"
                            class="regular-text"
                            value="<?php echo esc_attr($industry); ?>"
                            placeholder="e.g. Plumber"
                        />
                        <p class="description">Helps future setup suggestions match your trade.</p>
                    </div>
                </div>
            </div>
        </section>

        <section class="matewa-core-settings-panel<?php echo in_array($mode, ['free', 'trial_expired'], true) ? ' is-pro-locked' : ''; ?>" aria-labelledby="matewa-lead-routing-heading">
            <div class="matewa-core-panel-heading">
                <span class="matewa-panel-step">2</span>
                <div>
                    <h3 id="matewa-lead-routing-heading">Lead routing<?php if (in_array($mode, ['free', 'trial_expired'], true)) : ?> <span class="matewa-inline-pro-badge">PRO</span><?php endif; ?></h3>
                    <?php if (in_array($mode, ['free', 'trial_expired'], true)) : ?>
                        <p>Free hands enquiries to WhatsApp. Email lead delivery and reporting unlock with Pro.</p>
                    <?php else : ?>
                        <p>Choose where new enquiries go.</p>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (in_array($mode, ['free', 'trial_expired'], true)) : ?>
                <div class="matewa-pro-feature-preview matewa-pro-feature-preview--lead-routing">
                    <div class="matewa-pro-feature-preview__row">
                        <span class="dashicons dashicons-email-alt" aria-hidden="true"></span>
                        <div><strong>Email lead delivery</strong><small>Send each captured enquiry to your sales or enquiries inbox.</small></div>
                        <span class="matewa-inline-pro-badge">PRO</span>
                    </div>
                    <div class="matewa-pro-feature-preview__row">
                        <span class="dashicons dashicons-chart-area" aria-hidden="true"></span>
                        <div><strong>Lead tools & weekly summaries</strong><small>Test delivery, monitor lead totals and receive weekly reports.</small></div>
                        <span class="matewa-inline-pro-badge">PRO</span>
                    </div>
                    <p class="matewa-pro-feature-preview__note">Your Free widget continues to hand visitors directly to WhatsApp.</p>
                </div>
            <?php else : ?>

            <div class="matewa-field-stack">
                <div class="matewa-field-row">
                    <label class="matewa-field-label" for="matewa_leads_email">Lead destination inbox</label>
                    <div class="matewa-field-control">
                        <input
                            type="email"
                            id="matewa_leads_email"
                            name="matewa_leads_email"
                            class="regular-text"
                            value="<?php echo esc_attr($leads_email); ?>"
                            placeholder="e.g. jobs@yourbusiness.com"
                        />
                        <p class="description">New website leads are emailed here. Use your sales or enquiries inbox.</p>
                    </div>
                </div>


                <div id="matewa-setup-lead-tools" class="matewa-setup-lead-tools" aria-label="Lead tools and reporting controls">
                    <div class="matewa-setup-lead-tools__heading">
                        <strong>Lead tools</strong>
                        <span>Use these tools to test, refresh or reset your lead reports.</span>
                    </div>

                    <?php if (!empty($dashboard_history_notice_message)) : ?>
                        <div class="matewa-dashboard-history-notice is-<?php echo esc_attr($dashboard_history_notice_type); ?>" role="status" aria-live="polite">
                            <?php echo esc_html($dashboard_history_notice_message); ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($setup_weekly_summary_notice_message)) : ?>
                        <div class="matewa-dashboard-history-notice is-<?php echo esc_attr($setup_weekly_summary_notice_type); ?>" role="status" aria-live="polite">
                            <?php echo esc_html($setup_weekly_summary_notice_message); ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($matewa_fallback_mail_notice_message)) : ?>
                        <div class="matewa-dashboard-history-notice is-<?php echo esc_attr($matewa_fallback_mail_notice_type); ?>" role="status" aria-live="polite">
                            <?php echo esc_html($matewa_fallback_mail_notice_message); ?>
                        </div>
                    <?php endif; ?>

                    <div class="matewa-dashboard-history-notice is-success matewa-mail-route-status" role="status" aria-live="polite">
                        <strong>Mail delivery:</strong> <?php echo esc_html($matewa_fallback_mail_status_label); ?>
                        <?php if (!empty($matewa_fallback_mail_last_error)) : ?>
                            <br><span>Last mail error: <?php echo esc_html($matewa_fallback_mail_last_error); ?></span>
                        <?php endif; ?>
                    </div>

                    <div class="matewa-setup-lead-tool-grid">
                        <a class="matewa-dashboard-history-button is-secondary" href="<?php echo esc_url(admin_url('admin.php?page=247chatmate#matewa-setup-lead-tools')); ?>">Refresh lead totals</a>
                        <button type="submit" form="matewa-weekly-summary-test-form" class="matewa-dashboard-history-button is-secondary" aria-label="Send a test weekly lead summary email">Send test weekly summary</button>
                        <button type="submit" form="matewa-fallback-mail-retry-form" class="matewa-dashboard-history-button is-secondary" aria-label="Retry queued lead and summary emails" <?php disabled(0 === absint($matewa_fallback_mail_queue_count)); ?>>Retry queued emails<?php echo 0 < absint($matewa_fallback_mail_queue_count) ? ' (' . esc_html((string) absint($matewa_fallback_mail_queue_count)) . ')' : ''; ?></button>
                    </div>

                    <?php if (function_exists('matewa_client_mail_delivery_render_panel')) : ?>
                        <?php matewa_client_mail_delivery_render_panel(); ?>
                    <?php endif; ?>

                    <details class="matewa-dashboard-detail-zone matewa-setup-lead-detail">
                        <summary>Retention settings</summary>
                        <div class="matewa-dashboard-retention-card" aria-label="Lead history retention rules">
                            <p>Raw lead details are kept for <?php echo esc_html((string) ($dashboard_history_retention_label ?? '28 days')); ?>, then cleared. Dashboard totals stay.</p>
                            <label>
                                Raw lead details retention
                                <select form="matewa-history-retention-form" name="matewa_history_retention_days">
                                    <?php foreach (($dashboard_history_retention_options ?? [28 => '28 days']) as $retention_value => $retention_label) : ?>
                                        <option value="<?php echo esc_attr((string) absint($retention_value)); ?>" <?php selected(absint($dashboard_history_retention_days ?? 28), absint($retention_value)); ?>>
                                            <?php echo esc_html((string) $retention_label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </label>
                            <button type="submit" form="matewa-history-retention-form" class="matewa-dashboard-history-button is-secondary" aria-label="Save lead history retention setting">Save retention setting</button>
                        </div>
                    </details>

                    <details class="matewa-dashboard-danger-zone matewa-setup-lead-detail">
                        <summary>Reset controls</summary>
                        <div class="matewa-dashboard-danger-zone-inner">
                            <label class="matewa-dashboard-history-confirm">
                                <input form="matewa-reset-current-month-form" type="checkbox" name="matewa_history_confirm_reset_month" value="1">
                                Confirm reset for this month
                            </label>
                            <button type="submit" form="matewa-reset-current-month-form" class="matewa-dashboard-history-button is-warning">Reset this month</button>

                            <label>
                                Type <strong>RESET HISTORY</strong>
                                <input form="matewa-reset-history-form" type="text" name="matewa_history_confirm_text" autocomplete="off" placeholder="RESET HISTORY">
                            </label>
                            <button type="submit" form="matewa-reset-history-form" class="matewa-dashboard-history-button is-danger">Reset history</button>

                            <label>
                                Type <strong>RESET</strong>
                                <input form="matewa-hard-reset-history-form" type="text" name="matewa_history_confirm_text" autocomplete="off" placeholder="RESET">
                            </label>
                            <button type="submit" form="matewa-hard-reset-history-form" class="matewa-dashboard-history-button is-danger">Hard reset</button>
                        </div>
                    </details>
                </div>
            </div>
            <?php endif; ?>
        </section>

        <section class="matewa-core-settings-panel" aria-labelledby="matewa-plan-key-heading">
            <div class="matewa-core-panel-heading">
                <span class="matewa-panel-step">3</span>
                <div>
                    <h3 id="matewa-plan-key-heading">Plan key</h3>
                    <p>Add your Pro licence key, or upgrade directly.</p>
                </div>
            </div>

            <div class="matewa-field-stack">
                <div class="matewa-field-row">
                    <label class="matewa-field-label" for="matewa_license_key">Licence key</label>
                    <div class="matewa-field-control">
                        <input
                            type="password"
                            id="matewa_license_key"
                            name="matewa_license_key"
                            class="regular-text"
                            value=""
                            placeholder="<?php echo '' !== $masked_license ? esc_attr('Saved key hidden - enter a new key to replace') : esc_attr('Enter your 247ChatMate licence or access key'); ?>"
                            autocomplete="new-password"
                            spellcheck="false"
                            aria-describedby="matewa-license-key-help"
                        />
                        <p class="description" id="matewa-license-key-help">For security, saved keys are hidden after saving and are not printed back into the page. Leave this field blank to keep the saved key, or enter a new key to replace it.</p>
                        <?php if ('' !== $masked_license) : ?>
                            <div class="matewa-license-meta">
                                Saved key hidden for security.
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($saved_key_is_agency_access)) : ?>
                            <div class="matewa-license-meta">
                                <?php if (!empty($dashboard_agency_active)) : ?>
                                    Agency own-site access verified. Client seats granted by this key: 0.
                                <?php else : ?>
                                    Agency own-site access: <?php echo esc_html(sanitize_text_field((string) ($agency_diag['status'] ?? ($agency_last['status'] ?? 'not active')))); ?>.
                                    <?php if (!empty($agency_message)) : ?>
                                        <?php echo esc_html($agency_message); ?>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="matewa-license-save-refresh">
                    <p class="description matewa-license-save-refresh__help">After entering a paid licence or private access key, use this to save the hidden key and recheck access immediately.</p>
                    <div class="matewa-license-save-refresh__actions">
                        <button
                            type="submit"
                            name="matewa_save_and_refresh_license"
                            value="1"
                            class="button button-secondary matewa-license-save-refresh__button"
                        >
                            Save &amp; refresh plan
                        </button>
                        <?php if (!empty($dashboard_agency_active)) : ?>
                            <a
                                class="button button-secondary matewa-agency-buy-licences-button"
                                href="<?php echo esc_url(function_exists('matewa_agency_bundle_get_default_checkout_url') ? matewa_agency_bundle_get_default_checkout_url() : 'https://247chatmate.lemonsqueezy.com/'); ?>"
                                target="_blank"
                                rel="noopener noreferrer"
                            >
                                Buy client licences
                            </a>
                        <?php endif; ?>
                    </div>
                </div>

                <?php
                $matewa_is_free_distribution = defined('MATEWA_DISTRIBUTION_PROFILE') && 'free' === MATEWA_DISTRIBUTION_PROFILE;
                $matewa_show_free_upgrade_cta = $matewa_is_free_distribution
                    && 'free' === ($mode ?? 'free')
                    && empty($dashboard_agency_active);
                ?>
                <?php if ($matewa_show_free_upgrade_cta) : ?>
                    <div class="matewa-plan-key-upgrade-row">
                        <a
                            class="button button-primary matewa-license-upgrade-pro-button"
                            href="<?php echo esc_url(defined('MATEWA_SINGLE_MONTHLY_CHECKOUT_URL') ? MATEWA_SINGLE_MONTHLY_CHECKOUT_URL : 'https://247chatmate.lemonsqueezy.com/checkout/buy/654461de-2eae-4715-a249-a2ac7e032678'); ?>"
                            target="_blank"
                            rel="noopener noreferrer"
                        >
                            Upgrade to Pro
                        </a>
                    </div>
                <?php endif; ?>

                <?php if (function_exists('matewa_founder_qa_is_available') && matewa_founder_qa_is_available()) { require MATEWA_PLUGIN_DIR . 'admin/views/partials/core-settings/test-reset.php'; } ?>
            </div>
        </section>

        <section class="matewa-core-settings-panel" aria-labelledby="matewa-widget-basics-heading">
            <div class="matewa-core-panel-heading">
                <span class="matewa-panel-step">4</span>
                <div>
                    <h3 id="matewa-widget-basics-heading">Widget basics</h3>
                    <p>Turn the website widget on and choose whether visitors can select a country code.</p>
                </div>
            </div>

            <div class="matewa-choice-stack">
                <label class="matewa-choice-card">
                    <input
                        type="checkbox"
                        name="matewa_widget_settings[enabled]"
                        value="1"
                        <?php checked(($widget['enabled'] ?? '0'), '1'); ?>
                    >
                    <span>
                        <strong>Enable widget</strong>
                        <small>Turn the chat widget on across your site.</small>
                    </span>
                </label>

                <input
                    type="hidden"
                    name="matewa_widget_settings[show_country_selector]"
                    value="0"
                />
                <label class="matewa-choice-card">
                    <input
                        type="checkbox"
                        name="matewa_widget_settings[show_country_selector]"
                        value="1"
                        <?php checked($widget_show_country_selector); ?>
                    >
                    <span>
                        <strong>Show country code selector</strong>
                        <small>Visitors can choose their phone country code.</small>
                    </span>
                </label>

                <?php if ($matewa_language_controls_allowed) : ?>
                    <input
                        type="hidden"
                        name="matewa_widget_settings[show_language_selector]"
                        value="0"
                    />
                    <label class="matewa-choice-card">
                        <input
                            type="checkbox"
                            name="matewa_widget_settings[show_language_selector]"
                            value="1"
                            <?php checked(!isset($widget_show_language_selector) || $widget_show_language_selector); ?>
                        >
                        <span>
                            <strong>Show language selector</strong>
                            <small>Visitors can choose the widget language. This is separate from the phone country code selector.</small>
                        </span>
                    </label>

                    <div class="matewa-choice-card matewa-choice-card--language-default">
                        <span class="matewa-language-control-wrap">
                            <strong>Default widget language</strong>
                            <small>Choose the language the widget returns to after a hard reset. <code>Auto</code> follows the website language first.</small>
                            <details class="matewa-language-harmonica" data-matewa-language-harmonica>
                                <summary class="matewa-language-harmonica-summary">
                                    <span class="matewa-language-admin-flag" aria-hidden="true">
                                        <?php if ('auto' === $matewa_selected_default_language && isset($matewa_i18n_languages['en-gb']) && !empty($matewa_i18n_languages['en-gb']['flagExists'])) : ?>
                                            <img src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_i18n_languages['en-gb']['flagFile']); ?>" alt="">
                                        <?php elseif (isset($matewa_i18n_languages[$matewa_selected_default_language]) && !empty($matewa_i18n_languages[$matewa_selected_default_language]['flagExists'])) : ?>
                                            <img src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_i18n_languages[$matewa_selected_default_language]['flagFile']); ?>" alt="">
                                        <?php endif; ?>
                                    </span>
                                    <span class="matewa-language-harmonica-label" data-matewa-language-summary>
                                        <?php echo 'auto' === $matewa_selected_default_language ? esc_html__('Auto — website language', '247chatmate') : esc_html($matewa_i18n_languages[$matewa_selected_default_language]['englishName'] ?? $matewa_selected_default_language); ?>
                                    </span>
                                </summary>
                                <div class="matewa-language-admin-grid matewa-language-admin-grid--default">
                                    <label class="matewa-language-admin-row">
                                        <input
                                            type="radio"
                                            name="matewa_widget_settings[default_language]"
                                            value="auto"
                                            data-matewa-language-label="Auto — website language"
                                            <?php if (isset($matewa_i18n_languages['en-gb']) && !empty($matewa_i18n_languages['en-gb']['flagExists'])) : ?>
                                                data-matewa-language-flag-src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_i18n_languages['en-gb']['flagFile']); ?>"
                                            <?php endif; ?>
                                            <?php checked($matewa_selected_default_language, 'auto'); ?>
                                        >
                                        <span class="matewa-language-admin-flag" aria-hidden="true">
                                            <?php if (isset($matewa_i18n_languages['en-gb']) && !empty($matewa_i18n_languages['en-gb']['flagExists'])) : ?>
                                                <img src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_i18n_languages['en-gb']['flagFile']); ?>" alt="">
                                            <?php endif; ?>
                                        </span>
                                        <span class="matewa-language-admin-name">Auto</span>
                                        <small>website</small>
                                    </label>
                                    <?php foreach ($matewa_i18n_languages as $matewa_language) : ?>
                                        <label class="matewa-language-admin-row">
                                            <input
                                                type="radio"
                                                name="matewa_widget_settings[default_language]"
                                                value="<?php echo esc_attr($matewa_language['code']); ?>"
                                                data-matewa-language-label="<?php echo esc_attr($matewa_language['englishName'] . ' / ' . $matewa_language['nativeName']); ?>"
                                                <?php if (!empty($matewa_language['flagFile']) && !empty($matewa_language['flagExists'])) : ?>
                                                    data-matewa-language-flag-src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_language['flagFile']); ?>"
                                                <?php endif; ?>
                                                <?php checked($matewa_selected_default_language, $matewa_language['code']); ?>
                                            >
                                            <span class="matewa-language-admin-flag" aria-hidden="true">
                                                <?php if (!empty($matewa_language['flagFile']) && !empty($matewa_language['flagExists'])) : ?>
                                                    <img src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_language['flagFile']); ?>" alt="">
                                                <?php endif; ?>
                                            </span>
                                            <span class="matewa-language-admin-name"><?php echo esc_html($matewa_language['englishName']); ?></span>
                                            <small><?php echo esc_html($matewa_language['nativeName']); ?></small>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </details>
                        </span>
                    </div>

                    <div class="matewa-choice-card matewa-choice-card--language-visible">
                        <span class="matewa-language-control-wrap">
                            <strong>Visible languages</strong>
                            <small>Select which languages visitors can choose. Leave all unchecked to show every available language.</small>
                            <details class="matewa-language-harmonica" data-matewa-language-harmonica>
                                <summary class="matewa-language-harmonica-summary">
                                    <span class="matewa-language-harmonica-label">Choose visible languages</span>
                                </summary>
                                <div class="matewa-language-admin-grid">
                                    <?php foreach ($matewa_i18n_languages as $matewa_language) : ?>
                                        <label class="matewa-language-admin-row">
                                            <input
                                                type="checkbox"
                                                name="matewa_widget_settings[visible_languages][]"
                                                value="<?php echo esc_attr($matewa_language['code']); ?>"
                                                <?php checked(isset($matewa_selected_visible_languages[$matewa_language['code']])); ?>
                                            >
                                            <span class="matewa-language-admin-flag" aria-hidden="true">
                                                <?php if (!empty($matewa_language['flagFile']) && !empty($matewa_language['flagExists'])) : ?>
                                                    <img src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_language['flagFile']); ?>" alt="">
                                                <?php endif; ?>
                                            </span>
                                            <span class="matewa-language-admin-name"><?php echo esc_html($matewa_language['englishName']); ?></span>
                                            <small><?php echo esc_html($matewa_language['nativeName']); ?></small>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </details>
                            <button type="submit" class="button button-primary matewa-language-save-button">Save language settings</button>
                        </span>
                    </div>
                <?php else : ?>
                    <input type="hidden" name="matewa_widget_settings[show_language_selector]" value="0" />
                    <input type="hidden" name="matewa_widget_settings[default_language]" value="auto" />

                    <div class="matewa-choice-card matewa-choice-card--language-default matewa-choice-card--language-locked">
                        <span class="matewa-language-control-wrap">
                            <strong>Default widget language <span class="matewa-vertical-lock">PRO</span></strong>
                            <small>Free follows the website language. Browse the same language catalogue as Pro below; selection remains locked until Pro is active.</small>

                            <details class="matewa-language-harmonica" data-matewa-language-harmonica>
                                <summary class="matewa-language-harmonica-summary">
                                    <span class="matewa-language-admin-flag" aria-hidden="true">
                                        <?php if (isset($matewa_i18n_languages['en-gb']) && !empty($matewa_i18n_languages['en-gb']['flagExists'])) : ?>
                                            <img src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_i18n_languages['en-gb']['flagFile']); ?>" alt="">
                                        <?php endif; ?>
                                    </span>
                                    <span class="matewa-language-harmonica-label">Auto — website language</span>
                                </summary>

                                <div class="matewa-language-admin-grid matewa-language-admin-grid--default matewa-free-language-preview-grid">
                                    <div class="matewa-language-admin-row is-current-free-language">
                                        <span class="matewa-language-admin-flag" aria-hidden="true">
                                            <?php if (isset($matewa_i18n_languages['en-gb']) && !empty($matewa_i18n_languages['en-gb']['flagExists'])) : ?>
                                                <img src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_i18n_languages['en-gb']['flagFile']); ?>" alt="">
                                            <?php endif; ?>
                                        </span>
                                        <span class="matewa-language-admin-name">Auto</span>
                                        <small>website language</small>
                                    </div>

                                    <?php foreach ($matewa_i18n_languages as $matewa_language) : ?>
                                        <div class="matewa-language-admin-row is-pro-preview" aria-disabled="true">
                                            <span class="matewa-language-admin-flag" aria-hidden="true">
                                                <?php if (!empty($matewa_language['flagFile']) && !empty($matewa_language['flagExists'])) : ?>
                                                    <img src="<?php echo esc_url(MATEWA_PLUGIN_URL . 'public/i18n/flags/' . $matewa_language['flagFile']); ?>" alt="">
                                                <?php endif; ?>
                                            </span>
                                            <span class="matewa-language-admin-name"><?php echo esc_html($matewa_language['englishName']); ?></span>
                                            <small><?php echo esc_html($matewa_language['nativeName']); ?> · PRO</small>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </details>
                        </span>
                    </div>
                <?php endif; ?>
            </div>
        </section>

        <?php if ($matewa_show_setup_remote_key_panel) : ?>
            <section id="matewa-setup-agency-key" class="matewa-core-settings-panel matewa-core-remote-setup-key-panel" aria-labelledby="matewa-setup-remote-key-heading">
                <div class="matewa-core-panel-heading">
                    <span class="matewa-panel-step">5</span>
                    <div>
                        <h3 id="matewa-setup-remote-key-heading">Agency setup key</h3>
                        <p>Only needed if an agency is pushing a saved setup pack into this client site.</p>
                    </div>
                </div>

                <details class="matewa-plan-access-section matewa-plan-access-section--support matewa-setup-remote-key-detail"<?php echo $matewa_setup_key_panel_should_open ? ' open' : ''; ?>>
                    <summary>
                        <span>Open one-time agency setup key</span>
                        <small>Generate a temporary key for remote setup. Keep closed for normal self-setup.</small>
                    </summary>
                    <div class="matewa-setup-remote-key-detail__body">
                        <?php matewa_agency_client_setup_key_render_panel('setup'); ?>
                    </div>
                </details>
            </section>
        <?php endif; ?>

        <section class="matewa-core-settings-panel matewa-core-settings-panel--wide matewa-core-support-diagnostics-panel" aria-labelledby="matewa-setup-support-diagnostics-heading">
            <div class="matewa-core-panel-heading">
                <span class="matewa-panel-step"><?php echo esc_html($matewa_support_step_number); ?></span>
                <div>
                    <h3 id="matewa-setup-support-diagnostics-heading">Support diagnostics</h3>
                    <p>Only open this if support asks.</p>
                </div>
            </div>

            <details class="matewa-plan-access-section matewa-plan-access-section--support matewa-setup-support-diagnostics" data-matewa-plan-section="support">
                <summary>
                    <span>Open safe support summary</span>
                    <small>No endpoints or raw registry details shown</small>
                </summary>
                <div class="matewa-support-diagnostics-intro">
                    <strong>Support-only summary</strong>
                    <p>This shows safe plan status only. Endpoint URLs, registry payloads, hashes, install IDs and raw validation data stay hidden.</p>
                </div>
                <?php require __DIR__ . '/plan-access/support-diagnostics.php'; ?>
            </details>
        </section>

        <section class="matewa-core-settings-panel matewa-core-settings-panel--wide<?php echo in_array($mode, ['free', 'trial_expired'], true) ? ' is-pro-locked' : ''; ?>" aria-labelledby="matewa-display-pages-heading">
            <div class="matewa-core-panel-heading">
                <span class="matewa-panel-step"><?php echo esc_html($matewa_display_pages_step_number); ?></span>
                <div>
                    <h3 id="matewa-display-pages-heading">Display pages<?php if (in_array($mode, ['free', 'trial_expired'], true)) : ?> <span class="matewa-inline-pro-badge">PRO</span><?php endif; ?></h3>
                    <?php if (in_array($mode, ['free', 'trial_expired'], true)) : ?>
                        <p>Free displays the widget on every page. Upgrade to Pro to choose individual pages.</p>
                    <?php else : ?>
                        <p>Choose whether the widget appears everywhere or only on selected pages.</p>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (in_array($mode, ['free', 'trial_expired'], true)) : ?>
                <input type="hidden" name="matewa_widget_settings[display_mode]" value="all">
                <input type="hidden" name="matewa_widget_settings[include_homepage]" value="0">
                <div class="matewa-free-page-lock" id="matewa-display-settings-section">
                    <div class="matewa-free-page-lock-status">
                        <span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>
                        <div><strong>Showing on all pages</strong><small>Fixed placement for 247ChatMate Free.</small></div>
                    </div>
                    <div class="matewa-free-page-lock-preview">
                        <label><input type="checkbox" disabled> Show widget only on selected pages <span class="matewa-inline-pro-badge">PRO</span></label>
                        <div class="matewa-free-page-lock-list"><span>Homepage</span><span>Service pages</span><span>Contact page</span></div>
                    </div>
                    <p class="matewa-free-page-lock-upgrade">Page-by-page targeting unlocks with Pro.</p>
                </div>
            <?php else : ?>

            <fieldset class="matewa-display-mode-options">
                <legend class="screen-reader-text">Widget Page Display</legend>

                <label class="matewa-choice-card matewa-choice-card--inline">
                    <input
                        type="checkbox"
                        class="matewa-display-mode-checkbox"
                        name="matewa_widget_settings[display_mode]"
                        value="selected"
                        <?php checked($widget_display_mode, 'selected'); ?>
                    >
                    <span>
                        <strong>Show widget only on selected pages</strong>
                        <small>Leave this off to show the widget everywhere.</small>
                    </span>
                </label>
            </fieldset>

            <div class="matewa-page-targeting-box" id="matewa-display-settings-section">
                <strong>Detected pages</strong>
                <p class="description">Tick the pages where the widget should appear.</p>

                <div class="matewa-page-checkbox-list" role="group" aria-label="Detected pages">
                    <label class="matewa-page-checkbox-row">
                        <input
                            type="checkbox"
                            name="matewa_widget_settings[include_homepage]"
                            value="1"
                            <?php checked($widget_include_homepage, '1'); ?>
                        >
                        <span class="matewa-page-checkbox-main">
                            <span class="matewa-page-checkbox-title">Homepage</span>
                            <span class="matewa-page-checkbox-url"><?php echo esc_html(untrailingslashit(home_url('/'))); ?></span>
                        </span>
                    </label>

                    <?php if (!empty($available_pages)) : ?>
                        <?php $home_page_id = (int) get_option('page_on_front'); ?>
                        <?php foreach ($available_pages as $available_page) : ?>
                            <?php
                            $available_page_id = (int) $available_page->ID;

                            if ($home_page_id > 0 && $available_page_id === $home_page_id) {
                                continue;
                            }

                            $available_page_title = $available_page->post_title ?: ('Page #' . $available_page_id);
                            $available_page_url = get_permalink($available_page_id);
                            ?>
                            <label class="matewa-page-checkbox-row">
                                <input
                                    type="checkbox"
                                    name="matewa_widget_settings[page_ids][]"
                                    value="<?php echo esc_attr((string) $available_page_id); ?>"
                                    <?php checked(in_array($available_page_id, $widget_page_ids, true)); ?>
                                >
                                <span class="matewa-page-checkbox-main">
                                    <span class="matewa-page-checkbox-title"><?php echo esc_html($available_page_title); ?></span>
                                    <span class="matewa-page-checkbox-url"><?php echo esc_html($available_page_url); ?></span>
                                </span>
                            </label>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </section>
    </div>
</div>
