<?php
/**
 * TAB: TESTING — Kompleksowa diagnostyka i testy kompatybilności hostingu
 *
 * Sprawdza:
 *  - Środowisko PHP + WordPress + WooCommerce
 *  - Kompatybilność z restrykcyjnymi hostingami (WP Engine, Kinsta, Cloudways itp.)
 *  - Łączność z API ParcelSelector
 *  - Stan metody wysyłki i stref
 *  - Konflikty z wtyczkami
 *  - Checkout widget — czy jest w DOM (live test)
 *
 * @package ParcelSelector
 */

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

if ( ! function_exists( 'parcselect_tab_testing' ) ) :
function parcselect_tab_testing() {
    $wc_version   = class_exists( 'WooCommerce' ) ? WC()->version : null;
    $php_version  = phpversion();
    $wp_version   = get_bloginfo( 'version' );

    // ── Detect hosting environment ──────────────────────────────────────────
    $host_name    = parcselect_detect_hosting_env();
    $host_flags   = parcselect_get_hosting_flags( $host_name );

    // ── Shipping method status ───────────────────────────────────────────────
    $zones_count  = 0;
    $method_found = false;
    if ( class_exists( 'WC_Shipping_Zones' ) ) {
        $all_zones = array_merge( WC_Shipping_Zones::get_zones(), array( array( 'zone_id' => 0 ) ) );
        foreach ( $all_zones as $zdata ) {
            $zone = new WC_Shipping_Zone( $zdata['zone_id'] );
            foreach ( $zone->get_shipping_methods() as $m ) {
                if ( 'parcselect_inpost_paczkomat' === $m->id ) {
                    $method_found = true;
                    if ( 'yes' === $m->enabled ) $zones_count++;
                }
            }
        }
    }

    // ── Conflicting plugins ──────────────────────────────────────────────────
    $conflict_slugs = array(
        'flexible-shipping'          => 'WPDesk Flexible Shipping',
        'woocommerce-table-rate'     => 'Table Rate Shipping',
        'woocommerce-conditional-shipping' => 'Conditional Shipping',
        'advanced-shipping'          => 'Advanced Shipping',
        'checkoutwc'                 => 'CheckoutWC',
        'cartflows'                  => 'CartFlows',
        'woo-checkout-field-editor'  => 'Checkout Field Editor',
        'wp-rocket'                  => 'WP Rocket',
        'litespeed-cache'            => 'LiteSpeed Cache',
        'w3-total-cache'             => 'W3 Total Cache',
        'autoptimize'                => 'Autoptimize',
    );
    $active_plugins  = (array) get_option( 'active_plugins', array() );
    $found_conflicts = array();
    foreach ( $active_plugins as $pf ) {
        foreach ( $conflict_slugs as $slug => $label ) {
            if ( strpos( $pf, $slug ) !== false ) {
                $found_conflicts[] = $label;
            }
        }
    }

    // ── Translations (for testing tab) ─────────────────────────────────────
    $t = array(
        'diag_title'            => __( '🔬 Diagnostics & Hosting Compatibility', 'parcel-selector' ),
        'diag_desc'             => __( 'System checks for ParcelSelector', 'parcel-selector' ),
        'diag_env_check'        => __( 'Environment', 'parcel-selector' ),
        'diag_hosting_compat'   => __( 'Hosting Compatibility', 'parcel-selector' ),
        'diag_shipping_methods' => __( 'Shipping Method', 'parcel-selector' ),
        'diag_conflicts'        => __( 'Plugin Conflicts', 'parcel-selector' ),
        'diag_logs'             => __( 'Plugin Log', 'parcel-selector' ),
        'diag_sysinfo'          => __( 'System Info', 'parcel-selector' ),
    );
    ?>

<div class="ps-test-wrap" style="max-width:900px;">

    <!-- ════════════════════ AUTO HEALTHCHECK ════════════════════ -->
    <?php
    $hc_results = class_exists( 'Parcselect_Error_Monitor' ) ? Parcselect_Error_Monitor::run_healthcheck() : array();
    if ( ! empty( $hc_results ) ) :
        $all_ok    = true;
        $fail_count = 0;
        foreach ( $hc_results as $r ) {
            if ( 'ok' !== ( $r['status'] ?? '' ) ) { $all_ok = false; }
            if ( 'fail' === ( $r['status'] ?? '' ) ) { $fail_count++; }
        }
        $hc_color = $all_ok ? '#22c55e' : ( $fail_count > 0 ? '#ef4444' : '#f59e0b' );
        $hc_bg    = $all_ok ? '#f0fdf4' : ( $fail_count > 0 ? '#fef2f2' : '#fffbeb' );
        $hc_label = $all_ok
            ? __( 'All systems operational', 'parcel-selector' )
            : ( $fail_count > 0
                /* translators: %d: number of failed checks */
                ? sprintf( __( '%d critical issues found', 'parcel-selector' ), $fail_count )
                : __( 'Warnings detected — review below', 'parcel-selector' ) );
    ?>
    <div style="background:<?php echo esc_attr( $hc_bg ); ?>;border:2px solid <?php echo esc_attr( $hc_color ); ?>;border-radius:12px;padding:20px 24px;margin-bottom:20px;">
        <div style="display:flex;align-items:center;gap:12px;margin-bottom:14px;">
            <div style="width:14px;height:14px;border-radius:50%;background:<?php echo esc_attr( $hc_color ); ?>;flex-shrink:0;<?php echo $all_ok ? 'box-shadow:0 0 0 4px rgba(34,197,94,0.2);' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static CSS value from boolean condition. ?>"></div>
            <h3 style="margin:0;font-size:16px;font-weight:800;color:<?php echo esc_attr( $hc_color ); ?>;">
                <?php echo esc_html( $hc_label ); ?>
            </h3>
        </div>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:8px;">
            <?php foreach ( $hc_results as $key => $r ) :
                $icon = 'ok' === $r['status'] ? '&#x2705;' : ( 'fail' === $r['status'] ? '&#x274C;' : '&#x26A0;' );
            ?>
            <div style="display:flex;align-items:flex-start;gap:8px;padding:8px 12px;background:#fff;border-radius:8px;border:1px solid <?php echo esc_attr( 'ok' === $r['status'] ? '#bbf7d0' : ( 'fail' === $r['status'] ? '#fecaca' : '#fde68a' ) ); ?>;">
                <span style="font-size:14px;flex-shrink:0;"><?php echo $icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <div>
                    <div style="font-size:12px;font-weight:700;color:#0f172a;"><?php echo esc_html( $r['label'] ); ?></div>
                    <div style="font-size:11px;color:#64748b;"><?php echo esc_html( $r['message'] ?? '' ); ?></div>
                    <?php if ( ! empty( $r['fix'] ) && 'ok' !== $r['status'] ) : ?>
                        <div style="font-size:10px;color:#dc2626;margin-top:2px;font-style:italic;"><?php echo esc_html( $r['fix'] ); ?></div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <p style="margin:12px 0 0;font-size:10px;color:#94a3b8;">
            <?php echo esc_html__( 'Auto-check runs every hour. Critical failures are emailed to admin + ParcelSelector support.', 'parcel-selector' ); ?>
        </p>
    </div>
    <?php endif; ?>

    <!-- ════════════════════ HEADER ════════════════════ -->
    <div style="background:linear-gradient(135deg,#f97316,#ea580c);color:#fff;padding:24px 28px;border-radius:12px;margin-bottom:24px;">
        <h2 style="margin:0 0 4px;font-size:22px;color:#fff;"><?php echo esc_html( $t['diag_title'] ?? '🔬 Diagnostics & Hosting Compatibility' ); ?></h2>
        <p style="margin:0;opacity:0.8;font-size:14px;color:#fff;"><?php echo esc_html( $t['diag_desc'] ?? 'System checks for ParcelSelector' ); ?></p>
        <p style="margin:0;color:#ffedd5;font-size:13px;">ParcelSelector v<?php echo esc_html( PARCSELECT_VERSION ); ?> · WP <?php echo esc_html( $wp_version ); ?> · WC <?php echo esc_html( $wc_version ?: 'N/A' ); ?> · PHP <?php echo esc_html( $php_version ); ?></p>
    </div>

    <!-- ════════════════════ MANUAL MAP TEST ════════════════════ -->
    <div class="ps-test-section">
        <h3 class="ps-test-section-title">🗺️ Manual Map Engine Test</h3>
        <p style="color:#64748b;font-size:13px;margin:0 0 16px;">Click to open the map directly — bypasses checkout to test map engine independently.</p>
        <div id="ps-map-test-area" style="display:flex;gap:12px;flex-wrap:wrap;">
            <button type="button" class="ps-test-btn-primary" onclick="parcselectAdminOpenAnunaki()">🟢 Test ANUNAKI Map</button>
            <button type="button" class="ps-test-btn-outline" onclick="parcselectAdminOpenClassic()">🔵 Test Classic Map</button>
        </div>
        <div id="ps-popup-root" style="position:relative;z-index:999999;"></div>
    </div>

    <!-- ════════════════════ QUICK TEST CART ════════════════════ -->
    <div class="ps-test-section">
        <h3 class="ps-test-section-title">🧪 Quick InPost shipping method test</h3>
        <p style="color:#64748b;font-size:13px;margin:0 0 12px;">Automatically adds products to the cart, sets the shipping address to Warsaw and opens checkout in a new tab — ready to test InPost.</p>
        <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px 16px;margin-bottom:14px;font-size:12px;color:#475569;font-family:monospace;">
            <strong style="color:#1e293b;font-family:sans-serif;">Test data:</strong><br>
            Jan Kowalski · office@parcelselector.com · +48 123 456 789<br>
            ul. Złota 7, 00-821 Warszawa, Poland
        </div>
        <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:12px;">
            <button type="button" id="ps-quick-test-btn" class="ps-test-btn-primary">
                🚀 Prepare cart and open checkout
            </button>
        </div>
        <div id="ps-quick-test-result" style="display:none;font-size:13px;padding:8px 12px;border-radius:6px;"></div>
    </div>

    <!-- ════════════════════ LIVE DOM TEST ════════════════════ -->
    <div class="ps-test-section">
        <h3 class="ps-test-section-title">🔴 Live Checkout Test</h3>
        <p style="color:#64748b;font-size:13px;margin:0 0 16px;">Open your checkout page in a new tab, select InPost as shipping method, then come back and click the button below to validate the DOM state.</p>
        <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:16px;">
            <a href="<?php echo esc_url( wc_get_checkout_url() ); ?>" target="_blank" class="ps-test-btn-outline">
                🛒 Open Checkout Page
            </a>
            <button type="button" id="ps-run-full-diag" class="ps-test-btn-primary">
                ⚡ Run Full Diagnostics
            </button>
            <button type="button" id="ps-copy-report" class="ps-test-btn-outline" style="display:none;">
                📋 Copy Report
            </button>
        </div>
        <div id="ps-diag-result" style="display:none;"></div>
    </div>

    <!-- ════════════════════ CONFLICTS ════════════════════ -->
    <div class="ps-test-section">
        <h3 class="ps-test-section-title">⚔️ Plugin Conflicts</h3>
        <?php if ( empty( $found_conflicts ) ) : ?>
            <div class="ps-test-ok-banner">✅ No known conflicting plugins detected.</div>
        <?php else : ?>
            <div class="ps-test-warn-banner">
                ⚠️ <?php echo absint( count( $found_conflicts ) ); ?> potentially conflicting plugin(s) active:
                <strong><?php echo esc_html( implode( ', ', $found_conflicts ) ); ?></strong>
            </div>
            <div class="ps-test-notes">
                <strong>What this means:</strong>
                <ul style="margin:8px 0 0 16px;">
                    <li>Shipping plugins (Flexible Shipping, Table Rate) may intercept WC shipping rendering — our widget injection JS layers will compensate.</li>
                    <li>Cache plugins (WP Rocket, LiteSpeed, W3TC) may defer or minify ps-wc-bridge.js — add it to your cache plugin's exclusion list.</li>
                    <li>Checkout builders (CartFlows, CheckoutWC) replace the checkout template — the widget may appear in a fallback position (before place-order button).</li>
                </ul>
            </div>
        <?php endif; ?>
    </div>

    <?php
    // Same-origin admin-ajax proxy (avoids a cross-origin/CORS fetch to the VPS API).
    $_ps_api = admin_url( 'admin-ajax.php' ) . '?action=parcselect_get_points&nonce=' . wp_create_nonce( 'parcselect_points_public' ) . '&country=';

    // ── Styles ──
    wp_enqueue_style( 'parcselect-leaflet-css', PARCSELECT_PLUGIN_URL . 'assets/vendor/leaflet/leaflet.css', array(), PARCSELECT_VERSION );
    wp_enqueue_style( 'parcselect-markercluster-css', PARCSELECT_PLUGIN_URL . 'assets/vendor/markercluster/MarkerCluster.css', array(), PARCSELECT_VERSION );
    wp_enqueue_style( 'parcselect-markercluster-default-css', PARCSELECT_PLUGIN_URL . 'assets/vendor/markercluster/MarkerCluster.Default.css', array(), PARCSELECT_VERSION );
    wp_enqueue_style( 'parcselect-classic-intro-css', PARCSELECT_PLUGIN_URL . 'map/classic/css/intro-popup.css', array(), PARCSELECT_VERSION );
    wp_enqueue_style( 'parcselect-anunaki-popup-css', PARCSELECT_PLUGIN_URL . 'map/anunaki/css/anunaki-popup.css', array(), PARCSELECT_VERSION );

    // ── Vendor scripts ──
    wp_enqueue_script( 'parcselect-leaflet', PARCSELECT_PLUGIN_URL . 'assets/vendor/leaflet/leaflet.js', array(), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-markercluster', PARCSELECT_PLUGIN_URL . 'assets/vendor/markercluster/leaflet.markercluster.js', array( 'parcselect-leaflet' ), PARCSELECT_VERSION, true );

    // ── Config inline script ──
    wp_add_inline_script( 'parcselect-markercluster', 'window.inpostPopupConfig = { initialPointsLimit: 1000, lazyLoadOnZoom: true, viewportCulling: false };
    window.parcselectCacheConfig = { enabled: false, baseUrl: ' . wp_json_encode( wp_upload_dir()['baseurl'] . '/inpost-cache/' ) . ', epicZoomEnabled: true,
        countryModes: { pl:"api",it:"api",fr:"api",es:"api",gb:"api",de:"api",be:"api",nl:"api",pt:"api",at:"api",hr:"api" } };' );

    // ── Mobile detect + search libs ──
    wp_enqueue_script( 'parcselect-mobile-detect', PARCSELECT_PLUGIN_URL . 'map/Mobilki/ps-mobile-detect.js', array(), PARCSELECT_VERSION, true );
    // flexsearch.bundle.js intentionally NOT loaded (no script uses the FlexSearch global;
    // search-engine.js is self-contained; the shipped vendor bundle has a syntax error).
    wp_enqueue_script( 'parcselect-classic-search', PARCSELECT_PLUGIN_URL . 'map/classic/js/search-engine.js', array(), PARCSELECT_VERSION, true );
    // CLASSIC countries — defines IPS_COUNTRIES and routes its point API through the
    // same-origin admin-ajax proxy (avoids cross-origin fetch to the VPS API → CORS).
    wp_enqueue_script( 'parcselect-classic-countries', PARCSELECT_PLUGIN_URL . 'map/classic/js/countries.js', array(), PARCSELECT_VERSION, true );
    wp_localize_script( 'parcselect-classic-countries', 'parcselectClassicConfig', array( 'apiBase' => $_ps_api ) );
    wp_enqueue_script( 'parcselect-classic-intro', PARCSELECT_PLUGIN_URL . 'map/classic/js/intro-popup.js', array( 'parcselect-leaflet', 'parcselect-markercluster', 'parcselect-classic-countries' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-classic-selector', PARCSELECT_PLUGIN_URL . 'map/classic/js/parcel-locker-selector.js', array( 'parcselect-classic-intro' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-fuse', PARCSELECT_PLUGIN_URL . 'assets/vendor/fuse/fuse.min.js', array(), PARCSELECT_VERSION, true );

    // ── ANUNAKI engine ──
    wp_enqueue_script( 'parcselect-anunaki-countries', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-countries.js', array(), PARCSELECT_VERSION, true );
    wp_localize_script( 'parcselect-anunaki-countries', 'parcselectAnunakiConfig', array(
        'flagBaseW20' => PARCSELECT_PLUGIN_URL . 'assets/flags/20x15/',
        'flagBaseW40' => PARCSELECT_PLUGIN_URL . 'assets/flags/w40/',
        'mascotUrl'   => PARCSELECT_PLUGIN_URL . 'assets/images/Parcel_Selector_Com.jpg',
    ) );
    wp_add_inline_script( 'parcselect-anunaki-countries', '(function(){ var c=window.ANUNAKI_COUNTRIES||{}; var b=' . wp_json_encode( $_ps_api ) . '; Object.keys(c).forEach(function(cc){c[cc].api=b+cc;}); })();' );
    wp_enqueue_script( 'parcselect-anunaki-translations', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-translations.js', array( 'parcselect-anunaki-countries' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-anunaki-search', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-search.js', array( 'parcselect-anunaki-translations' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-anunaki-popup', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-popup.js', array( 'parcselect-anunaki-search', 'parcselect-leaflet', 'parcselect-markercluster' ), PARCSELECT_VERSION, true );
    ?>

    <!-- ════════════════════ NAVIGATION ════════════════════ -->
    <nav class="ps-test-nav">
        <a href="#env" class="active"><?php echo esc_html( $t['diag_env_check'] ); ?></a>
        <a href="#hosting"><?php echo esc_html( $t['diag_hosting_compat'] ); ?></a>
        <a href="#shipping"><?php echo esc_html( $t['diag_shipping_methods'] ); ?></a>
        <a href="#conflicts"><?php echo esc_html( $t['diag_conflicts'] ); ?></a>
        <a href="#logs"><?php echo esc_html( $t['diag_logs'] ); ?></a>
        <a href="#sysinfo"><?php echo esc_html( $t['diag_sysinfo'] ); ?></a>
    </nav>

    <!-- ════════════════════ ENVIRONMENT ════════════════════ -->
    <div class="ps-test-section" id="env">
        <h3 class="ps-test-section-title">🖥️ Environment</h3>
        <div class="ps-test-grid">
            <?php parcselect_test_row( 'WordPress', $wp_version, version_compare( $wp_version, '5.8', '>=' ), 'Minimum 5.8 required. Recommended 6.0+.' ); ?>
            <?php parcselect_test_row( 'WooCommerce', $wc_version ?: 'NOT FOUND', ! empty( $wc_version ), 'WooCommerce 5.0+ required. Recommended 8.0+ for Blocks support.' ); ?>
            <?php parcselect_test_row( 'PHP', $php_version, version_compare( $php_version, '7.4', '>=' ), 'PHP 7.4+ required. 8.1+ recommended for performance.' ); ?>
            <?php parcselect_test_row( 'HPOS Enabled', parcselect_test_hpos_status(), null, 'High Performance Order Storage (WC 7.1+). Plugin is fully compatible.' ); ?>
            <?php parcselect_test_row( 'WC Blocks Checkout', parcselect_test_blocks_checkout(), null, 'Detects if site uses block-based checkout (WC 8.3+).' ); ?>
            <?php parcselect_test_row( 'Hosting', $host_name, null, 'Detected hosting environment for compatibility notes.' ); ?>
            <?php parcselect_test_row( 'PHP Memory Limit', ini_get('memory_limit'), parcselect_memory_ok(), 'Minimum 128MB. 256MB recommended.' ); ?>
            <?php parcselect_test_row( 'Max Execution Time', ini_get('max_execution_time') . 's', (int)ini_get('max_execution_time') >= 30 || (int)ini_get('max_execution_time') === 0, 'Minimum 30s needed for shipping zone setup. 0 = unlimited.' ); ?>
        </div>
    </div>

    <!-- ════════════════════ HOSTING COMPATIBILITY ════════════════════ -->
    <div class="ps-test-section" id="hosting">
        <h3 class="ps-test-section-title">🏠 Hosting Compatibility</h3>
        <?php if ( ! empty( $host_flags ) ) : ?>
        <div class="ps-test-host-banner ps-test-host-<?php echo esc_attr( $host_flags['severity'] ); ?>">
            <?php echo esc_html( $host_flags['banner'] ); ?>
        </div>
        <?php endif; ?>
        <div class="ps-test-grid">
            <?php parcselect_test_row( 'cURL Extension', function_exists( 'curl_version' ) ? 'Available' : 'MISSING', function_exists( 'curl_version' ), 'Required for outbound HTTP requests to ParcelSelector API.' ); ?>
            <?php parcselect_test_row( 'wp_remote_get()', 'Available', true, 'WordPress HTTP API used for all external requests.' ); ?>
            <?php parcselect_test_row( 'SSL/TLS', parcselect_test_ssl(), parcselect_test_ssl() !== 'FAIL', 'All API calls use HTTPS. SSL must be verifiable.' ); ?>
            <?php parcselect_test_row( 'WP-Cron', defined('DISABLE_WP_CRON') && DISABLE_WP_CRON ? 'Disabled (external cron)' : 'Enabled', true, 'Plugin uses wp_cron for daily license sync. External cron is fine.' ); ?>
            <?php parcselect_test_row( 'gethostbyname()', function_exists('gethostbyname') ? 'Available' : 'Disabled (handled gracefully)', true, 'Used in diagnostics only — not required for plugin operation.' ); ?>
            <?php parcselect_test_row( 'JSON Extension', extension_loaded('json') ? 'Available' : 'MISSING', extension_loaded('json'), 'Required for API communication.' ); ?>
            <?php parcselect_test_row( 'Outbound HTTP', '<span id="ps-outbound-status">⏳ Testing...</span>', null, 'Tests real HTTP connection to parcelselector.com API.' ); ?>
        </div>

        <?php if ( ! empty( $host_flags['notes'] ) ) : ?>
        <div class="ps-test-notes">
            <strong>📋 <?php echo esc_html( $host_name ); ?> — specific notes:</strong>
            <ul style="margin:8px 0 0 16px;">
            <?php foreach ( $host_flags['notes'] as $note ) : ?>
                <li style="margin-bottom:4px;"><?php echo esc_html( $note ); ?></li>
            <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
    </div>

    <!-- ════════════════════ SHIPPING METHOD ════════════════════ -->
    <div class="ps-test-section" id="shipping">
        <h3 class="ps-test-section-title">📦 Shipping Method</h3>
        <div class="ps-test-grid">
            <?php parcselect_test_row( 'Class loaded', class_exists( 'Parcselect_Shipping_Method') ? 'Parcselect_Shipping_Method ✓' : 'NOT LOADED', class_exists( 'Parcselect_Shipping_Method'), 'Parcselect_Shipping_Method must be loaded via woocommerce_shipping_init.' ); ?>
            <?php parcselect_test_row( 'Registered in WC', $method_found ? 'Yes' : 'NO — not in any zone', $method_found, 'Go to WooCommerce → Settings → Shipping → Zones to add it.' ); ?>
            <?php parcselect_test_row( 'Enabled zones', $zones_count . ' zone(s)', $zones_count > 0, 'Method must be enabled (not just added) in at least one zone.' ); ?>
            <?php parcselect_test_row( 'Default country', strtoupper( get_option('parcselect_default_country', 'pl') ), true, 'Default country shown on map when shipping address is empty.' ); ?>
            <?php parcselect_test_row( 'Map engine', strtoupper( get_option('parcselect_map_engine', 'classic') ), true, 'ANUNAKI = live API (recommended). CLASSIC = local data files.' ); ?>
            <?php
            /* WP.org FREE — always active, no license needed */
            parcselect_test_row( 'Plugin status', 'FREE — Active, Unlimited', true, 'Free version is always active with no restrictions.' );
            ?>
        </div>
    </div>

    <!-- ════════════════════ LOG VIEWER ════════════════════ -->
    <div class="ps-test-section">
        <h3 class="ps-test-section-title">📋 Plugin Log (last 50 lines)</h3>
        <p style="color:#64748b;font-size:13px;margin:0 0 12px;">Recent plugin activity from the WooCommerce logger. Click "Refresh" to reload.</p>
        <textarea id="ps-log-viewer" readonly style="width:100%;height:200px;font-family:monospace;font-size:11px;background:#1e293b;color:#94a3b8;padding:14px;border:none;border-radius:8px;resize:vertical;"><?php
            $log_content = '';
            $log_dir = WC_LOG_DIR;
            if ( is_dir( $log_dir ) ) {
                $log_files = glob( $log_dir . 'parcel-selector-*.log' );
                if ( $log_files ) {
                    // Use the most recently modified log file
                    usort( $log_files, static function( $a, $b ) { return filemtime( $b ) - filemtime( $a ); } );
                    $last_file  = $log_files[0];
                    $lines      = file( $last_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
                    if ( $lines ) {
                        $last50     = array_slice( $lines, -50 );
                        $log_content = implode( "\n", $last50 );
                    }
                }
            }
            echo esc_textarea( $log_content ?: '(No log entries yet — plugin writes to log when processing orders and background tasks.)' );
        ?></textarea>
        <div style="display:flex;gap:8px;margin-top:8px;">
            <button type="button" id="ps-log-refresh-btn" class="ps-test-btn-outline">🔄 Refresh</button>
            <button type="button" onclick="var t=document.getElementById('ps-log-viewer');t.select();document.execCommand('copy');this.textContent='✅ Copied!';" class="ps-test-btn-outline">📋 Copy</button>
        </div>
    </div>

    <!-- ════════════════════ SYSTEM INFO (copyable) ════════════════════ -->
    <div class="ps-test-section">
        <h3 class="ps-test-section-title">📄 System Info (for support)</h3>
        <p style="color:#64748b;font-size:13px;margin:0 0 12px;">Copy this and paste it when contacting support.</p>
        <textarea id="ps-sysinfo" readonly style="width:100%;height:160px;font-family:monospace;font-size:11px;background:#1e293b;color:#94a3b8;padding:14px;border:none;border-radius:8px;resize:vertical;"><?php echo esc_textarea( parcselect_generate_sysinfo() ); ?></textarea>
        <button type="button" onclick="document.getElementById('ps-sysinfo').select();document.execCommand('copy');this.textContent='✅ Copied!';" class="ps-test-btn-outline" style="margin-top:8px;">📋 Copy to clipboard</button>
    </div>

</div><!-- .ps-test-wrap -->

<?php
wp_add_inline_style( 'parcselect-admin-premium-css', '
.ps-test-wrap * { box-sizing: border-box; }
.ps-test-section { background:#fff; border:1px solid #e2e8f0; border-radius:10px; padding:20px 24px; margin-bottom:20px; }
.ps-test-section-title { margin:0 0 16px; font-size:15px; font-weight:700; color:#1e293b; border-bottom:1px solid #f1f5f9; padding-bottom:10px; }
.ps-test-grid { display:grid; grid-template-columns:1fr; gap:0; }
.ps-test-row { display:grid; grid-template-columns:200px 1fr auto; align-items:start; gap:12px; padding:9px 0; border-bottom:1px solid #f8fafc; font-size:13px; }
.ps-test-row:last-child { border-bottom:none; }
.ps-test-row-label { font-weight:600; color:#374151; }
.ps-test-row-value { color:#1e293b; }
.ps-test-row-hint { font-size:11px; color:#94a3b8; max-width:240px; text-align:right; }
.ps-test-ok    { color:#16a34a; font-weight:600; }
.ps-test-fail  { color:#dc2626; font-weight:600; }
.ps-test-warn  { color:#d97706; font-weight:600; }
.ps-test-info  { color:#2563eb; }
.ps-test-ok-banner   { background:#f0fdf4; border:1px solid #86efac; color:#166534; padding:10px 14px; border-radius:6px; font-size:13px; }
.ps-test-warn-banner { background:#fffbeb; border:1px solid #fcd34d; color:#92400e; padding:10px 14px; border-radius:6px; font-size:13px; margin-bottom:12px; }
.ps-test-notes { background:#f8fafc; border-left:3px solid #94a3b8; padding:10px 14px; font-size:12px; color:#475569; border-radius:0 6px 6px 0; }
.ps-test-btn-primary { background:#f97316; color:#fff; border:none; padding:9px 18px; border-radius:6px; font-size:13px; font-weight:600; cursor:pointer; }
.ps-test-btn-primary:hover { background:#ea580c; }
.ps-test-btn-outline { background:#fff7ed; color:#c2410c; border:2px solid #f97316; padding:9px 18px; border-radius:6px; font-size:13px; font-weight:600; cursor:pointer; text-decoration:none; display:inline-block; }
.ps-test-btn-outline:hover { background:#ffedd5; }
.ps-test-host-banner { padding:10px 14px; border-radius:6px; font-size:13px; margin-bottom:12px; }
.ps-test-host-ok   { background:#f0fdf4; border:1px solid #86efac; color:#166534; }
.ps-test-host-warn { background:#fffbeb; border:1px solid #fcd34d; color:#92400e; }
.ps-test-host-info { background:#eff6ff; border:1px solid #93c5fd; color:#1e40af; }
#ps-diag-result { background:#0f172a; color:#e2e8f0; font-family:monospace; font-size:12px; padding:16px; border-radius:8px; line-height:1.7; white-space:pre-wrap; }
' );
?>

<?php
    // Localize nonces and config for diagnostics JS
    wp_localize_script( 'parcselect-admin-premium-js', 'parcselectDiagVars', array(
        'nonces' => array(
            'prepare_test_cart' => wp_create_nonce( 'parcselect_prepare_test_cart' ),
            'test_api'          => wp_create_nonce( 'parcselect_test_api' ),
            'full_diag'         => wp_create_nonce( 'parcselect_full_diag' ),
            'get_log_tail'      => wp_create_nonce( 'parcselect_get_log_tail' ),
        ),
        'defaultCountry' => get_option( 'parcselect_default_country', 'pl' ),
    ) );

    wp_add_inline_script( 'parcselect-admin-premium-js', 'jQuery(document).ready(function($) {
    $("#ps-quick-test-btn").on("click", function() {
        var $btn = $(this);
        var $res = $("#ps-quick-test-result");
        $btn.prop("disabled", true).text("\u23F3 Preparing...");
        $res.hide();
        var newTab = window.open("about:blank", "_blank");
        $.ajax({
            url: ajaxurl, method: "POST",
            data: { action: "ps_prepare_test_cart", nonce: parcselectDiagVars.nonces.prepare_test_cart },
            success: function(r) {
                $btn.prop("disabled", false).text("\uD83D\uDE80 Prepare cart and open checkout");
                if (r.success && r.data && r.data.checkout_url) {
                    $res.css({"background":"#f0fdf4","border":"1px solid #86efac","color":"#166534"})
                        .html("\u2705 Koszyk gotowy! Checkout otwarty w nowej karcie.").show();
                    if (newTab) { newTab.location.href = r.data.checkout_url; }
                    else { $res.html("\u2705 Cart ready! <a href=\"" + r.data.checkout_url + "\" target=\"_blank\">Open checkout</a> (popup blocked by browser)."); }
                } else {
                    if (newTab) { newTab.close(); }
                    $res.css({"background":"#fff1f1","border":"1px solid #fca5a5","color":"#991b1b"})
                        .text("\u274C " + (r.data && r.data.message ? r.data.message : "Error \u2014 no products or WC unavailable.")).show();
                }
            },
            error: function(xhr) {
                if (newTab) { newTab.close(); }
                $btn.prop("disabled", false).text("\uD83D\uDE80 Prepare cart and open checkout");
                $res.css({"background":"#fff1f1","border":"1px solid #fca5a5","color":"#991b1b"})
                    .text("\u274C Connection error: " + xhr.status).show();
            },
            timeout: 20000
        });
    });

    // Outbound API connectivity test was removed for WP.org compliance \u2014
    // plugin must not call internal /license/* endpoints without explicit
    // user consent for each request. WordPress core handles update checks.
    (function(){ var el = document.getElementById("ps-outbound-status"); if (el) { el.innerHTML = "(disabled in distribution build)"; el.style.color = "#94a3b8"; } })();

    $("#ps-run-full-diag").on("click", function() {
        var $btn = $(this);
        $btn.prop("disabled", true).text("\u23F3 Running...");
        $.ajax({
            url: ajaxurl, method: "POST",
            data: { action: "ps_run_full_diagnostics", nonce: parcselectDiagVars.nonces.full_diag },
            success: function(r) {
                var $out = $("#ps-diag-result"); $out.show();
                if (r.success && r.data && r.data.report) { $out.text(r.data.report); }
                else { $out.text("Error: " + JSON.stringify(r)); }
                $("#ps-copy-report").show();
                $btn.prop("disabled", false).text("\u26A1 Run Full Diagnostics");
            },
            error: function(xhr) {
                $("#ps-diag-result").show().text("Connection error: " + xhr.status + " " + xhr.statusText);
                $btn.prop("disabled", false).text("\u26A1 Run Full Diagnostics");
            },
            timeout: 30000
        });
    });

    $("#ps-copy-report").on("click", function() {
        var text = document.getElementById("ps-diag-result").textContent;
        if (navigator.clipboard) { navigator.clipboard.writeText(text).then(function() { document.getElementById("ps-copy-report").textContent = "\u2705 Copied!"; }); }
    });

    $("#ps-log-refresh-btn").on("click", function() {
        var $btn = $(this); $btn.text("\u23F3 Loading...");
        $.post(ajaxurl, { action: "ps_get_log_tail", nonce: parcselectDiagVars.nonces.get_log_tail })
         .done(function(r) { if (r.success) { $("#ps-log-viewer").val(r.data.log); } $btn.text("\uD83D\uDD04 Refresh"); })
         .fail(function() { $btn.text("\uD83D\uDD04 Refresh"); });
    });

    // Update notifications are delivered by WordPress.org core; the legacy custom
    // "Check for updates" link/AJAX was removed for plugin-directory compliance.
});

window.parcselectAdminOpenAnunaki = function() {
    var country = parcselectDiagVars.defaultCountry;
    if (window.AnunakiPopup && typeof AnunakiPopup.open === "function") { AnunakiPopup.open(country); }
    else { console.error("[PS] AnunakiPopup nie zaladowany"); }
};
window.parcselectAdminOpenClassic = function() {
    var country = parcselectDiagVars.defaultCountry;
    document.dispatchEvent(new CustomEvent("inpost-open-map", { detail: { country: country } }));
};' );

}
endif; // parcelselector_tab_testing


// ═══════════════════════════════════════════════════════════════════════════════
// Helper functions for the testing tab
// ═══════════════════════════════════════════════════════════════════════════════

if ( ! function_exists( 'parcselect_test_row' ) ) {
function parcselect_test_row( $label, $value, $ok, $hint = '' ) {
    if ( $ok === true ) {
        $cls = 'ps-test-ok';
    } elseif ( $ok === false ) {
        $cls = 'ps-test-fail';
    } else {
        $cls = 'ps-test-info'; // null = informational
    }
    echo '<div class="ps-test-row">';
    echo '<span class="ps-test-row-label">' . esc_html( $label ) . '</span>';
    echo '<span class="ps-test-row-value ' . esc_attr( $cls ) . '">' . wp_kses_post( $value ) . '</span>';
    if ( $hint ) {
        echo '<span class="ps-test-row-hint">' . esc_html( $hint ) . '</span>';
    }
    echo '</div>';
}
}

if ( ! function_exists( 'parcselect_detect_hosting_env' ) ) {
function parcselect_detect_hosting_env() {
    $checks = array(
        'wpengine'       => array( 'IS_WPE', 'WPE_APIKEY' ),
        'kinsta'         => array( 'KINSTA_ENVIRONMENT_NAME', 'KINSTA_CACHE_ZONE' ),
        'flywheel'       => array( 'FLYWHEEL_CONFIG_PATH' ),
        'cloudways'      => array( 'CLOUDWAYS_HOSTING' ),
        'siteground'     => array( 'SiteGround' ),
        'wpcloud'        => array( 'WPVIP_ENVIRONMENT' ),
        'pantheon'       => array( 'PANTHEON_ENVIRONMENT' ),
        'pressable'      => array( 'PRESSABLE_ENVIRONMENT' ),
    );
    foreach ( $checks as $host => $constants ) {
        foreach ( $constants as $c ) {
            if ( defined( $c ) ) return ucfirst( $host );
        }
    }
    // Server software detection
    $sw = isset( $_SERVER['SERVER_SOFTWARE'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) ) : '';
    if ( strpos( $sw, 'litespeed' ) !== false ) return 'LiteSpeed Server';
    if ( strpos( $sw, 'nginx' ) !== false ) return 'Nginx';
    if ( strpos( $sw, 'apache' ) !== false ) return 'Apache';
    return 'Generic / Unknown';
}
}

if ( ! function_exists( 'parcselect_get_hosting_flags' ) ) {
function parcselect_get_hosting_flags( $host ) {
    $flags = array(
        'wpengine' => array(
            'severity' => 'warn',
            'banner'   => '⚠️ WP Engine detected — managed hosting with specific restrictions.',
            'notes'    => array(
                'Outbound HTTP timeout is capped at 10s — plugin uses 10s max.',
                'Add ps-wc-bridge.js to WP Engine\'s JS exclusion list in the caching panel.',
                'Object cache is aggressive — test checkout after clearing cache.',
                'usleep() and sleep() are blocked — plugin does not use them.',
                'External cron is recommended — WP-Cron may be unreliable on WP Engine.',
            ),
        ),
        'kinsta' => array(
            'severity' => 'warn',
            'banner'   => '⚠️ Kinsta detected — Nginx + Redis stack with strict caching.',
            'notes'    => array(
                'Add checkout and cart pages to Kinsta\'s cache exclusion rules.',
                'Redis object cache may cache WC sessions — test locker selection persistence.',
                'Add ps-wc-bridge.js to Kinsta\'s JavaScript defer exclusion.',
                'Outbound HTTP works normally — no timeout restrictions.',
            ),
        ),
        'flywheel' => array(
            'severity' => 'warn',
            'banner'   => '⚠️ Flywheel / Local detected.',
            'notes'    => array(
                'Flywheel caches checkout pages aggressively — exclude /checkout/ and /cart/ from cache.',
                'Plugin operates normally on Flywheel infrastructure.',
            ),
        ),
        'cloudways' => array(
            'severity' => 'info',
            'banner'   => 'ℹ️ Cloudways detected — Breeze cache plugin may defer scripts.',
            'notes'    => array(
                'In Breeze settings, add ps-wc-bridge.js to excluded JS files.',
                'Varnish cache: add BYPASS rules for /checkout/ and /cart/ URLs.',
            ),
        ),
        'wpcloud' => array(
            'severity' => 'warn',
            'banner'   => '⚠️ WordPress.com VIP detected — highly restrictive environment.',
            'notes'    => array(
                'Many functions restricted — plugin may require code review approval.',
                'wp_remote_get() with external URLs requires domain allowlist approval.',
                'usleep() is blocked — plugin does not use it (confirmed).',
            ),
        ),
    );
    $key = strtolower( str_replace( ' ', '', $host ) );
    foreach ( $flags as $k => $v ) {
        if ( strpos( $key, $k ) !== false ) return $v;
    }
    return array( 'severity' => 'ok', 'banner' => '✅ No known hosting restrictions detected.', 'notes' => array() );
}
}

if ( ! function_exists( 'parcselect_test_hpos_status' ) ) {
function parcselect_test_hpos_status() {
    if ( ! class_exists( 'Automattic\\WooCommerce\\Utilities\\FeaturesUtil' ) ) {
        return 'WC too old (< 7.1)';
    }
    $enabled = \Automattic\WooCommerce\Utilities\FeaturesUtil::feature_is_enabled( 'custom_order_tables' );
    return $enabled ? '✅ Enabled (plugin compatible)' : 'Disabled (classic posts)';
}
}

if ( ! function_exists( 'parcselect_test_blocks_checkout' ) ) {
function parcselect_test_blocks_checkout() {
    $checkout_page_id = wc_get_page_id( 'checkout' );
    if ( $checkout_page_id <= 0 ) return 'Checkout page not set';
    $content = get_post_field( 'post_content', $checkout_page_id );
    if ( has_block( 'woocommerce/checkout', $content ) ) {
        return '✅ Block-based checkout (WC Blocks)';
    }
    return 'Classic shortcode checkout';
}
}

if ( ! function_exists( 'parcselect_test_ssl' ) ) {
function parcselect_test_ssl() {
    $r = wp_remote_get( 'https://parcelselector.com/', array( 'timeout' => 5, 'sslverify' => true ) );
    if ( is_wp_error( $r ) ) return 'FAIL: ' . $r->get_error_message();
    return 'OK (verified)';
}
}

if ( ! function_exists( 'parcselect_memory_ok' ) ) {
function parcselect_memory_ok() {
    $limit = ini_get( 'memory_limit' );
    if ( '-1' === $limit ) return true;
    $bytes = wp_convert_hr_to_bytes( $limit );
    return $bytes >= 128 * 1024 * 1024;
}
}

if ( ! function_exists( 'parcselect_generate_sysinfo' ) ) {
function parcselect_generate_sysinfo() {
    $wc = class_exists('WooCommerce') ? WC()->version : 'N/A';
    $lines = array(
        '=== ParcelSelector System Info ===',
        'Generated: ' . gmdate('Y-m-d H:i:s') . ' UTC',
        '',
        '--- Plugin ---',
        'Version: ' . PARCSELECT_VERSION,
        'Edition: Free',
        'Map Engine: ' . get_option('parcselect_map_engine','classic'),
        'Default Country: ' . get_option('parcselect_default_country','pl'),
        '',
        '--- WordPress ---',
        'WP Version: ' . get_bloginfo('version'),
        'WC Version: ' . $wc,
        'PHP Version: ' . phpversion(),
        'PHP Memory: ' . ini_get('memory_limit'),
        'Max Exec Time: ' . ini_get('max_execution_time') . 's',
        '',
        '--- Hosting ---',
        'Detected Host: ' . parcselect_detect_hosting_env(),
        'Server SW: ' . ( isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : 'N/A' ),
        'HTTPS: ' . ( is_ssl() ? 'Yes' : 'No' ),
        '',
        '--- Shipping ---',
        'Method Class: ' . ( class_exists( 'Parcselect_Shipping_Method') ? 'Loaded' : 'NOT LOADED' ),
        'HPOS: ' . parcselect_test_hpos_status(),
        'Blocks Checkout: ' . parcselect_test_blocks_checkout(),
        '',
        '--- Active Plugins (shipping/cache) ---',
    );
    $conflict_slugs = array('flexible-shipping','table-rate','cartflows','checkoutwc','wp-rocket','litespeed-cache','w3-total-cache','autoptimize','siteground-optimizer');
    foreach ( (array) get_option('active_plugins',[]) as $p ) {
        foreach ( $conflict_slugs as $s ) {
            if ( strpos($p,$s) !== false ) $lines[] = '  - ' . $p;
        }
    }
    $lines[] = '';
    $lines[] = '--- Installation ID ---';
    $lines[] = get_option('parcselect_installation_id','N/A');
    return implode("\n", $lines);
}
}

// ─── AJAX: Full diagnostics report ──────────────────────────────────────────
add_action( 'wp_ajax_parcselect_run_full_diagnostics', 'parcselect_ajax_run_full_diagnostics' );

if ( ! function_exists( 'parcselect_ajax_run_full_diagnostics' ) ) {
function parcselect_ajax_run_full_diagnostics() {
    check_ajax_referer( 'parcselect_full_diag', 'nonce' );
    if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

    $report = array();
    $report[] = '╔══════════════════════════════════════════╗';
    $report[] = '║  ParcelSelector Full Diagnostics Report  ║';
    $report[] = '╚══════════════════════════════════════════╝';
    $report[] = 'Timestamp: ' . gmdate('Y-m-d H:i:s') . ' UTC';
    $report[] = '';

    // 1. WC Session check
    $report[] = '[ WC Session ]';
    $session_ok = function_exists('WC') && WC()->session ? 'OK' : 'UNAVAILABLE (admin context)';
    $report[] = '  Status: ' . $session_ok;
    $report[] = '';

    // 2. Shipping zones
    $report[] = '[ Shipping Zones ]';
    if ( class_exists('WC_Shipping_Zones') ) {
        $zones = array_merge( WC_Shipping_Zones::get_zones(), array( array('zone_id'=>0) ) );
        $ps_zones = array();
        foreach ( $zones as $zd ) {
            $z = new WC_Shipping_Zone( $zd['zone_id'] );
            foreach ( $z->get_shipping_methods() as $m ) {
                if ( 'parcselect_inpost_paczkomat' === $m->id ) {
                    $ps_zones[] = sprintf('  Zone #%d "%s" — enabled: %s', $z->get_id(), $z->get_zone_name(), $m->enabled);
                }
            }
        }
        if ( empty($ps_zones) ) {
            $report[] = '  ❌ InPost method NOT found in any zone!';
        } else {
            foreach ( $ps_zones as $line ) $report[] = $line;
        }
    } else {
        $report[] = '  WC_Shipping_Zones not available';
    }
    $report[] = '';

    // 3. API connectivity report deliberately omitted in the WP.org distribution
    // — outbound requests are gated by the consent flow and only fire on
    // explicit user action (label generation, map data fetch, etc.).
    $report[] = '';

    // 4. PHP function availability
    $report[] = '[ PHP Functions ]';
    $fns = array('curl_version','gethostbyname','usleep','file_get_contents','json_encode','mb_strlen');
    foreach ( $fns as $fn ) {
        $avail = function_exists($fn) ? '✅' : '❌ blocked';
        $critical = in_array($fn, array('curl_version','json_encode','mb_strlen')) ? ' (critical)' : '';
        $report[] = sprintf('  %s %s%s', $avail, $fn, $critical);
    }
    $report[] = '';

    // 5. License
    $report[] = '[ Plugin ]';
    $report[] = '  Edition: FREE (WP.org)';
    $report[] = '  Status: Active — Unlimited';
    $report[] = '';

    $report[] = parcselect_generate_sysinfo();

    wp_send_json_success( array( 'report' => implode("\n", $report) ) );
}
}

// ─── AJAX: Quick Test Cart ───────────────────────────────────────────────────
add_action( 'wp_ajax_parcselect_prepare_test_cart', 'parcselect_ajax_prepare_test_cart' );

if ( ! function_exists( 'parcselect_ajax_prepare_test_cart' ) ) {
function parcselect_ajax_prepare_test_cart() {
    check_ajax_referer( 'parcselect_prepare_test_cart', 'nonce' );
    if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => 'Unauthorized' ) );
    if ( ! function_exists( 'WC' ) || ! WC()->cart ) wp_send_json_error( array( 'message' => 'WooCommerce nie jest aktywne.' ) );

    WC()->cart->empty_cart();

    $products = wc_get_products( array(
        'status'       => 'publish',
        'limit'        => 3,
        'stock_status' => 'instock',
        'return'       => 'ids',
    ) );

    if ( empty( $products ) ) {
        wp_send_json_error( array( 'message' => 'No published products found in the store.' ) );
    }

    foreach ( $products as $pid ) {
        WC()->cart->add_to_cart( (int) $pid, 1 );
    }

    // Pre-fill Warsaw shipping + billing address
    if ( WC()->customer ) {
        WC()->customer->set_shipping_first_name( 'Jan' );
        WC()->customer->set_shipping_last_name( 'Kowalski' );
        WC()->customer->set_shipping_address_1( 'ul. Złota 7' );
        WC()->customer->set_shipping_city( 'Warszawa' );
        WC()->customer->set_shipping_postcode( '00-821' );
        WC()->customer->set_shipping_country( 'PL' );
        WC()->customer->set_billing_first_name( 'Jan' );
        WC()->customer->set_billing_last_name( 'Kowalski' );
        WC()->customer->set_billing_email( 'office@parcelselector.com' );
        WC()->customer->set_billing_phone( '+48 123 456 789' );
        WC()->customer->set_billing_address_1( 'ul. Złota 7' );
        WC()->customer->set_billing_city( 'Warszawa' );
        WC()->customer->set_billing_postcode( '00-821' );
        WC()->customer->set_billing_country( 'PL' );
        WC()->customer->save();
    }

    wp_send_json_success( array( 'checkout_url' => wc_get_checkout_url() ) );
}
}

// ─── AJAX: Log tail viewer ───────────────────────────────────────────────────
add_action( 'wp_ajax_parcselect_get_log_tail', 'parcselect_ajax_get_log_tail' );

if ( ! function_exists( 'parcselect_ajax_get_log_tail' ) ) {
function parcselect_ajax_get_log_tail() {
    check_ajax_referer( 'parcselect_get_log_tail', 'nonce' );
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => 'Unauthorized' ) );
    }

    $log_content = '(No log entries yet.)';
    $log_dir     = defined( 'WC_LOG_DIR' ) ? WC_LOG_DIR : trailingslashit( wp_upload_dir()['basedir'] ) . 'wc-logs/';

    if ( is_dir( $log_dir ) ) {
        $files = glob( $log_dir . 'parcel-selector-*.log' );
        if ( $files ) {
            usort( $files, static function( $a, $b ) { return filemtime( $b ) - filemtime( $a ); } );
            $lines = @file( $files[0], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
            if ( $lines ) {
                $log_content = implode( "\n", array_slice( $lines, -50 ) );
            }
        }
    }

    wp_send_json_success( array( 'log' => $log_content ) );
}
}

// Update notifications are handled by WordPress.org core (Plugin Directory).
// We do NOT ship a custom update checker — that would require a private endpoint
// outside the WordPress.org distribution channel.
