<?php
/**
 * ╔══════════════════════════════════════════════════════════════════════════════╗
 * ║  PANEL_ADMINA — Main Admin Panel for ParcelSelector.com                     ║
 * ╠══════════════════════════════════════════════════════════════════════════════╣
 * ║                                                                            ║
 * ║  SINGLE entry point for ALL admin settings.                                ║
 * ║  Both WordPress Admin Tab and WooCommerce Tab point here.                  ║
 * ║                                                                            ║
 * ║  TABS:                                                                     ║
 * ║  1. MAPS        - Country enable/disable + drag-to-order                   ║
 * ║  2. CARRIERS    - Carrier management                                       ║
 * ║  3. BEHAVIOR    - Popup/map/checkout interaction settings                  ║
 * ║  4. APPEARANCE  - Color schemes (placeholder)                              ║
 * ║  5. SETTINGS    - Core WooCommerce settings (migrated from admin.php)      ║
 * ║  6. CONTACT     - Contact form + office@parcelselector.com                 ║
 * ║  7. TESTING     - API connection test (hidden, via direct URL)             ║
 * ║                                                                            ║
 * ║  Multi-language: All strings from PANEL_ADMINA/i18n.php                    ║
 * ║  Each tab is a separate file in PANEL_ADMINA/tabs/                         ║
 * ║                                                                            ║
 * ╚══════════════════════════════════════════════════════════════════════════════╝
 *
 * @package ParcelSelector
 * @since   3.0.9
 */

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

// ═══════════════════════════════════════════════════════════════════════════════
// Load dependencies
// ═══════════════════════════════════════════════════════════════════════════════
require_once __DIR__ . '/i18n.php';

// Load individual tab renderers
foreach ( glob( __DIR__ . '/tabs/tab-*.php' ) as $parcselect_tab_file ) {
    require_once $parcselect_tab_file;
}

/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * TAB REGISTRY — defines all available tabs and their properties
 * ═══════════════════════════════════════════════════════════════════════════════
 */
if ( ! function_exists( 'parcselect_get_tabs' ) ) {
function parcselect_get_tabs() {
    $t = parcselect_admin_i18n();
    
    // Tab order: setup flow first (Maps → Carriers → Checkout → Appearance),
    // then technical (Diagnostics → License), then support (Contact).
    // Etykietownik added via filter by its own module.
    $tabs = array(
        'maps' => array(
            'label'    => $t['tab_maps'] ?? __( 'Maps', 'parcel-selector' ),
            'icon'     => "\xF0\x9F\x97\xBA",
            'callback' => 'parcselect_tab_maps',
        ),
        'carriers' => array(
            'label'    => $t['tab_carriers'] ?? __( 'Carriers', 'parcel-selector' ),
            'icon'     => "\xF0\x9F\x9A\x9A",
            'callback' => 'parcselect_tab_carriers',
        ),
        'behavior' => array(
            'label'    => $t['tab_checkout'] ?? $t['tab_behavior'] ?? __( 'Checkout', 'parcel-selector' ),
            'icon'     => "\xE2\x9A\x99\xEF\xB8\x8F",
            'callback' => 'parcselect_tab_behavior',
        ),
        'appearance' => array(
            'label'    => $t['tab_appearance'] ?? __( 'Appearance', 'parcel-selector' ),
            'icon'     => "\xF0\x9F\x8E\xA8",
            'callback' => 'parcselect_tab_appearance',
        ),
        'settings' => array(
            'label'    => $t['tab_settings'] ?? __( 'Settings', 'parcel-selector' ),
            'icon'     => "\xF0\x9F\x9B\xA0",
            'callback' => 'parcselect_tab_settings',
        ),
        'contact' => array(
            'label'    => $t['tab_contact'] ?? __( 'Contact', 'parcel-selector' ),
            'icon'     => "\xF0\x9F\x93\xA7",
            'callback' => 'parcselect_tab_contact',
        ),
    );

    // Diagnostics tab — hidden by default, visible only via direct URL or support link.
    $_ps_show_diag = isset( $_GET['show_diagnostics'] ) || ( isset( $_GET['tab'] ) && 'testing' === sanitize_key( $_GET['tab'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( $_ps_show_diag ) {
        $tabs['testing'] = array(
            'label'    => $t['tab_diagnostics'] ?? __( 'Diagnostics', 'parcel-selector' ),
            'icon'     => "\xF0\x9F\x94\xAC",
            'callback' => 'parcselect_tab_testing',
        );
    }

    // Label Sender tab — sender address for shipping label generation.
    $tabs['label-sender'] = array(
        'label'    => __( 'Labels — Sender', 'parcel-selector' ),
        'icon'     => "\xF0\x9F\x93\xA6",
        'callback' => 'parcselect_tab_label_sender',
    );

    // Go Pro tab — always last.
    $tabs['go-pro'] = array(
        'label'    => __( 'Go Pro', 'parcel-selector' ),
        'icon'     => "\xF0\x9F\x9A\x80",
        'callback' => 'parcselect_tab_go_pro',
    );

    // Allow modules to register their own tabs.
    return apply_filters( 'parcselect_tabs', $tabs );
}
}

/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * MAIN RENDER FUNCTION — called by both WP Admin menu and WC submenu
 * ═══════════════════════════════════════════════════════════════════════════════
 */
if ( ! function_exists( 'parcselect_admin_panel_render' ) ) {
function parcselect_admin_panel_render() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Unauthorized', 'parcel-selector' ) );
    }

    $t    = parcselect_admin_i18n();
    $tabs = parcselect_get_tabs();

    // Default tab: Maps first (setup flow: Maps → Carriers → Checkout).
    $_ps_default_tab  = 'maps';

    $active_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : $_ps_default_tab; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin tab navigation param, no form submission.
    if ( ! isset( $tabs[ $active_tab ] ) ) {
        $active_tab = $_ps_default_tab;
    }

    // Metadata
    $version       = defined( 'PARCSELECT_VERSION' ) ? PARCSELECT_VERSION : '3.3.0';
    $theme         = get_user_meta( get_current_user_id(), 'parcselect_admin_theme', true ) ?: 'light';

    // Asset paths for premium experience
    $css_url = plugin_dir_url( __FILE__ ) . 'assets/css/admin-panel.css';
    $js_url  = plugin_dir_url( __FILE__ ) . 'assets/js/admin-panel.js';

    // Local self-hosted fonts (GDPR compliant — no external Google Fonts).
    wp_enqueue_style( 'parcselect-local-fonts', PARCSELECT_PLUGIN_URL . 'assets/fonts/fonts.css', array(), $version );
    wp_enqueue_style( 'parcselect-admin-premium-css', $css_url, array( 'parcselect-local-fonts' ), $version );
    wp_enqueue_script( 'parcselect-admin-premium-js', $js_url, array( 'jquery' ), $version, true );

    // Localize for JS
    wp_localize_script( 'parcselect-admin-premium-js', 'parcselectAdminVars', array(
        'version'   => $version,
        'saveNonce' => wp_create_nonce( 'parcselect_panel_save' ),
        'ajaxurl'   => admin_url( 'admin-ajax.php' ),
        'nonces'    => array(
            'test_api'         => wp_create_nonce( 'parcselect_test_api' ),
            'reset_activation' => wp_create_nonce( 'parcselect_reset_activation_nonce' ),
        ),
        'strings'   => array(
            'saved'   => $t['notice_settings_saved'],
            'error'   => $t['notice_error'],
            'loading' => $t['loading'],
        ),
        'i18n'      => array(
            'test_connection_btn'    => $t['js_test_connection_btn'] ?? '🔌 Test connection',
            'checking'               => $t['js_checking'] ?? 'Checking...',
            'check_updates_link'     => $t['js_check_updates_link'] ?? 'Check for updates',
            'update_available'       => $t['js_update_available'] ?? '⚠️ Update available:',
            'up_to_date'             => $t['js_up_to_date'] ?? 'You have the latest version',
            'reset_confirm_title'    => $t['js_reset_confirm_title'] ?? 'Reset local plugin data?',
            'reset_confirm_body'     => $t['js_reset_confirm_body'] ?? 'Removes the local installation ID and plugin settings from the WordPress database. The pickup-point service keeps its own data.',
            'resetting'              => $t['js_resetting'] ?? 'Resetting...',
            'please_wait'            => $t['js_please_wait'] ?? '⏳ Please wait...',
            'update_server_error'    => $t['js_update_server_error'] ?? 'Update server connection error.',
        ),
    ) );
    ?>
    <div class="wrap parcelselector-admin-wrap ps-theme-<?php echo esc_attr( $theme ); ?>" id="ps-admin-panel">
        <!-- ═══════════════ HEADER ═══════════════ -->
        <div class="parcelselector-admin-header">
            <div class="parcelselector-header-left" style="display:flex;align-items:center;gap:14px;">
                <!-- ── ParcelSelector Mascot ── -->
                <img
                    src="<?php echo esc_url( plugin_dir_url( dirname( __FILE__ ) ) . 'assets/images/Parcel_Selector_Com.jpg' ); ?>"
                    alt="Parcel Selector — WooCommerce pickup point and parcel locker map plugin mascot"
                    width="220"
                    height="220"
                    style="flex-shrink:0;border-radius:12px;object-fit:contain;"
                />
                <div>
                    <h1 class="parcelselector-title">
                        <?php echo esc_html( $t['panel_title'] ); ?>
                    </h1>
                    <span class="parcelselector-version">v<?php echo esc_html( $version ); ?></span>
                    <p class="parcelselector-subtitle"><?php echo esc_html( $t['panel_subtitle'] ); ?></p>
                </div>
            </div>
        </div>

        <!-- ═══════════════ QUICK ACTIONS ═══════════════ -->
        <?php if ( $inst_id = get_option( 'parcselect_installation_id', '' ) ) : ?>
        <div style="margin:-8px 0 16px; display:flex; gap:8px; flex-wrap:wrap; align-items:center;">
            <span style="font-size:12px; color:#9ca3af; display:flex; align-items:center; gap:6px;">
                ID: <code id="ps-header-inst-id" style="font-size:11px; color:#6b7280; background:#f3f4f6; padding:2px 6px; border-radius:4px;"><?php echo esc_html( $inst_id ); ?></code>
                <button type="button" onclick="parcselectCopyText('ps-header-inst-id',this)" style="background:none;border:none;cursor:pointer;font-size:13px;padding:0;color:#9ca3af;" title="<?php esc_attr_e( 'Copy Installation ID', 'parcel-selector' ); ?>">&#x1F4CB;</button>
            </span>
        </div>
        <?php endif; ?>
        <?php
        wp_add_inline_script( 'parcselect-admin-premium-js', 'window.parcselectCopyText = function(elemId, btn) {
            var el = document.getElementById(elemId);
            if (!el) return;
            var text = el.textContent.trim();
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(function() {
                    btn.textContent = "\u2705";
                    setTimeout(function() { btn.innerHTML = "\uD83D\uDCCB"; }, 1500);
                });
            } else {
                var ta = document.createElement("textarea");
                ta.value = text; ta.style.position="fixed"; ta.style.opacity="0";
                document.body.appendChild(ta); ta.select(); document.execCommand("copy");
                document.body.removeChild(ta);
                btn.textContent = "\u2705";
                setTimeout(function() { btn.innerHTML = "\uD83D\uDCCB"; }, 1500);
            }
        };' );
        ?>

        <!-- ═══════════════ TAB NAVIGATION ═══════════════ -->
        <nav class="nav-tab-wrapper parcelselector-tabs">
            <?php foreach ( $tabs as $slug => $tab ): ?>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=parcelselector-settings&tab=' . $slug ) ); ?>"
                   class="nav-tab <?php echo ( $active_tab === $slug ) ? 'nav-tab-active' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static CSS class name. ?>">
                    <?php echo esc_html( $tab['icon'] ); ?> <?php echo esc_html( $tab['label'] ); ?>
                </a>
            <?php endforeach; ?>
        </nav>

        <!-- ═══════════════ TAB CONTENT ═══════════════ -->
        <div class="parcelselector-tab-content">
            <?php
            $callback = $tabs[ $active_tab ]['callback'];
            if ( function_exists( $callback ) ) {
                call_user_func( $callback );
            } else {
                echo '<div class="parcelselector-notice parcelselector-notice-info">';
                echo '<p>&#x1F6A7; ' . esc_html( $t['coming_soon'] ) . '</p>';
                echo '</div>';
            }
            ?>
        </div>


        <!-- ═══════════════ FOOTER ═══════════════ -->
        <div class="parcelselector-admin-footer">
            <p>
                &#x1F4E6; <a href="https://www.parcelselector.com/" target="_blank" rel="noopener noreferrer">www.parcelselector.com</a>
                &nbsp;|&nbsp; &#x1F4E7; <a href="mailto:office@parcelselector.com">office@parcelselector.com</a>
                &nbsp;|&nbsp; v<?php echo esc_html( $version ); ?>
            </p>
        </div>
    </div>

    <div class="ps-saving-overlay">
        <div class="ps-save-spinner"></div>
    </div>
    <?php
}
}

// AJAX endpoint parcselect_test_api was removed for WP.org compliance:
// the legacy handler pinged an internal admin health endpoint to display
// connection status, which is a phone-home pattern requiring per-request
// user consent. Removing the endpoint and its UI eliminates the issue
// entirely.

// ═══════════════════════════════════════════════════════════════════════════════
// AJAX HANDLER: parcelselector_send_contact — send contact form to API server
// ═══════════════════════════════════════════════════════════════════════════════
add_action( 'wp_ajax_parcselect_send_contact', 'parcselect_handle_send_contact' );

if ( ! function_exists( 'parcselect_handle_send_contact' ) ) {
function parcselect_handle_send_contact() {
    check_ajax_referer( 'parcselect_contact', '_wpnonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( [ 'message' => 'Unauthorized' ] );
    }

    // Collect & sanitize form fields (WordPress sanitization functions)
    $sender_name  = sanitize_text_field( wp_unslash( $_POST['sender_name'] ?? '' ) );
    $sender_email = sanitize_email( wp_unslash( $_POST['sender_email'] ?? '' ) );
    $sender_phone = sanitize_text_field( wp_unslash( $_POST['sender_phone'] ?? '' ) );
    if ( function_exists( 'parcselect_phone_normalize_pl' ) ) { $_n = parcselect_phone_normalize_pl( $sender_phone ); if ( $_n ) { $sender_phone = $_n; } }
    $subject      = sanitize_text_field( wp_unslash( $_POST['subject'] ?? '' ) );
    $message      = sanitize_textarea_field( wp_unslash( $_POST['message'] ?? '' ) );
    $category     = sanitize_text_field( wp_unslash( $_POST['category'] ?? 'general' ) );

    // Validate required fields
    if ( empty( $sender_email ) || ! is_email( $sender_email ) ) {
        wp_send_json_error( [ 'message' => 'Valid email address is required.' ] );
    }
    if ( mb_strlen( $message ) < 10 ) {
        wp_send_json_error( [ 'message' => 'Message must be at least 10 characters.' ] );
    }
    if ( mb_strlen( $message ) > 5000 ) {
        wp_send_json_error( [ 'message' => 'Message must be under 5000 characters.' ] );
    }

    // Whitelist categories
    $allowed_cats = [ 'general', 'bug', 'feature', 'billing', 'technical', 'other' ];
    if ( ! in_array( $category, $allowed_cats, true ) ) {
        $category = 'general';
    }

    // Build payload for API server
    $payload = [
        'sender_name'    => $sender_name,
        'sender_email'   => $sender_email,
        'sender_phone'   => $sender_phone,
        'subject'        => $subject,
        'message'        => $message,
        'category'       => $category,
        'domain'         => wp_parse_url( home_url(), PHP_URL_HOST ),
        'site_url'       => home_url(),
        'site_name'      => get_bloginfo( 'name' ),
        'installation_id'=> get_option( 'parcselect_installation_id', '' ),
        'plugin_version' => PARCSELECT_VERSION,
        'wp_version'     => get_bloginfo( 'version' ),
        'wc_version'     => defined( 'WC_VERSION' ) ? WC_VERSION : '',
        'php_version'    => phpversion(),
        'locale'         => get_locale(),
    ];

    if ( function_exists( 'parcselect_log' ) ) {
        parcselect_log( '[CONTACT] Sending message to API: ' . wp_json_encode( [
            'email' => $sender_email,
            'subject' => $subject,
            'category' => $category,
            'msg_length' => mb_strlen( $message ),
        ] ) );
    }

    // PRIMARY: send via wp_mail (always works, no VPS dependency)
    $send_copy    = sanitize_text_field( wp_unslash( $_POST['send_copy'] ?? 'no' ) );
    $ticket_id    = strtoupper( substr( md5( $sender_email . time() ), 0, 8 ) );
    $mail_subject = '[ParcelSelector Contact] [' . strtoupper( $category ) . '] '
                  . ( $subject ?: sprintf( /* translators: %s = sender name */ __( 'Message from %s', 'parcel-selector' ), $sender_name ) );

    $install_id   = get_option( 'parcselect_installation_id', '—' );
    $site_domain  = wp_parse_url( home_url(), PHP_URL_HOST );
    $site_name_v  = get_bloginfo( 'name' );
    $wp_ver       = get_bloginfo( 'version' );
    $wc_ver       = defined( 'WC_VERSION' ) ? WC_VERSION : '—';
    $php_ver      = phpversion();

    // ── Kategoria badge kolor ──
    $cat_colors = [
        'bug'       => '#dc2626',
        'billing'   => '#7c3aed',
        'technical' => '#2563eb',
        'feature'   => '#059669',
        'general'   => '#f97316',
        'other'     => '#6b7280',
    ];
    $cat_color = $cat_colors[ $category ] ?? '#f97316';

    // ── Wspólna funkcja HTML emaila ──
    $build_html_email = function( $for_admin ) use (
        $ticket_id, $sender_name, $sender_email, $sender_phone,
        $category, $cat_color, $subject, $message,
        $site_domain, $site_name_v, $install_id,
        $wp_ver, $wc_ver, $php_ver
    ) {
        $esc_msg     = nl2br( esc_html( $message ) );
        $esc_name    = esc_html( $sender_name );
        $esc_email   = esc_html( $sender_email );
        $esc_phone   = esc_html( $sender_phone );
        $esc_cat     = esc_html( ucfirst( $category ) );
        $esc_subject = esc_html( $subject ?: __( '(no subject)', 'parcel-selector' ) );
        $esc_domain  = esc_html( $site_domain );
        $esc_site    = esc_html( $site_name_v );
        $esc_install = esc_html( $install_id );
        $esc_wp      = esc_html( $wp_ver );
        $esc_wc      = esc_html( $wc_ver );
        $esc_php     = esc_html( $php_ver );
        $esc_ticket  = esc_html( $ticket_id );

        $header_text = $for_admin
            ? sprintf( /* translators: %s = ticket number */ __( 'New support request — Ticket #%s', 'parcel-selector' ), $esc_ticket )
            : sprintf( /* translators: %s = ticket number */ __( 'Request confirmation #%s', 'parcel-selector' ), $esc_ticket );
        $subheader = $for_admin
            ? __( 'Message from a ParcelSelector customer', 'parcel-selector' )
            : __( 'Thank you for contacting us — we will reply within 24–48h', 'parcel-selector' );

        $o  = '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"></head>';
        $o .= '<body style="margin:0;padding:0;background:#fff7ed;font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Arial,sans-serif;">';
        $o .= '<table width="100%" cellpadding="0" cellspacing="0" style="background:#fff7ed;padding:32px 16px;"><tr><td align="center">';
        $o .= '<table width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 4px 24px rgba(249,115,22,0.15);">';

        // Header gradient
        $o .= '<tr><td style="background:linear-gradient(135deg,#f97316,#f59e0b);padding:28px 40px;text-align:center;">';
        $o .= '<img src="' . esc_url( PARCSELECT_PLUGIN_URL . 'assets/icon-256x256.png' ) . '" alt="ParcelSelector" style="width:72px;height:72px;border-radius:50%;border:3px solid rgba(255,255,255,0.85);object-fit:cover;display:block;margin:0 auto 14px;">';
        $o .= '<h1 style="margin:0;color:#ffffff;font-size:21px;font-weight:700;">' . esc_html( $header_text ) . '</h1>';
        $o .= '<p style="margin:6px 0 0;color:rgba(255,255,255,0.9);font-size:13px;">' . esc_html( $subheader ) . '</p>';
        $o .= '</td></tr>';

        // Body
        $o .= '<tr><td style="padding:32px 40px;">';

        // Ticket + kategoria badges
        $o .= '<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:22px;">';
        $o .= '<span style="background:#fff7ed;color:#f97316;border:1px solid #fed7aa;font-size:12px;font-weight:700;padding:4px 12px;border-radius:20px;letter-spacing:0.5px;">Ticket #' . $esc_ticket . '</span>';
        $o .= '<span style="background:' . $cat_color . ';color:#fff;font-size:12px;font-weight:700;padding:4px 12px;border-radius:20px;">' . $esc_cat . '</span>';
        $o .= '</div>';

        // Wiadomość
        $o .= '<p style="margin:0 0 8px;color:#6b7280;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:1px;">' . esc_html__( 'Message', 'parcel-selector' );
        if ( $esc_subject ) $o .= ' — ' . $esc_subject;
        $o .= '</p>';
        $o .= '<div style="background:#f9fafb;border:1px solid #e5e7eb;border-radius:10px;padding:18px 20px;margin-bottom:24px;color:#1f2937;font-size:14px;line-height:1.75;">' . $esc_msg . '</div>';

        // Nadawca
        $o .= '<p style="margin:0 0 8px;color:#6b7280;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:1px;">' . esc_html__( 'Sender', 'parcel-selector' ) . '</p>';
        $o .= '<table cellpadding="0" cellspacing="0" style="width:100%;margin-bottom:24px;">';
        $o .= '<tr><td style="padding:4px 14px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase;letter-spacing:0.5px;white-space:nowrap;">' . esc_html__( 'Name', 'parcel-selector' ) . '</td>';
        $o .= '<td style="padding:4px 0;font-weight:600;color:#1f2937;">' . $esc_name . '</td></tr>';
        $o .= '<tr><td style="padding:4px 14px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase;letter-spacing:0.5px;">Email</td>';
        $o .= '<td style="padding:4px 0;"><a href="mailto:' . $esc_email . '" style="color:#f97316;text-decoration:none;">' . $esc_email . '</a></td></tr>';
        if ( $esc_phone ) {
            $o .= '<tr><td style="padding:4px 14px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase;letter-spacing:0.5px;">' . esc_html__( 'Phone', 'parcel-selector' ) . '</td>';
            $o .= '<td style="padding:4px 0;color:#374151;">' . $esc_phone . '</td></tr>';
        }
        $o .= '</table>';

        // Dane instalacji
        $o .= '<p style="margin:0 0 8px;color:#6b7280;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:1px;">' . esc_html__( 'Installation details', 'parcel-selector' ) . '</p>';
        $o .= '<table cellpadding="0" cellspacing="0" style="width:100%;margin-bottom:24px;">';
        $o .= '<tr><td style="padding:4px 14px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase;letter-spacing:0.5px;">' . esc_html__( 'Domain', 'parcel-selector' ) . '</td>';
        $o .= '<td style="padding:4px 0;font-weight:600;color:#1f2937;">' . $esc_domain . ' &mdash; ' . $esc_site . '</td></tr>';
        $o .= '<tr><td style="padding:4px 14px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase;letter-spacing:0.5px;">WP/WC/PHP</td>';
        $o .= '<td style="padding:4px 0;color:#6b7280;font-size:13px;">' . $esc_wp . ' / ' . $esc_wc . ' / ' . $esc_php . '</td></tr>';
        if ( $esc_install && $esc_install !== '—' ) {
            $o .= '<tr><td style="padding:4px 14px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase;letter-spacing:0.5px;">' . esc_html__( 'Installation ID', 'parcel-selector' ) . '</td>';
            $o .= '<td style="padding:4px 0;font-family:monospace;font-size:12px;color:#6b7280;">' . $esc_install . '</td></tr>';
        }
        $o .= '</table>';

        $o .= '<p style="margin:0;color:#9ca3af;font-size:12px;">' . esc_html__( 'Message sent via the ParcelSelector.com contact form', 'parcel-selector' ) . '</p>';
        $o .= '</td></tr>';

        // Footer
        $o .= '<tr><td style="background:#f9fafb;padding:16px 40px;text-align:center;border-top:1px solid #f3f4f6;">';
        $o .= '<p style="margin:0;color:#9ca3af;font-size:12px;">ParcelSelector.com &bull; <a href="https://parcelselector.com" style="color:#f97316;text-decoration:none;">parcelselector.com</a>';
        $o .= ' &bull; <a href="mailto:office@parcelselector.com" style="color:#f97316;text-decoration:none;">office@parcelselector.com</a></p>';
        $o .= '</td></tr>';
        $o .= '</table></td></tr></table></body></html>';

        return $o;
    };

    $html_to_office = $build_html_email( true );

    // Plain-text fallback
    $mail_body  = "=== " . __( 'ParcelSelector — Message to support', 'parcel-selector' ) . " ===\n\n";
    $mail_body .= __( 'Ticket ID', 'parcel-selector' ) . "     : #" . $ticket_id . "\n";
    $mail_body .= __( 'Category', 'parcel-selector' ) . "      : " . $category . "\n";
    $mail_body .= __( 'From', 'parcel-selector' ) . "          : " . $sender_name . " <" . $sender_email . ">\n";
    if ( $sender_phone ) $mail_body .= __( 'Phone', 'parcel-selector' ) . "         : " . $sender_phone . "\n";
    $mail_body .= "\n--- " . __( 'Message body', 'parcel-selector' ) . " ---\n" . $message . "\n";
    $mail_body .= "\n--- " . __( 'Installation details', 'parcel-selector' ) . " ---\n";
    $mail_body .= __( 'Domain', 'parcel-selector' ) . "        : " . $site_domain . "\n";
    $mail_body .= __( 'Shop', 'parcel-selector' ) . "          : " . $site_name_v . " (" . home_url() . ")\n";
    $mail_body .= __( 'Installation ID', 'parcel-selector' ) . " : " . $install_id . "\n";
    $mail_body .= "Plugin v      : " . PARCSELECT_VERSION . "\n";
    $mail_body .= "WP / WC / PHP : " . $wp_ver . " / " . $wc_ver . " / " . $php_ver . "\n";

    // Wyślij do nas (office@) — piękny HTML
    $sent = wp_mail(
        'office@parcelselector.com',
        $mail_subject,
        $html_to_office,
        [
            'Content-Type: text/html; charset=UTF-8',
            'Reply-To: ' . $sender_name . ' <' . $sender_email . '>',
        ]
    );

    if ( ! $sent ) {
        wp_send_json_error( [ 'message' => __( 'The message could not be sent. Please write directly to office@parcelselector.com', 'parcel-selector' ) ] );
    }

    // Wyślij kopię do klienta jeśli zaznaczył checkbox
    if ( $send_copy === 'yes' ) {
        $html_to_client = $build_html_email( false );
        wp_mail(
            $sender_email,
            sprintf( /* translators: %s = ticket number */ __( '[ParcelSelector] Request confirmation #%s', 'parcel-selector' ), $ticket_id ),
            $html_to_client,
            [ 'Content-Type: text/html; charset=UTF-8' ]
        );
    }

    // SECONDARY: VPS support endpoint (for ticketing) — only if admin opted in.
    if ( 'yes' === get_option( 'parcselect_share_diagnostics', 'no' ) ) {
        wp_remote_post( 'https://parcelselector.com/support/v1/contact', [
            'timeout'   => 8,
            'blocking'  => false,
            'headers'   => [ 'Content-Type' => 'application/json', 'User-Agent' => 'ParcelSelector/' . PARCSELECT_VERSION ],
            'body'      => wp_json_encode( $payload ),
            'sslverify' => true,
        ] );
    }

    wp_send_json_success( [
        'message'   => sprintf( /* translators: %s = ticket number */ __( 'Message sent! We will reply within 24–48h. Request number: #%s', 'parcel-selector' ), $ticket_id ),
        'ticket_id' => $ticket_id,
    ] );
}
}
