<?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';
?>

<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" 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</h3>
                    <p>Choose where new enquiries go.</p>
                </div>
            </div>

            <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>
        </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 licence or private access key.</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 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>
            </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" 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</h3>
                    <p>Choose whether the widget appears everywhere or only on selected pages.</p>
                </div>
            </div>

            <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>
        </section>
    </div>
</div>
