<?php
/**
 * Admin Settings — Returns Manager submenu under WooCommerce.
 * 3 tabs (General / Exclusion Rules / Get Pro), 2 option groups for cross-tab safety.
 *
 * @package WPNest_Returns_For_WooCommerce
 */

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

class WPNest_RFW_Admin_Settings {

    const PAGE_SLUG       = 'wpnest-rfw-settings';
    const GROUP_GENERAL   = 'wpnest_rfw_general_group';
    const GROUP_EXCLUSION = 'wpnest_rfw_exclusion_group';

    const PRO_URL     = 'https://wpnest.pl/wpnest-returns-for-woocommerce-pro/';
    const CONTACT_URL = 'https://wpnest.pl/kontakt/';

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'register_menu' ), 60 );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_post_wpnest_rfw_flush_cache', array( $this, 'handle_flush_cache' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );

        // Tell WooCommerce's React-based navigation to leave our settings page alone —
        // otherwise wc-admin SPA hijacks the click and rewrites the URL to /wp-admin/<slug>.
        add_filter( 'woocommerce_navigation_is_connected_page', array( $this, 'opt_out_of_wc_navigation' ), 10, 2 );
        add_filter( 'woocommerce_navigation_is_registered_page', array( $this, 'opt_out_of_wc_navigation' ), 10, 2 );
    }

    public function opt_out_of_wc_navigation( $is_connected, $current_page = null ) {
        $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
        if ( $screen && in_array( $screen->id, array(
            'woocommerce_page_' . self::PAGE_SLUG,
            'woocommerce_page_wpnest-rfw-requests',
        ), true ) ) {
            return false;
        }
        return $is_connected;
    }

    public function register_menu() {
        add_submenu_page(
            'woocommerce',
            __( 'Returns Manager', 'wpnest-returns-for-woocommerce' ),
            __( 'Returns Manager', 'wpnest-returns-for-woocommerce' ),
            'manage_woocommerce',
            self::PAGE_SLUG,
            array( $this, 'render' )
        );
    }

    public function register_settings() {
        // GROUP_GENERAL
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_enabled', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_withdrawal_window_days', array( 'sanitize_callback' => array( $this, 'sanitize_window_days' ), 'default' => 14 ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_button_label', array( 'sanitize_callback' => 'sanitize_text_field', 'default' => '' ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_merchant_email', array( 'sanitize_callback' => 'sanitize_email', 'default' => '' ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_delete_data_on_uninstall', array( 'sanitize_callback' => 'absint', 'default' => 0 ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_show_on_my_account', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_show_on_view_order', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_show_on_returns_page', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_notify_customer_on_status', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_custom_form_en_id', array( 'sanitize_callback' => array( $this, 'sanitize_attachment_id' ), 'default' => 0 ) );
        register_setting( self::GROUP_GENERAL, 'wpnest_rfw_custom_form_pl_id', array( 'sanitize_callback' => array( $this, 'sanitize_attachment_id' ), 'default' => 0 ) );

        // GROUP_EXCLUSION
        register_setting( self::GROUP_EXCLUSION, 'wpnest_rfw_excluded_statuses', array( 'sanitize_callback' => array( $this, 'sanitize_statuses' ), 'default' => array( 'cancelled', 'failed', 'refunded', 'trash' ) ) );
        register_setting( self::GROUP_EXCLUSION, 'wpnest_rfw_exclude_digital_with_waiver', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( self::GROUP_EXCLUSION, 'wpnest_rfw_exclude_customized', array( 'sanitize_callback' => 'absint', 'default' => 0 ) );
        register_setting( self::GROUP_EXCLUSION, 'wpnest_rfw_exclude_subscriptions', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( self::GROUP_EXCLUSION, 'wpnest_rfw_excluded_product_ids', array( 'sanitize_callback' => array( $this, 'sanitize_product_ids' ), 'default' => array() ) );

        add_filter( 'option_page_capability_' . self::GROUP_GENERAL, array( $this, 'options_capability' ) );
        add_filter( 'option_page_capability_' . self::GROUP_EXCLUSION, array( $this, 'options_capability' ) );
    }

    public function options_capability() {
        return 'manage_woocommerce';
    }

    public function sanitize_window_days( $value ) {
        $v = (int) $value;
        if ( $v < 1 ) { $v = 1; }
        if ( $v > 30 ) { $v = 30; }
        return $v;
    }

    public function sanitize_statuses( $value ) {
        $value = (array) $value;
        $valid = array_keys( wc_get_order_statuses() );
        $clean = array();
        foreach ( $value as $key ) {
            $key = sanitize_key( str_replace( 'wc-', '', (string) $key ) );
            if ( in_array( 'wc-' . $key, $valid, true ) ) {
                $clean[] = $key;
            }
        }
        return array_values( array_unique( $clean ) );
    }

    /**
     * Accept an attachment ID only if it points to an existing PDF in the media library.
     */
    public function sanitize_attachment_id( $value ) {
        $id = (int) $value;
        if ( $id <= 0 ) {
            return 0;
        }
        $post = get_post( $id );
        if ( ! $post || 'attachment' !== $post->post_type ) {
            return 0;
        }
        $mime = (string) get_post_mime_type( $id );
        if ( 'application/pdf' !== $mime ) {
            add_settings_error(
                'wpnest_rfw_messages',
                'wpnest_rfw_bad_pdf',
                __( 'Custom return form must be a PDF file.', 'wpnest-returns-for-woocommerce' ),
                'error'
            );
            return 0;
        }
        return $id;
    }

    public function sanitize_product_ids( $value ) {
        if ( is_array( $value ) ) {
            $ids = $value;
        } else {
            $ids = preg_split( '/[\r\n,\s]+/', (string) $value );
        }
        $clean = array();
        foreach ( (array) $ids as $id ) {
            $i = (int) $id;
            if ( $i > 0 ) { $clean[] = $i; }
        }
        return array_values( array_unique( $clean ) );
    }

    public function enqueue_assets( $hook ) {
        $allowed = array( 'woocommerce_page_' . self::PAGE_SLUG, 'woocommerce_page_wpnest-rfw-requests' );
        if ( ! in_array( $hook, $allowed, true ) ) {
            return;
        }
        wp_enqueue_style( 'wpnest-rfw-admin', WPNEST_RFW_PLUGIN_URL . 'assets/css/admin.css', array(), WPNEST_RFW_VERSION );

        // Settings page only — load the WP Media Library picker for custom PDF uploads.
        if ( 'woocommerce_page_' . self::PAGE_SLUG === $hook ) {
            wp_enqueue_media();
            wp_add_inline_script( 'jquery-core', $this->custom_pdf_picker_js() );
        }
    }

    /**
     * Inline JS that wires the two "Upload custom" buttons in the Tools card
     * to the WP Media Library picker (PDF only).
     */
    private function custom_pdf_picker_js() {
        $title  = esc_js( __( 'Choose a PDF', 'wpnest-returns-for-woocommerce' ) );
        $button = esc_js( __( 'Use this file', 'wpnest-returns-for-woocommerce' ) );

        return "( function ( \$ ) {\n"
            . "  \$( function () {\n"
            . "    var frames = {};\n"
            . "    \$( document ).on( 'click', '.wpnest-rfw-pdf-pick', function ( e ) {\n"
            . "      e.preventDefault();\n"
            . "      var \$btn   = \$( this );\n"
            . "      var locale = \$btn.data( 'locale' );\n"
            . "      var \$row   = \$btn.closest( '.wpnest-rfw-pdf-row' );\n"
            . "      if ( frames[ locale ] ) { frames[ locale ].open(); return; }\n"
            . "      frames[ locale ] = wp.media( {\n"
            . "        title:  '" . $title . "',\n"
            . "        button: { text: '" . $button . "' },\n"
            . "        library: { type: 'application/pdf' },\n"
            . "        multiple: false\n"
            . "      } );\n"
            . "      frames[ locale ].on( 'select', function () {\n"
            . "        var att = frames[ locale ].state().get( 'selection' ).first().toJSON();\n"
            . "        \$row.find( 'input[name=\"wpnest_rfw_custom_form_' + locale + '_id\"]' ).val( att.id );\n"
            . "        \$row.find( '.wpnest-rfw-pdf-filename' ).text( att.filename || att.title || ( '#' + att.id ) );\n"
            . "        \$row.find( '.wpnest-rfw-pdf-clear' ).removeAttr( 'hidden' );\n"
            . "        \$row.find( '.wpnest-rfw-pdf-status' ).text( '' );\n"
            . "      } );\n"
            . "      frames[ locale ].open();\n"
            . "    } );\n"
            . "    \$( document ).on( 'click', '.wpnest-rfw-pdf-clear', function ( e ) {\n"
            . "      e.preventDefault();\n"
            . "      var \$row = \$( this ).closest( '.wpnest-rfw-pdf-row' );\n"
            . "      \$row.find( 'input[type=\"hidden\"]' ).val( 0 );\n"
            . "      \$row.find( '.wpnest-rfw-pdf-filename' ).text( '' );\n"
            . "      \$( this ).attr( 'hidden', 'hidden' );\n"
            . "    } );\n"
            . "  } );\n"
            . "} )( jQuery );\n";
    }

    private function current_tab() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only navigation; no state mutation in this method.
        $requested = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';
        $tabs      = $this->get_tabs();
        return ( $requested && isset( $tabs[ $requested ] ) ) ? $requested : 'general';
    }

    private function get_tabs() {
        $tabs = array(
            'general'    => __( 'General', 'wpnest-returns-for-woocommerce' ),
            'exclusions' => __( 'Exclusion Rules', 'wpnest-returns-for-woocommerce' ),
        );

        // The Get Pro tab is suppressed once the Pro extension hooks into wpnest_rfw_pro_active.
        if ( ! WPNest_Returns_For_WooCommerce::is_pro_active() ) {
            $tabs['get_pro'] = __( 'Get Pro', 'wpnest-returns-for-woocommerce' );
        }

        // Pro (and other integrations) can register additional tabs through this filter.
        // Each entry is keyed by a sanitized slug; render a tab body by hooking
        // `wpnest_rfw_render_settings_tab_<slug>` (handled below in render()).
        $tabs = apply_filters( 'wpnest_rfw_settings_tabs', $tabs );
        return is_array( $tabs ) ? $tabs : array();
    }

    public function render() {
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            return;
        }
        $current = $this->current_tab();
        ?>
        <div class="wrap wpnph-app">
            <div class="wpnph-hero">
                <div class="wpnph-hero__brand">
                    <span class="dashicons dashicons-update"></span>
                    <h1 class="wpnph-hero__title"><?php esc_html_e( 'Returns Manager', 'wpnest-returns-for-woocommerce' ); ?></h1>
                </div>
                <p class="wpnph-hero__lede">
                    <?php esc_html_e( 'EU Directive 2023/2673 compliance — let customers initiate returns with a single button on My Account.', 'wpnest-returns-for-woocommerce' ); ?>
                </p>
                <?php $pill = $this->status_pill(); ?>
                <span class="wpnph-hero__pill wpnph-hero__pill--<?php echo esc_attr( $pill['type'] ); ?>"><?php echo esc_html( $pill['label'] ); ?></span>
            </div>

            <nav class="wpnph-tabs">
                <?php foreach ( $this->get_tabs() as $key => $label ) : ?>
                    <a class="wpnph-tabs__link <?php echo $current === $key ? 'is-active' : ''; ?>"
                       href="<?php echo esc_url( add_query_arg( array( 'page' => self::PAGE_SLUG, 'tab' => $key ), admin_url( 'admin.php' ) ) ); ?>">
                        <?php echo esc_html( $label ); ?>
                    </a>
                <?php endforeach; ?>
            </nav>

            <?php settings_errors(); ?>

            <?php
            switch ( $current ) {
                case 'exclusions':
                    $this->render_exclusions_tab();
                    break;
                case 'get_pro':
                    $this->render_get_pro_tab();
                    break;
                case 'general':
                    $this->render_general_tab();
                    break;
                default:
                    // Tabs registered by Pro / 3rd-party render via this action.
                    if ( has_action( 'wpnest_rfw_render_settings_tab_' . $current ) ) {
                        do_action( 'wpnest_rfw_render_settings_tab_' . $current, $current );
                    } else {
                        $this->render_general_tab();
                    }
                    break;
            }
            ?>
        </div>
        <?php
    }

    private function status_pill() {
        $enabled = (bool) get_option( 'wpnest_rfw_enabled', 1 );
        if ( ! $enabled ) {
            return array( 'type' => 'warn', 'label' => __( 'Disabled', 'wpnest-returns-for-woocommerce' ) );
        }
        $page_id = (int) get_option( 'wpnest_rfw_page_id', 0 );
        if ( ! $page_id || ! get_post( $page_id ) ) {
            return array( 'type' => 'warn', 'label' => __( 'Returns page missing', 'wpnest-returns-for-woocommerce' ) );
        }
        return array( 'type' => 'ok', 'label' => __( 'Active', 'wpnest-returns-for-woocommerce' ) );
    }

    private function render_general_tab() {
        $page_id = (int) get_option( 'wpnest_rfw_page_id', 0 );
        ?>
        <form method="post" action="options.php">
            <?php settings_fields( self::GROUP_GENERAL ); ?>

            <div class="wpnph-card">
                <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Core settings', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
                <div class="wpnph-card__body">

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Plugin enabled', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_enabled" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_enabled', 1 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Show return button to customers', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label">
                            <label for="wpnest-rfw-window"><?php esc_html_e( 'Return window (days)', 'wpnest-returns-for-woocommerce' ); ?></label>
                        </div>
                        <div class="wpnph-row__control">
                            <input type="number" id="wpnest-rfw-window" name="wpnest_rfw_withdrawal_window_days"
                                value="<?php echo esc_attr( (int) get_option( 'wpnest_rfw_withdrawal_window_days', 14 ) ); ?>"
                                min="1" max="30" class="small-text">
                            <p class="wpnph-row__hint"><?php esc_html_e( 'EU directive sets a minimum of 14 days. You may extend it.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label">
                            <label for="wpnest-rfw-label"><?php esc_html_e( 'Button label', 'wpnest-returns-for-woocommerce' ); ?></label>
                        </div>
                        <div class="wpnph-row__control">
                            <input type="text" id="wpnest-rfw-label" name="wpnest_rfw_button_label"
                                value="<?php echo esc_attr( (string) get_option( 'wpnest_rfw_button_label', '' ) ); ?>"
                                placeholder="<?php echo esc_attr__( 'Return this order', 'wpnest-returns-for-woocommerce' ); ?>"
                                class="regular-text">
                            <p class="wpnph-row__hint"><?php
                                printf(
                                    /* translators: %s: default translated label */
                                    esc_html__( 'Pozostaw puste, aby użyć domyślnego tłumaczenia: „%s".', 'wpnest-returns-for-woocommerce' ),
                                    esc_html__( 'Return this order', 'wpnest-returns-for-woocommerce' )
                                );
                            ?></p>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label">
                            <label for="wpnest-rfw-email"><?php esc_html_e( 'Merchant notification email', 'wpnest-returns-for-woocommerce' ); ?></label>
                        </div>
                        <div class="wpnph-row__control">
                            <input type="email" id="wpnest-rfw-email" name="wpnest_rfw_merchant_email"
                                value="<?php echo esc_attr( (string) get_option( 'wpnest_rfw_merchant_email', '' ) ); ?>"
                                class="regular-text">
                            <p class="wpnph-row__hint"><?php esc_html_e( 'Where new return notifications are sent. Falls back to the WordPress admin email if empty.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Customer status emails', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_notify_customer_on_status" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_notify_customer_on_status', 1 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Automatically email the customer whenever a return status changes', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                            <p class="wpnph-row__hint"><?php esc_html_e( 'On by default. The customer always receives the submission confirmation (with PDF) regardless of this setting; this toggle controls follow-up emails for accept/reject/refund transitions. Admins can override per change in the Return Requests detail screen.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Delete data on uninstall', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_delete_data_on_uninstall" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_delete_data_on_uninstall', 0 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Drop tables and delete the Returns page when the plugin is uninstalled', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                            <p class="wpnph-row__hint"><?php esc_html_e( 'Off by default. Return request history is treated as audit-relevant data.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                </div>
            </div>

            <div class="wpnph-card">
                <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Where to show the return button', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
                <div class="wpnph-card__body">
                    <p class="wpnph-row__hint" style="margin-top:0">
                        <?php esc_html_e( 'Pick the locations where the "Return this order" button should appear. Each location can be toggled independently — the wizard at /returns/?order=ID always works regardless of these toggles.', 'wpnest-returns-for-woocommerce' ); ?>
                    </p>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'My Account → Orders list', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_show_on_my_account" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_show_on_my_account', 1 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Show as an action next to "View" on every eligible order in the orders table', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'My Account → Single order', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_show_on_view_order" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_show_on_view_order', 1 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Show under the order details table on the "View order" page', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Public Returns page', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_show_on_returns_page" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_show_on_returns_page', 1 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Enable the /returns/ landing page (orders list for logged-in users + guest verification form)', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                            <p class="wpnph-row__hint"><?php esc_html_e( 'When off, the /returns/ URL returns a real 404. The wizard URL /returns/?order=ID still works, so the "Return this order" button in My Account keeps functioning.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                </div>
            </div>

            <div class="wpnph-card">
                <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Customer-facing return forms (PDFs)', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
                <div class="wpnph-card__body">
                    <p class="wpnph-row__hint" style="margin-top:0">
                        <?php esc_html_e( 'These PDFs are linked from /returns/ and emailed to customers who prefer a paper form. The plugin ships a generic EU model form; upload your own branded version to override per language.', 'wpnest-returns-for-woocommerce' ); ?>
                    </p>

                    <?php
                    foreach ( array(
                        'en' => __( 'English (EN)', 'wpnest-returns-for-woocommerce' ),
                        'pl' => __( 'Polish (PL)', 'wpnest-returns-for-woocommerce' ),
                    ) as $locale => $label ) :
                        $custom_id = (int) get_option( 'wpnest_rfw_custom_form_' . $locale . '_id', 0 );
                        $custom_url = $custom_id ? wp_get_attachment_url( $custom_id ) : '';
                        $custom_filename = '';
                        if ( $custom_id ) {
                            $att_path = get_attached_file( $custom_id );
                            $custom_filename = $att_path ? basename( $att_path ) : '';
                        }
                        $bundled_path = WPNEST_RFW_PLUGIN_DIR . 'assets/pdf/return-form-' . $locale . '.pdf';
                        $bundled_present = file_exists( $bundled_path );
                        $effective_url = $custom_url ? $custom_url : ( $bundled_present ? WPNEST_RFW_PLUGIN_URL . 'assets/pdf/return-form-' . $locale . '.pdf' : '' );
                        $source_label = $custom_url
                            ? __( 'Custom upload', 'wpnest-returns-for-woocommerce' )
                            : ( $bundled_present ? __( 'Bundled default', 'wpnest-returns-for-woocommerce' ) : __( 'Not available', 'wpnest-returns-for-woocommerce' ) );
                    ?>
                        <div class="wpnest-rfw-pdf-row">
                            <p class="wpnest-rfw-pdf-row__head">
                                <strong><?php echo esc_html( $label ); ?></strong>
                                &middot; <span class="wpnest-rfw-pdf-status">
                                    <?php
                                    printf(
                                        /* translators: %s: source label (e.g. Custom upload / Bundled default) */
                                        esc_html__( 'Source: %s', 'wpnest-returns-for-woocommerce' ),
                                        esc_html( $source_label )
                                    );
                                    ?>
                                </span>
                                <?php if ( $effective_url ) : ?>
                                    &middot; <a href="<?php echo esc_url( $effective_url ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Preview current PDF', 'wpnest-returns-for-woocommerce' ); ?></a>
                                <?php endif; ?>
                            </p>

                            <input type="hidden" name="wpnest_rfw_custom_form_<?php echo esc_attr( $locale ); ?>_id" value="<?php echo esc_attr( $custom_id ); ?>">

                            <p class="wpnest-rfw-pdf-row__body">
                                <button type="button" class="button wpnest-rfw-pdf-pick" data-locale="<?php echo esc_attr( $locale ); ?>">
                                    <?php echo esc_html( $custom_id ? __( 'Replace PDF…', 'wpnest-returns-for-woocommerce' ) : __( 'Upload custom PDF…', 'wpnest-returns-for-woocommerce' ) ); ?>
                                </button>
                                <button type="button" class="button-link wpnest-rfw-pdf-clear" <?php echo $custom_id ? '' : 'hidden'; ?>>
                                    <?php esc_html_e( 'Use bundled default', 'wpnest-returns-for-woocommerce' ); ?>
                                </button>
                                <span class="wpnest-rfw-pdf-filename"><?php echo esc_html( $custom_filename ); ?></span>
                            </p>
                        </div>
                    <?php endforeach; ?>

                    <p class="wpnph-row__hint">
                        <?php esc_html_e( 'Click "Save changes" below for upload selection to take effect.', 'wpnest-returns-for-woocommerce' ); ?>
                    </p>
                </div>
            </div>

            <p><button type="submit" class="button button-primary wpnph-btn wpnph-btn--primary"><?php esc_html_e( 'Save changes', 'wpnest-returns-for-woocommerce' ); ?></button></p>
        </form>

        <div class="wpnph-card">
            <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Tools', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
            <div class="wpnph-card__body">

                <div class="wpnph-row">
                    <div class="wpnph-row__label"><?php esc_html_e( 'Returns page', 'wpnest-returns-for-woocommerce' ); ?></div>
                    <div class="wpnph-row__control">
                        <?php if ( $page_id && get_post( $page_id ) ) : ?>
                            <a href="<?php echo esc_url( get_permalink( $page_id ) ); ?>" target="_blank" rel="noopener"><?php echo esc_html( get_permalink( $page_id ) ); ?></a>
                        <?php else : ?>
                            <em><?php esc_html_e( 'Page not found. Reactivate the plugin to recreate it.', 'wpnest-returns-for-woocommerce' ); ?></em>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="wpnph-row">
                    <div class="wpnph-row__label"><?php esc_html_e( 'Cache', 'wpnest-returns-for-woocommerce' ); ?></div>
                    <div class="wpnph-row__control">
                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline">
                            <input type="hidden" name="action" value="wpnest_rfw_flush_cache">
                            <?php wp_nonce_field( 'wpnest_rfw_flush_cache' ); ?>
                            <button type="submit" class="button"><?php esc_html_e( 'Flush plugin cache', 'wpnest-returns-for-woocommerce' ); ?></button>
                        </form>
                        <p class="wpnph-row__hint"><?php esc_html_e( 'Clears guest verification tokens and rate-limit counters.', 'wpnest-returns-for-woocommerce' ); ?></p>
                    </div>
                </div>

            </div>
        </div>
        <?php
    }

    private function render_exclusions_tab() {
        $excluded_statuses = (array) get_option( 'wpnest_rfw_excluded_statuses', array( 'cancelled', 'failed', 'refunded', 'trash' ) );
        $excluded_ids      = (array) get_option( 'wpnest_rfw_excluded_product_ids', array() );
        ?>
        <form method="post" action="options.php">
            <?php settings_fields( self::GROUP_EXCLUSION ); ?>

            <div class="wpnph-card">
                <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Order eligibility filters', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
                <div class="wpnph-card__body">

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Excluded order statuses', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <?php foreach ( wc_get_order_statuses() as $key => $label ) :
                                $clean = str_replace( 'wc-', '', $key );
                                if ( 0 === strpos( $clean, 'rfw-' ) ) { continue; }
                            ?>
                                <label class="wpnph-check" style="display:block;margin:4px 0;">
                                    <input type="checkbox" name="wpnest_rfw_excluded_statuses[]" value="<?php echo esc_attr( $clean ); ?>"
                                        <?php checked( in_array( $clean, $excluded_statuses, true ) ); ?>>
                                    <?php echo esc_html( $label ); ?>
                                </label>
                            <?php endforeach; ?>
                            <p class="wpnph-row__hint"><?php esc_html_e( 'Orders in these statuses cannot be returned through the form.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Digital orders with waiver', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_exclude_digital_with_waiver" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_exclude_digital_with_waiver', 1 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Block returns for fully-digital orders where the customer accepted the waiver at checkout', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                            <p class="wpnph-row__hint"><?php esc_html_e( 'Required by Article 16(m) of Directive 2011/83/EU.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Customized products', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_exclude_customized" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_exclude_customized', 0 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Block returns for orders containing products marked as customized', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                            <p class="wpnph-row__hint"><?php esc_html_e( 'Mark a product as customized via the _wpnest_rfw_exclude meta key.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Subscription orders', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="wpnest_rfw_exclude_subscriptions" value="1" <?php checked( 1, (int) get_option( 'wpnest_rfw_exclude_subscriptions', 1 ) ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Skip orders that contain WooCommerce Subscriptions products', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label">
                            <label for="wpnest-rfw-excluded-ids"><?php esc_html_e( 'Excluded product IDs', 'wpnest-returns-for-woocommerce' ); ?></label>
                        </div>
                        <div class="wpnph-row__control">
                            <textarea id="wpnest-rfw-excluded-ids" name="wpnest_rfw_excluded_product_ids" rows="4" class="large-text code"><?php echo esc_textarea( implode( "\n", array_map( 'intval', $excluded_ids ) ) ); ?></textarea>
                            <p class="wpnph-row__hint"><?php esc_html_e( 'One product ID per line. Orders containing any of these products are blocked from returns.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>

                </div>
            </div>

            <p><button type="submit" class="button button-primary wpnph-btn wpnph-btn--primary"><?php esc_html_e( 'Save changes', 'wpnest-returns-for-woocommerce' ); ?></button></p>
        </form>
        <?php
    }

    private function render_get_pro_tab() {
        $buy_url     = self::PRO_URL;
        $contact_url = self::CONTACT_URL;
        ?>
        <div class="wpnph-getpro">

            <?php
            /**
             * Fires at the top of the Get Pro tab — Pro hooks in here to render
             * its license re-check panel when the current domain isn't yet
             * authorized (skips the 12h fresh-cache wait).
             */
            do_action( 'wpnest_rfw_get_pro_tab_top' );
            ?>

            <!-- HERO: pain → solution + primary CTA -->
            <div class="wpnph-getpro__hero">
                <span class="wpnph-getpro__eyebrow"><?php esc_html_e( 'WPNest Returns Pro', 'wpnest-returns-for-woocommerce' ); ?></span>
                <h2><?php esc_html_e( 'Stop losing 15 minutes on every return', 'wpnest-returns-for-woocommerce' ); ?></h2>
                <p>
                    <?php esc_html_e( 'The Free plugin keeps you compliant. Pro turns return handling into a 60-second job — prepaid courier labels, refund deadline tracker, branded emails, and an analytics dashboard. Everything you need to deliver a Zalando-grade return experience without hiring extra staff.', 'wpnest-returns-for-woocommerce' ); ?>
                </p>
                <div class="wpnph-getpro__hero-actions">
                    <a class="wpnph-btn wpnph-btn--primary" href="<?php echo esc_url( $buy_url ); ?>" target="_blank" rel="noopener">
                        <?php esc_html_e( 'Unlock Returns Pro →', 'wpnest-returns-for-woocommerce' ); ?>
                    </a>
                    <a class="wpnph-getpro__hero-secondary" href="<?php echo esc_url( $buy_url . '#features' ); ?>" target="_blank" rel="noopener">
                        <?php esc_html_e( 'Compare full feature list', 'wpnest-returns-for-woocommerce' ); ?>
                    </a>
                </div>
            </div>

            <!-- COMPLIANCE URGENCY: real, externally-fixed deadline (not fake scarcity) -->
            <div class="wpnph-banner wpnph-banner--warn">
                <span class="wpnph-banner__icon">⚖️</span>
                <div>
                    <p class="wpnph-banner__title"><?php esc_html_e( 'EU Directive 2023/2673 — return button mandatory from 19 June 2026', 'wpnest-returns-for-woocommerce' ); ?></p>
                    <p class="wpnph-banner__msg"><?php esc_html_e( 'Every WooCommerce store selling to EU consumers must offer a customer-facing return button. Free covers compliance. Pro covers the workflow that turns compliance into customer loyalty.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </div>
            </div>

            <!-- OUTCOME STATS: concrete value framing (anchor before showing features) -->
            <div class="wpnph-getpro__stats">
                <article class="wpnph-stat">
                    <span class="wpnph-stat__label"><?php esc_html_e( 'Time per return', 'wpnest-returns-for-woocommerce' ); ?></span>
                    <span class="wpnph-stat__value wpnph-stat__value--accent"><?php esc_html_e( '~60 s', 'wpnest-returns-for-woocommerce' ); ?></span>
                    <p class="wpnph-stat__hint"><?php esc_html_e( 'Customer triggers, Pro generates the label, you ship. No back-and-forth emails.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>
                <article class="wpnph-stat">
                    <span class="wpnph-stat__label"><?php esc_html_e( 'Refund deadline', 'wpnest-returns-for-woocommerce' ); ?></span>
                    <span class="wpnph-stat__value wpnph-stat__value--ok"><?php esc_html_e( 'Tracked', 'wpnest-returns-for-woocommerce' ); ?></span>
                    <p class="wpnph-stat__hint"><?php esc_html_e( 'Art. 13 CRD +14 days. Pro nudges you days before a UOKiK fine becomes a risk.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>
                <article class="wpnph-stat">
                    <span class="wpnph-stat__label"><?php esc_html_e( 'Customer experience', 'wpnest-returns-for-woocommerce' ); ?></span>
                    <span class="wpnph-stat__value wpnph-stat__value--accent"><?php esc_html_e( 'Like Zalando', 'wpnest-returns-for-woocommerce' ); ?></span>
                    <p class="wpnph-stat__hint"><?php esc_html_e( 'Branded emails, status tracking, prepaid labels — the experience customers already expect.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>
            </div>

            <!-- FEATURE GRID: pain-framed feature descriptions -->
            <h3 class="wpnph-getpro__section-title"><?php esc_html_e( 'Everything you unlock with Pro', 'wpnest-returns-for-woocommerce' ); ?></h3>
            <div class="wpnph-getpro__grid">

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">📦</span>
                    <h3><?php esc_html_e( 'Prepaid courier labels', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'One-click integration with Apaczka.pl, InPost paczkomaty and DPD. The customer downloads a ready-to-ship label — friction goes to zero, repeat purchases go up.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">⏱️</span>
                    <h3><?php esc_html_e( 'Refund deadline tracker', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'Automatic Art. 13 CRD +14d countdown on every accepted return, with admin notice and email reminder 48h before you risk a fine.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">✉️</span>
                    <h3><?php esc_html_e( 'Branded HTML emails', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'Beautiful customer + merchant templates that match your store, with your logo, colors and tone. Plain-text fallback included.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">📊</span>
                    <h3><?php esc_html_e( 'Analytics dashboard', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'Return rate, top reasons by SKU, average refund time, monthly trend. Spot the product that ruins your margins before you re-order it.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">📱</span>
                    <h3><?php esc_html_e( 'SMS notifications', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'SMSAPI integration delivers status updates to the customer at every step. Open rate: 98%. Email reply rate when customer also got SMS: way higher.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">🔗</span>
                    <h3><?php esc_html_e( 'Webhooks: Slack, Discord, JSON', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'A new return request lands in your team channel before the customer closes the browser tab. Connect anything: Make, Zapier, n8n, custom CRMs.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">📎</span>
                    <h3><?php esc_html_e( 'Customer attachment uploads', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'Customers attach photos of damaged products at the moment of complaint. No more "could you send a photo" email loops.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">🏷️</span>
                    <h3><?php esc_html_e( 'Per-category exclusion rules', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'Block returns on perishable food, custom prints, intimate items — anything you can scope by WooCommerce category. Stays compliant with consumer law.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

                <article class="wpnph-getpro__feature">
                    <span class="wpnph-getpro__feature-icon">🧾</span>
                    <h3><?php esc_html_e( 'Audit-grade history & CSV export', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'UOKiK request? Tax audit? Pull a complete CSV of every return, item, reason and refund date in two clicks.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </article>

            </div>

            <!-- AUTHORITY: same engineering team -->
            <div class="wpnph-card wpnph-card--accent">
                <div class="wpnph-card__body wpnph-getpro__authority">
                    <h3><?php esc_html_e( 'Built by the team behind WPNest Price History', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <p><?php esc_html_e( 'Our Omnibus compliance plugin runs in production on Polish WooCommerce stores under real UOKiK scrutiny. Returns Pro is built with the same standards: production-grade code, Polish documentation, support from the engineers who wrote the plugin.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </div>
            </div>

            <!-- RISK REVERSAL -->
            <div class="wpnph-banner wpnph-banner--success">
                <span class="wpnph-banner__icon">🛡️</span>
                <div>
                    <p class="wpnph-banner__title"><?php esc_html_e( '14-day money-back guarantee', 'wpnest-returns-for-woocommerce' ); ?></p>
                    <p class="wpnph-banner__msg"><?php esc_html_e( 'If Pro does not save you time in the first two weeks, write one email and we refund. No forms, no friction — the same standard we hold our own returns to.', 'wpnest-returns-for-woocommerce' ); ?></p>
                </div>
            </div>

            <!-- FINAL CTA -->
            <div class="wpnph-getpro__final">
                <h3><?php esc_html_e( 'Ready to upgrade?', 'wpnest-returns-for-woocommerce' ); ?></h3>
                <p><?php esc_html_e( 'One license. Lifetime updates. Polish-speaking support from the people who wrote the plugin.', 'wpnest-returns-for-woocommerce' ); ?></p>
                <a class="wpnph-btn wpnph-btn--primary wpnph-getpro__final-cta" href="<?php echo esc_url( $buy_url ); ?>" target="_blank" rel="noopener">
                    <?php esc_html_e( 'Get WPNest Returns Pro →', 'wpnest-returns-for-woocommerce' ); ?>
                </a>
                <p class="wpnph-getpro__contact">
                    <?php
                    printf(
                        /* translators: %s: contact page link wrapping "Talk to us" */
                        esc_html__( 'Not sure if Pro fits your store? %s before buying — same engineers, no sales script.', 'wpnest-returns-for-woocommerce' ),
                        '<a href="' . esc_url( $contact_url ) . '" target="_blank" rel="noopener">' . esc_html__( 'Talk to us first', 'wpnest-returns-for-woocommerce' ) . '</a>'
                    );
                    ?>
                </p>
            </div>

        </div>
        <?php
    }

    public function handle_flush_cache() {
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'wpnest-returns-for-woocommerce' ) );
        }
        check_admin_referer( 'wpnest_rfw_flush_cache' );

        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- One-shot transient cleanup.
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
                $wpdb->esc_like( '_transient_wpnest_rfw_' ) . '%',
                $wpdb->esc_like( '_transient_timeout_wpnest_rfw_' ) . '%'
            )
        );

        wp_safe_redirect( add_query_arg( array( 'page' => self::PAGE_SLUG, 'flushed' => 1 ), admin_url( 'admin.php' ) ) );
        exit;
    }
}
