<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! class_exists( 'OPA_Picking_Route' ) ) {

    class OPA_Picking_Route {

        protected $taxonomy = 'pickingroute';
        protected $parent_slug = 'edit.php?post_type=product';
        protected $menu_slug = 'orderpickingapp-picking-route';

        public function __construct() {
            add_action( 'init', array( $this, 'orderpickingapp_register_pickingroute_taxonomy' ), 99 );

            // Admin UI
            add_action( 'admin_menu', array( $this, 'orderpickingapp_register_admin_page' ), 99 );
            add_action( 'admin_menu', array( $this, 'orderpickingapp_hide_default_taxonomy_menu' ), 999 );
            add_action( 'current_screen', array( $this, 'orderpickingapp_redirect_default_taxonomy_pages' ) );

            // Product tab
            add_filter( 'woocommerce_product_data_tabs', array( $this, 'orderpickingapp_add_product_tab' ) );
            add_action( 'woocommerce_product_data_panels', array( $this, 'orderpickingapp_render_product_tab' ) );
            add_action( 'woocommerce_process_product_meta', array( $this, 'orderpickingapp_save_product_terms' ) );

            // Variation support
            add_action( 'woocommerce_product_after_variable_attributes', array( $this, 'orderpickingapp_variation_field' ), 10, 3 );
            add_action( 'woocommerce_save_product_variation', array( $this, 'orderpickingapp_save_variation_terms' ), 10, 2 );

            add_action( 'admin_post_orderpickingapp_add_pickingroute_term', array( $this, 'orderpickingapp_handle_add_term' ) );
            add_action( 'admin_post_orderpickingapp_export_pickingroutes_pdf', array( $this, 'orderpickingapp_handle_export_pdf' ) );

            add_filter( 'manage_edit-product_columns', array( $this, 'orderpickingapp_add_pickingroute_product_column' ), 20 );
            add_action( 'manage_product_posts_custom_column', array( $this, 'orderpickingapp_render_product_columns' ), 20, 2 );

            add_action( 'add_meta_boxes', array( $this, 'orderpickingapp_register_location_meta_box' ) );

            add_filter( 'bulk_actions-edit-product', array( $this, 'orderpickingapp_register_bulk_location_action' ) );
            add_filter( 'handle_bulk_actions-edit-product', array( $this, 'orderpickingapp_handle_bulk_location_action' ), 10, 3 );
            add_action( 'restrict_manage_posts', array( $this, 'orderpickingapp_render_bulk_location_dropdown' ) );
            add_action( 'admin_notices', array( $this, 'orderpickingapp_bulk_location_admin_notice' ) );

            add_action( 'admin_notices', array( $this, 'orderpickingapp_render_orderpickingapp_orders_banner' ) );
        }

        public function orderpickingapp_render_orderpickingapp_orders_banner() {
            $screen = get_current_screen();

            if ( ! $screen ) {
                return;
            }

            $is_classic_orders = ( 'edit-shop_order' === $screen->id );
            $is_hpos_orders    = ( 'woocommerce_page_wc-orders' === $screen->id || 'admin_page_wc-orders' === $screen->id );

            if ( ! $is_classic_orders && ! $is_hpos_orders ) {
                return;
            }

            $orders = wc_get_orders( array(
                'limit'  => 250,
                'status' => array( 'wc-processing', 'wc-on-hold' ),
                'return' => 'ids',
            ) );

            if ( empty( $orders ) ) {
                return;
            }

            $order_count   = count( $orders );
            $product_count = 0;

            foreach ( $orders as $order_id ) {
                $order = wc_get_order( $order_id );

                if ( ! $order ) {
                    continue;
                }

                foreach ( $order->get_items() as $item ) {
                    $product_count += (int) $item->get_quantity();
                }
            }

            echo '<div class="notice orderpickingapp-orders-banner">';
            echo '<div class="orderpickingapp-orders-banner__inner">';

            echo '<div class="orderpickingapp-orders-banner__media">';
            echo '<img src="' .esc_url( OPA_PLUGIN_URL . 'admin/images/orderpickingapp-fast-and-error-free.png' ) . '" alt="' . esc_attr__( 'Order Picking App', 'order-picking-app' ) . '" style="width: 75px;" />';
            echo '</div>';

            echo '<div class="orderpickingapp-orders-banner__text">';
            echo '<strong>' . sprintf(
                /* translators: 1: Number of orders, 2: Number of products. */
                    esc_html__(
                        'You have %1$d orders to pick with %2$d products in them',
                        'order-picking-app'
                    ),
                    absint( $order_count ),
                    absint( $product_count )
                ) . '</strong>';
            echo '<i>' . esc_html__( 'Pick orders 3× faster — no paper, no errors — with Orderpicking App', 'order-picking-app' ) . '</i>';
            echo '</div>';
            echo '<div class="orderpickingapp-orders-banner__actions">';
            echo '<a class="btn btn-primary" href="admin.php?page=orderpickingapp-panel" target="_blank">';
            echo esc_html__( 'Settings', 'order-picking-app' );
            echo '</a>';
            echo '</div>';
            echo '</div>';
            echo '</div>';
        }

        public function orderpickingapp_register_bulk_location_action( $bulk_actions ) {
            $bulk_actions['orderpickingapp_assign_location'] = __( 'Assign location', 'order-picking-app' );
            return $bulk_actions;
        }

        public function orderpickingapp_render_bulk_location_dropdown( $post_type ) {
            if ( 'product' !== $post_type ) {
                return;
            }

            $screen = get_current_screen();
            if ( ! $screen || 'edit-product' !== $screen->id ) {
                return;
            }

            $tree = $this->orderpickingapp_get_terms_tree();

            wp_nonce_field( 'orderpickingapp_bulk_assign_location', 'orderpickingapp_bulk_location_nonce' );

            echo '<select name="orderpickingapp_bulk_location" style="max-width:260px; margin-left:6px;">';
            echo '<option value="">' . esc_html__( 'Select location', 'order-picking-app' ) . '</option>';
            $this->orderpickingapp_render_term_options( $tree, 0, array(), '' );
            echo '</select>';
        }


        public function orderpickingapp_handle_bulk_location_action( $redirect_to, $doaction, $post_ids ) {
            if ( 'orderpickingapp_assign_location' === $doaction ) {
                if ( ! current_user_can( 'edit_products' ) ) {
                    return add_query_arg(
                        array(
                            'orderpickingapp_bulk_location_assigned' => 0,
                            'orderpickingapp_bulk_location_error'    => 'permission',
                        ),
                        $redirect_to
                    );
                }

                $nonce = isset( $_REQUEST['orderpickingapp_bulk_location_nonce'] )
                    ? sanitize_text_field( wp_unslash( $_REQUEST['orderpickingapp_bulk_location_nonce'] ) )
                    : '';

                if ( ! wp_verify_nonce( $nonce, 'orderpickingapp_bulk_assign_location' ) ) {
                    return add_query_arg(
                        array(
                            'orderpickingapp_bulk_location_assigned' => 0,
                            'orderpickingapp_bulk_location_error'    => 'nonce',
                        ),
                        $redirect_to
                    );
                }

                $location_id = isset( $_REQUEST['orderpickingapp_bulk_location'] ) ? absint( wp_unslash( $_REQUEST['orderpickingapp_bulk_location'] ) ) : 0;

                if ( $location_id > 0 ) {
                    foreach ( $post_ids as $post_id ) {
                        wp_set_post_terms( $post_id, array( $location_id ), $this->taxonomy, false );
                    }

                    $redirect_to = add_query_arg(
                        array(
                            'orderpickingapp_bulk_location_assigned' => count( $post_ids ),
                            'orderpickingapp_bulk_location_id'       => $location_id,
                        ),
                        $redirect_to
                    );
                } else {
                    $redirect_to = add_query_arg(
                        array(
                            'orderpickingapp_bulk_location_assigned' => 0,
                            'orderpickingapp_bulk_location_missing'  => 1,
                        ),
                        $redirect_to
                    );
                }
            }

            return $redirect_to;
        }

        public function orderpickingapp_bulk_location_admin_notice() {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $post_type = isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : '';

            if ( 'product' !== $post_type ) {
                return;
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if ( ! isset( $_GET['orderpickingapp_bulk_location_assigned'] ) ) {
                return;
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $count = absint( wp_unslash( $_GET['orderpickingapp_bulk_location_assigned'] ) );

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $has_error = ! empty( $_GET['orderpickingapp_bulk_location_error'] );

            if ( $has_error ) {
                echo '<div class="notice notice-error is-dismissible"><p>';
                echo esc_html__( 'The location bulk action could not be verified. Please try again.', 'order-picking-app' );
                echo '</p></div>';
                return;
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $is_missing = ! empty( $_GET['orderpickingapp_bulk_location_missing'] );

            if ( $is_missing ) {
                echo '<div class="notice notice-warning is-dismissible"><p>';
                echo esc_html__( 'Please select a location before running the bulk action.', 'order-picking-app' );
                echo '</p></div>';
                return;
            }

            if ( $count > 0 ) {
                ?>
                <div class="notice notice-success is-dismissible">
                    <p>
                        <?php
                        $message = sprintf(
                        /* translators: %d: Number of product locations updated. */
                            _n(
                                '%d product location updated.',
                                '%d product locations updated.',
                                absint( $count ),
                                'order-picking-app'
                            ),
                            absint( $count )
                        );

                        echo esc_html( $message );
                        ?>
                    </p>
                </div>
                <?php
            }
        }

        public function orderpickingapp_register_location_meta_box() {
            add_meta_box(
                'orderpickingapp_product_location_summary',
                __( 'Picking Route', 'order-picking-app' ),
                array( $this, 'orderpickingapp_render_location_meta_box' ),
                'product',
                'side',
                'default'
            );
        }

        public function orderpickingapp_render_location_meta_box( $post ) {
            $product_id = $post->ID;

            $term_ids = wp_get_post_terms(
                $product_id,
                $this->taxonomy,
                array(
                    'fields' => 'ids',
                )
            );

            $add_location_url = add_query_arg(
                array(
                    'post_type' => 'product',
                    'page'      => 'orderpickingapp-picking-route',
                    'tab'       => 'input',
                    'term_id'   => 0,
                    's'         => '',
                ),
                admin_url( 'edit.php' )
            );

            echo '<div class="orderpickingapp-location-meta-box">';

            if ( ! empty( $term_ids ) && ! is_wp_error( $term_ids ) ) {
                foreach ( $term_ids as $term_id ) {
                    $path = $this->orderpickingapp_get_term_breadcrumb( $term_id );

                    echo '<div class="orderpickingapp-route-badge" style="margin-bottom:8px;width: 100%;">';
                    echo '<span class="dashicons dashicons-store" aria-hidden="true"></span>';
                    echo '<span class="orderpickingapp-route-badge-text">' . esc_html( $path ) . '</span>';
                    echo '</div>';
                }
            } else {
                echo '<p style="margin:0 0 10px; color:#646970;">' . esc_html__( 'No location assigned yet.', 'order-picking-app' ) . '</p>';
            }

            echo '<p style="margin:0 0 15px 0;">';
            echo '<a class="button" style="width: 100%;" href="' . esc_url( $add_location_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Add location', 'order-picking-app' ) . '</a>';
            echo '</p>';
            echo '</div>';
        }

        public function orderpickingapp_add_pickingroute_product_column( $columns ) {
            $new_columns = array();

            foreach ( $columns as $key => $label ) {
                $new_columns[ $key ] = $label;

                // Insert after SKU if present, otherwise after name/title is also possible
                if ( 'sku' === $key ) {
                    $new_columns['orderpickingapp_pickingroute'] = __( 'Location', 'order-picking-app' );
                }
            }

            if ( ! isset( $new_columns['orderpickingapp_pickingroute'] ) ) {
                $new_columns['orderpickingapp_pickingroute'] = __( 'Location', 'order-picking-app' );
            }

            return $new_columns;
        }

        public function orderpickingapp_render_product_columns( $column, $post_id ) {
            if ( 'orderpickingapp_pickingroute' !== $column ) {
                return;
            }

            $term_ids = wp_get_post_terms(
                $post_id,
                $this->taxonomy,
                array(
                    'fields' => 'ids',
                )
            );

            if ( empty( $term_ids ) ) {
                echo '<span style="color:#8c8f94;">—</span>';
                return;
            }

            foreach ( $term_ids as $term_id ) {
                echo '<span class="orderpickingapp-route-badge">';
                echo '<span class="orderpickingapp-route-badge-text">' . esc_html( $this->orderpickingapp_get_term_breadcrumb( $term_id ) ) . '</span>';
                echo '</span>';
            }
        }

        public function orderpickingapp_add_product_tab( $tabs ) {
            $tabs['orderpickingapp_location'] = array(
                'label'    => __( 'Location', 'order-picking-app' ),
                'target'   => 'orderpickingapp_location_data',
                'class'    => array( 'show_if_simple', 'show_if_variable' ),
                'priority' => 25,
            );
            return $tabs;
        }

        public function orderpickingapp_render_product_tab() {
            global $post;

            $tree = $this->orderpickingapp_get_terms_tree();
            $selected = wp_get_post_terms( $post->ID, $this->taxonomy, array( 'fields' => 'ids' ) );
            $note = get_post_meta( $post->ID, '_orderpickingapp_location_note', true );

            $add_location_url = add_query_arg(
                array(
                    'post_type' => 'product',
                    'page'      => 'orderpickingapp-picking-route',
                    'tab'       => 'input',
                    'term_id'   => 0,
                    's'         => '',
                ),
                admin_url( 'edit.php' )
            );

            echo '<div id="orderpickingapp_location_data" class="panel woocommerce_options_panel">';

            wp_nonce_field( 'orderpickingapp_save_product_location', 'orderpickingapp_product_location_nonce' );

            echo '<div class="options_group">';

            echo '<p class="form-field">';
            echo '<label>Location</label>';

            echo '<select class="wc-enhanced-select" name="orderpickingapp_location[]" style="width:100%;">';
            $this->orderpickingapp_render_term_options( $tree, 0, $selected );
            echo '</select>';

            echo '<span class="description">Assign picking locations.</span>';
            echo '</p>';

            echo '<p class="form-field">';
            echo '<label>Location Note</label>';
            echo '<textarea name="orderpickingapp_location_note" style="width:100%;">' . esc_textarea($note) . '</textarea>';
            echo '<span class="description">Example: Handle with care.</span>';
            echo '</p>';


            echo '<p style="margin:10px 0 0; font-size:12px; color:#646970;">';
            echo esc_html__( 'Missing a location?', 'order-picking-app' ) . ' ';
            echo '<a href="' . esc_url( $add_location_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Add location', 'order-picking-app' ) . '</a>';
            echo '</p>';
            echo '</div>';
            echo '</div>';
        }

        public function orderpickingapp_variation_field( $loop, $variation_data, $variation ) {
            $variation_id = is_object( $variation ) && isset( $variation->ID ) ? (int) $variation->ID : 0;

            if ( ! $variation_id ) {
                return;
            }

            $selected = wp_get_post_terms( $variation_id, $this->taxonomy, array( 'fields' => 'ids' ) );
            $note     = get_post_meta( $variation_id, '_orderpickingapp_location_note', true );
            $tree     = $this->orderpickingapp_get_terms_tree();

            $options = array(
                '' => __( 'Select picking location', 'order-picking-app' ),
            );
            $options = $this->orderpickingapp_build_term_options_for_select( $tree, $options );

            echo '<div class="location-variation-fields" style="padding:12px; margin:12px 0; border:1px solid #1377b3; border-radius: 5px; background:#fafafa;display: table; width:100%;">';
            echo '<p><strong>' . esc_html__( 'Order Picking App | Location settings', 'order-picking-app' ) . '</strong></p>';
            wp_nonce_field(
                'orderpickingapp_save_variation_location_' . $variation_id,
                'orderpickingapp_variation_location_nonce_' . $variation_id
            );

            woocommerce_wp_select( array(
                'id'            => 'orderpickingapp_location_variation[' . $variation_id . ']',
                'label'         => __( 'Picking location', 'order-picking-app' ),
                'wrapper_class' => 'form-row form-row-first orderpickingapp-location-field',
                'value'         => $selected,
                'options'       => $options,
                'description'   => '',
                'class'         => 'wc-enhanced-select',
            ) );

            woocommerce_wp_textarea_input( array(
                'id'            => 'orderpickingapp_location_note_variation[' . $variation_id . ']',
                'label'         => __( 'Location note', 'order-picking-app' ),
                'wrapper_class' => 'form-row form-row-last orderpickingapp-location-note-field',
                'value'         => $note,
                'description'   => __( 'Example: This product is fragile.', 'order-picking-app' ),
            ) );

            echo '<p style="margin:10px 0 0; font-size:12px; color:#646970;display: inline-block;">';
            echo esc_html__( 'Need more info or support?', 'order-picking-app' ) . ' ';
            echo '<a href="https://orderpickingapp.com" target="_blank" rel="noopener noreferrer">Order Picking App</a>';
            echo '</p>';

            echo '</div>';
        }

        protected function orderpickingapp_render_term_options( $nodes, $depth = 0, $selected = array(), $parent_path = '' ) {
            $selected_ids = is_array( $selected ) ? $selected : array_filter( array( (int) $selected ) );

            foreach ( $nodes as $node ) {
                $term = $node['term'];

                $current_path = $parent_path
                    ? $parent_path . ' → ' . $term->name
                    : $term->name;

                echo '<option value="' . esc_attr( $term->term_id ) . '" '
                    . selected( in_array( (int) $term->term_id, $selected_ids, true ), true, false ) . '>'
                    . esc_html( $current_path )
                    . '</option>';

                if ( ! empty( $node['children'] ) ) {
                    $this->orderpickingapp_render_term_options(
                        $node['children'],
                        $depth + 1,
                        $selected_ids,
                        $current_path
                    );
                }
            }
        }

        protected function orderpickingapp_build_term_options_for_select( $nodes, $options = array(), $parent_path = '' ) {
            foreach ( $nodes as $node ) {
                $term = $node['term'];

                $current_path = $parent_path
                    ? $parent_path . ' - ' . $term->name
                    : $term->name;

                $options[ $term->term_id ] = $current_path;

                if ( ! empty( $node['children'] ) ) {
                    $options = $this->orderpickingapp_build_term_options_for_select( $node['children'], $options, $current_path );
                }
            }

            return $options;
        }

        public function orderpickingapp_save_product_terms( $post_id ) {
            if ( ! current_user_can( 'edit_post', $post_id ) ) {
                return;
            }

            if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
                return;
            }

            $nonce = isset( $_POST['orderpickingapp_product_location_nonce'] )
                ? sanitize_text_field( wp_unslash( $_POST['orderpickingapp_product_location_nonce'] ) )
                : '';

            if ( ! wp_verify_nonce( $nonce, 'orderpickingapp_save_product_location' ) ) {
                return;
            }

            if ( isset( $_POST['orderpickingapp_location'] ) ) {
                $terms = array_map( 'absint', (array) wp_unslash( $_POST['orderpickingapp_location'] ) );
                $terms = array_filter( $terms );
                wp_set_post_terms( $post_id, $terms, $this->taxonomy );
            } else {
                wp_set_post_terms( $post_id, array(), $this->taxonomy );
            }

            if ( isset( $_POST['orderpickingapp_location_note'] ) ) {
                update_post_meta(
                    $post_id,
                    '_orderpickingapp_location_note',
                    sanitize_textarea_field( wp_unslash( $_POST['orderpickingapp_location_note'] ) )
                );
            } else {
                delete_post_meta( $post_id, '_orderpickingapp_location_note' );
            }
        }

        public function orderpickingapp_save_variation_terms( $variation_id, $i ) {
            if ( ! current_user_can( 'edit_post', $variation_id ) ) {
                return;
            }

            $nonce_name = 'orderpickingapp_variation_location_nonce_' . $variation_id;
            $nonce      = isset( $_POST[ $nonce_name ] )
                ? sanitize_text_field( wp_unslash( $_POST[ $nonce_name ] ) )
                : '';

            if ( ! wp_verify_nonce( $nonce, 'orderpickingapp_save_variation_location_' . $variation_id ) ) {
                return;
            }

            $term_id = 0;

            if ( isset( $_POST['orderpickingapp_location_variation'][ $variation_id ] ) ) {
                $term_id = absint( wp_unslash( $_POST['orderpickingapp_location_variation'][ $variation_id ] ) );
            }

            if ( $term_id > 0 ) {
                wp_set_post_terms( $variation_id, array( $term_id ), $this->taxonomy, false );
                update_post_meta( $variation_id, 'orderpickingapp_picking_location', $term_id );
            } else {
                wp_set_post_terms( $variation_id, array(), $this->taxonomy, false );
                update_post_meta( $variation_id, 'orderpickingapp_picking_location', '' );
            }

            if ( isset( $_POST['orderpickingapp_location_note_variation'][ $variation_id ] ) ) {
                update_post_meta(
                    $variation_id,
                    '_orderpickingapp_location_note',
                    sanitize_textarea_field( wp_unslash( $_POST['orderpickingapp_location_note_variation'][ $variation_id ] ) )
                );
            } else {
                delete_post_meta( $variation_id, '_orderpickingapp_location_note' );
            }
        }

        public function orderpickingapp_hide_default_taxonomy_menu() {
            remove_submenu_page(
                'edit.php?post_type=product',
                'edit-tags.php?taxonomy=' . $this->taxonomy . '&post_type=product'
            );
        }

        public function orderpickingapp_redirect_default_taxonomy_pages( $screen ) {
            if ( ! is_admin() ) {
                return;
            }

            if ( ! isset( $screen->base, $screen->taxonomy ) ) {
                return;
            }

            if ( $screen->taxonomy !== $this->taxonomy ) {
                return;
            }

            if ( in_array( $screen->base, array( 'edit-tags', 'term' ), true ) ) {
                wp_safe_redirect( $this->orderpickingapp_get_admin_url( 'overview' ) );
                exit;
            }
        }

        public function orderpickingapp_register_pickingroute_taxonomy() {
            register_taxonomy(
                'pickingroute',
                'product',
                array(
                    'hierarchical'        => true,
                    'show_admin_column'   => false,
                    'show_in_nav_menus'   => false,
                    'show_ui'               => false,
                    'labels'              => array(
                        'name'              => 'Picking Route',
                        'singular_name'     => 'Picking Route',
                        'search_items'      => 'Search Picking Routes',
                        'all_items'         => 'All Picking Routes',
                        'parent_item'       => 'Parent Picking Route:',
                        'parent_item_colon' => 'Parent Picking Route:',
                        'edit_item'         => 'Edit Picking Route',
                        'update_item'       => 'Update Picking Route',
                        'add_new_item'      => 'Add Picking Route',
                        'new_item_name'     => 'Add Picking Route',
                        'menu_name'         => __( 'Picking Route', 'order-picking-app' ),
                    ),
                    'rewrite'             => array(
                        'slug'         => 'pickingroute',
                        'with_front'   => false,
                        'hierarchical' => true,
                    ),
                )
            );
        }

        public function orderpickingapp_register_admin_page() {
            add_submenu_page(
                $this->parent_slug,
                __( 'Picking Route', 'order-picking-app' ),
                __( 'Picking Route', 'order-picking-app' ),
                'manage_categories',
                $this->menu_slug,
                array( $this, 'orderpickingapp_render_admin_page' )
            );
        }

        public function orderpickingapp_render_admin_page() {
            if ( ! current_user_can( 'manage_categories' ) ) {
                wp_die( esc_html__( 'You do not have permission to view this page.', 'order-picking-app' ) );
            }

            if ( ! taxonomy_exists( $this->taxonomy ) ) {
                echo '<div class="wrap"><h1>Picking Route UI</h1>';
                echo '<div class="notice notice-error"><p>' . esc_html__( 'The pickingroute taxonomy does not exist.', 'order-picking-app' ) . '</p></div>';
                echo '</div>';
                return;
            }

            $nonce_valid = isset( $_GET['orderpickingapp_nonce'] ) &&
                wp_verify_nonce(
                    sanitize_text_field( wp_unslash( $_GET['orderpickingapp_nonce'] ) ),
                    'orderpickingapp_admin_view'
                );

            if ( ! $nonce_valid ) {
                $active_tab  = 'input';
                $selected_id = 0;
                $search      = '';
            } else {
                $active_tab  = isset( $_GET['tab'] )
                    ? sanitize_key( wp_unslash( $_GET['tab'] ) )
                    : 'input';

                $selected_id = isset( $_GET['term_id'] )
                    ? absint( wp_unslash( $_GET['term_id'] ) )
                    : 0;

                $search = isset( $_GET['s'] )
                    ? sanitize_text_field( wp_unslash( $_GET['s'] ) )
                    : '';
            }

            $terms = $this->orderpickingapp_get_terms_tree();

            echo '<div class="wrap orderpickingapp-pickingroute">';
            echo '<h1 class="wp-heading-inline">' . esc_html__( 'Order Picking App | Picking Route', 'order-picking-app' ) . '</h1>';

            $this->orderpickingapp_render_inline_styles();
            $this->orderpickingapp_render_tabs( $active_tab, $selected_id, $search );

            echo '<div class="orderpickingapp-shell">';

            switch ( $active_tab ) {
                case 'overview':
                    $this->orderpickingapp_render_overview_tab( $terms, $selected_id, $search );
                    break;

                case 'export':
                    $this->orderpickingapp_render_export_tab();
                    break;

                case 'input':
                default:
                    $this->orderpickingapp_render_input_tab( $terms );
                    break;
            }

            echo '</div>';
            echo '</div>';
        }

        protected function orderpickingapp_render_tabs( $active_tab, $selected_id, $search ) {
            $base_url = admin_url( 'edit.php?post_type=product&page=' . $this->menu_slug );

            $tabs = array(
                'input'    => __( 'Input', 'order-picking-app' ),
                'overview' => __( 'Structure Overview', 'order-picking-app' ),
                'export'   => __( 'Export', 'order-picking-app' ),
            );

            echo '<nav class="nav-tab-wrapper wp-clearfix" style="margin-bottom:20px;">';
            foreach ( $tabs as $slug => $label ) {
                $url = wp_nonce_url(
                    add_query_arg(
                        array(
                            'tab'     => $slug,
                            'term_id' => $selected_id,
                            's'       => $search,
                        ),
                        $base_url
                    ),
                    'orderpickingapp_admin_view',
                    'orderpickingapp_nonce'
                );

                $class = ( $active_tab === $slug ) ? ' nav-tab-active' : '';
                echo '<a href="' . esc_url( $url ) . '" class="nav-tab' . esc_attr( $class ) . '">' . esc_html( $label ) . '</a>';
            }
            echo '</nav>';
        }

        protected function orderpickingapp_render_input_tab( $tree ) {
            // phpcs:disable WordPress.Security.NonceVerification.Recommended
            $selected_parent = isset( $_GET['parent'] )
                ? absint( wp_unslash( $_GET['parent'] ) )
                : 0;
            // phpcs:enable WordPress.Security.NonceVerification.Recommended

            echo '<div class="orderpickingapp-grid orderpickingapp-grid-2">';

            echo '<div class="orderpickingapp-card">';
            echo '<div class="orderpickingapp-card-header"><h2>' . esc_html__( 'Add New Location', 'order-picking-app' ) . '</h2><p>' . esc_html__( 'Quickly create a new floor, rack, or bin within the existing structure.', 'order-picking-app' ) . '</p></div>';
            echo '<div class="orderpickingapp-card-body">';

            echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '">';
            wp_nonce_field( 'orderpickingapp_add_pickingroute_term', 'orderpickingapp_nonce' );
            echo '<input type="hidden" name="action" value="orderpickingapp_add_pickingroute_term" />';

            echo '<table class="form-table" role="presentation">';

            echo '<tr>';
            echo '<th scope="row"><label for="orderpickingapp_name">' . esc_html__( 'Name', 'order-picking-app' ) . '</label></th>';
            echo '<td><input name="name" type="text" id="orderpickingapp_name" class="regular-text" required />';
            echo '<p class="description">' . esc_html__( 'Example: Floor 1, Rack 2, or Bin C.', 'order-picking-app' ) . '</p></td>';
            echo '</tr>';

            echo '<tr>';
            echo '<th scope="row"><label for="orderpickingapp_parent">' . esc_html__( 'Parent Location', 'order-picking-app' ) . '</label></th>';
            echo '<td>';
            echo '<select name="parent" id="orderpickingapp_parent">';
            echo '<option value="0"' . selected( $selected_parent, 0, false ) . '>' . esc_html__( 'None (top level)', 'order-picking-app' ) . '</option>';
            $this->orderpickingapp_render_term_options( $tree, 0, $selected_parent );
            echo '</select>';
            echo '<p class="description">' . esc_html__( 'Choose where this location should appear in the warehouse tree.', 'order-picking-app' ) . '</p>';
            echo '</td>';
            echo '</tr>';

            echo '<tr>';
            echo '<th scope="row"><label for="orderpickingapp_slug">' . esc_html__( 'Slug', 'order-picking-app' ) . '</label></th>';
            echo '<td><input name="slug" type="text" id="orderpickingapp_slug" class="regular-text" />';
            echo '<p class="description">' . esc_html__( 'Optional. Leave empty to generate it automatically.', 'order-picking-app' ) . '</p></td>';
            echo '</tr>';

            echo '<tr>';
            echo '<th scope="row"><label for="orderpickingapp_description">' . esc_html__( 'Description', 'order-picking-app' ) . '</label></th>';
            echo '<td><textarea name="description" id="orderpickingapp_description" rows="5" class="large-text"></textarea></td>';
            echo '</tr>';

            echo '</table>';

            echo '<p class="submit" style="margin-bottom:0;display:flex;gap:10px;align-items:center;">';
            echo '<button type="submit" class="button">' . esc_html__( 'Add Location', 'order-picking-app' ) . '</button>';
            echo '</p>';

            echo '</form>';
            echo '</div>';
            echo '</div>';

            echo '<div class="orderpickingapp-card">';
            echo '<div class="orderpickingapp-card-header"><h2>' . esc_html__( 'Live Structure Preview', 'order-picking-app' ) . '</h2><p>' . esc_html__( 'Use this panel to quickly review the current warehouse structure.', 'order-picking-app' ) . '</p></div>';
            echo '<div class="orderpickingapp-card-body">';

            if ( empty( $tree ) ) {
                echo '<p>' . esc_html__( 'No picking routes have been created yet.', 'order-picking-app' ) . '</p>';
            } else {
                echo '<div class="orderpickingapp-tree">';
                $this->orderpickingapp_render_tree_list( $tree );
                echo '</div>';
            }

            echo '</div>';
            echo '</div>';

            echo '</div>';
        }

        protected function orderpickingapp_render_overview_tab( $tree, $selected_id, $search ) {
            echo '<div class="orderpickingapp-grid orderpickingapp-grid-overview">';

            echo '<div class="orderpickingapp-card">';
            echo '<div class="orderpickingapp-card-header orderpickingapp-toolbar">';
            echo '<div><h2>' . esc_html__( 'Warehouse Structure', 'order-picking-app' ) . '</h2><p>' . esc_html__( 'Full tree structure of all picking routes.', 'order-picking-app' ) . '</p></div>';
            echo '<form method="get" action="">';
            echo '<input type="hidden" name="post_type" value="product" />';
            echo '<input type="hidden" name="page" value="' . esc_attr( $this->menu_slug ) . '" />';
            echo '<input type="hidden" name="tab" value="overview" />';
            echo '<input type="search" name="s" value="' . esc_attr( $search ) . '" placeholder="' . esc_attr__( 'Search location...', 'order-picking-app' ) . '" /> ';
            echo '<button type="submit" class="button">' . esc_html__( 'Search', 'order-picking-app' ) . '</button>';
            echo '</form>';
            echo '</div>';
            echo '<div class="orderpickingapp-card-body">';

            if ( empty( $tree ) ) {
                echo '<p>' . esc_html__( 'No locations found.', 'order-picking-app' ) . '</p>';
            } else {
                echo '<div class="orderpickingapp-tree">';
                $this->orderpickingapp_render_tree_list( $tree, $selected_id, $search );
                echo '</div>';
            }

            echo '</div>';
            echo '</div>';

            echo '<div class="orderpickingapp-card">';
            echo '<div class="orderpickingapp-card-header"><h2>' . esc_html__( 'Location Details', 'order-picking-app' ) . '</h2><p>' . esc_html__( 'Select a node in the tree to view details and quick actions.', 'order-picking-app' ) . '</p></div>';
            echo '<div class="orderpickingapp-card-body">';

            if ( $selected_id ) {
                $term = get_term( $selected_id, $this->taxonomy );
                if ( $term && ! is_wp_error( $term ) ) {
                    $children = get_terms(
                        array(
                            'taxonomy'   => $this->taxonomy,
                            'hide_empty' => false,
                            'parent'     => $term->term_id,
                        )
                    );

                    echo '<h3 style="margin-top:0;">' . esc_html( $term->name ) . '</h3>';
                    echo '<table class="widefat striped" style="margin-bottom:16px;">';
                    echo '<tbody>';
                    echo '<tr><td style="width:180px;"><strong>' . esc_html__( 'Full Path', 'order-picking-app' ) . '</strong></td><td>' . esc_html( $this->orderpickingapp_get_term_breadcrumb( $term->term_id ) ) . '</td></tr>';
                    echo '<tr><td><strong>' . esc_html__( 'Slug', 'order-picking-app' ) . '</strong></td><td>' . esc_html( $term->slug ) . '</td></tr>';
                    echo '<tr><td><strong>' . esc_html__( 'Description', 'order-picking-app' ) . '</strong></td><td>' . ( $term->description ? esc_html( $term->description ) : '—' ) . '</td></tr>';
                    echo '<tr><td><strong>' . esc_html__( 'Sub-locations', 'order-picking-app' ) . '</strong></td><td>' . esc_html( count( $children ) ) . '</td></tr>';
                    echo '</tbody>';
                    echo '</table>';

                    $add_child = add_query_arg(
                        array(
                            'post_type' => 'product',
                            'page'      => $this->menu_slug,
                            'tab'       => 'input',
                            'parent'    => $term->term_id,
                        ),
                        admin_url( 'edit.php' )
                    );

                    echo '<div style="display:flex;gap:10px;flex-wrap:wrap;">';
                    echo '<a class="button" href="' . esc_url( $add_child ) . '">' . esc_html__( 'Add Sub-location', 'order-picking-app' ) . '</a>';
                    echo '</div>';

                    $this->orderpickingapp_render_linked_products_table( $term->term_id );
                } else {
                    echo '<p>' . esc_html__( 'The selected location could not be loaded.', 'order-picking-app' ) . '</p>';
                }
            } else {
                echo '<p>' . esc_html__( 'No location selected yet. Click a location in the tree on the left.', 'order-picking-app' ) . '</p>';
            }

            echo '</div>';
            echo '</div>';

            echo '</div>';
        }

        protected function orderpickingapp_render_export_tab() {
            echo '<div class="orderpickingapp-grid orderpickingapp-grid-2">';

            echo '<div class="orderpickingapp-card">';
            echo '<div class="orderpickingapp-card-header"><h2>' . esc_html__( 'PDF Export', 'order-picking-app' ) . '</h2><p>' . esc_html__( 'Export the warehouse structure as a base document for internal use or onboarding.', 'order-picking-app' ) . '</p></div>';
            echo '<div class="orderpickingapp-card-body">';

            echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '">';
            wp_nonce_field( 'orderpickingapp_export_pickingroutes_pdf', 'orderpickingapp_export_nonce' );
            echo '<input type="hidden" name="action" value="orderpickingapp_export_pickingroutes_pdf" />';

            echo '<table class="form-table" role="presentation">';
            echo '<tr>';
            echo '<th scope="row"><label for="export_scope">' . esc_html__( 'Export Type', 'order-picking-app' ) . '</label></th>';
            echo '<td>';
            echo '<select name="export_scope" id="export_scope">';
            echo '<option value="all">' . esc_html__( 'Full Warehouse Structure', 'order-picking-app' ) . '</option>';
            echo '</select>';
            echo '</td>';
            echo '</tr>';
            echo '</table>';

            echo '<p class="submit" style="margin-bottom:0;">';
            echo '<button type="submit" class="button">' . esc_html__( 'Export PDF', 'order-picking-app' ) . '</button>';
            echo '</p>';
            echo '</form>';

            echo '</div>';
            echo '</div>';
        }

        public function orderpickingapp_handle_add_term() {
            if ( ! current_user_can( 'manage_categories' ) ) {
                wp_die( esc_html__( 'Insufficient permissions.', 'order-picking-app' ) );
            }

            check_admin_referer( 'orderpickingapp_add_pickingroute_term', 'orderpickingapp_nonce' );

            $name        = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
            $slug        = isset( $_POST['slug'] ) ? sanitize_title( wp_unslash( $_POST['slug'] ) ) : '';
            $description = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';
            $parent      = isset( $_POST['parent'] ) ? absint( $_POST['parent'] ) : 0;

            if ( empty( $name ) ) {
                wp_safe_redirect( $this->orderpickingapp_get_admin_url( 'input' ) );
                exit;
            }

            $args = array(
                'description' => $description,
                'parent'      => $parent,
            );

            if ( ! empty( $slug ) ) {
                $args['slug'] = $slug;
            }

            wp_insert_term( $name, $this->taxonomy, $args );

            wp_safe_redirect( $this->orderpickingapp_get_admin_url( 'overview' ) );
            exit;
        }

        public function orderpickingapp_handle_export_pdf() {
            if ( ! current_user_can( 'manage_categories' ) ) {
                wp_die( esc_html__( 'Insufficient permissions.', 'order-picking-app' ) );
            }

            check_admin_referer( 'orderpickingapp_export_pickingroutes_pdf', 'orderpickingapp_export_nonce' );

            if ( ! class_exists( '\Dompdf\Dompdf' ) ) {
                wp_die( esc_html__( 'Dompdf is not installed.', 'order-picking-app' ) );
            }

            $tree = $this->orderpickingapp_get_terms_tree();
            $html = $this->orderpickingapp_build_export_html( $tree );

            $dompdf = new \Dompdf\Dompdf(
                array(
                    'isRemoteEnabled' => false,
                    'defaultFont'     => 'DejaVu Sans',
                )
            );

            $dompdf->loadHtml( $html, 'UTF-8' );
            $dompdf->setPaper( 'A4', 'portrait' );
            $dompdf->render();

            nocache_headers();
            header( 'Content-Type: application/pdf' );
            header( 'Content-Disposition: attachment; filename=\"picking-routes-export.pdf\"' );

            echo $dompdf->output(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            exit;
        }

        protected function orderpickingapp_build_export_html( $tree ) {
            ob_start();

            $logo_base64 = '';
            $logo_path = OPA_PLUGIN_DIR . 'admin/images/orderpickingapp.png';
            if ( file_exists( $logo_path ) ) {
                $logo_data   = file_get_contents( $logo_path );
                $logo_type   = pathinfo( $logo_path, PATHINFO_EXTENSION );
                $logo_base64 = 'data:image/' . $logo_type . ';base64,' . base64_encode( $logo_data );
            }
            ?>
            <!doctype html>
            <html lang="en">
            <head>
                <meta charset="utf-8">
                <title>Picking Routes Export</title>
                <style>
                    body {
                        font-family: DejaVu Sans, Arial, sans-serif;
                        color: #1d2327;
                        margin: 40px;
                        font-size: 13px;
                    }
                    .header {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        margin-bottom: 30px;
                        border-bottom: 2px solid #0b163f;
                        padding-bottom: 15px;
                    }
                    .logo img {
                        height: 40px;
                    }
                    .title {
                        text-align: right;
                    }
                    h1 {
                        margin: 0;
                        font-size: 22px;
                        color: #0b163f;
                    }
                    .meta {
                        color: #666;
                        font-size: 12px;
                    }
                    ul {
                        list-style: none;
                        padding-left: 20px;
                    }
                    li {
                        margin: 6px 0;
                    }
                    .footer {
                        margin-top: 40px;
                        padding-top: 10px;
                        border-top: 1px solid #ddd;
                        font-size: 11px;
                        color: #888;
                        text-align: center;
                    }
                    .footer {
                        margin-top: 40px;
                        padding-top: 18px;
                        border-top: 1px solid #d9dee5;
                    }
                    .footer {
                        margin-top: 40px;
                        padding-top: 18px;
                        border-top: 1px solid #d9dee5;
                    }

                    .footer-cta-table {
                        margin-bottom: 16px;
                    }

                    .footer-cta-cell {
                        width: 33.33%;
                        background: #f4f7fb;
                        border: 1px solid #d9e4f2;
                        border-radius: 10px;
                        padding: 14px 12px;
                    }

                    .footer-cta-title {
                        font-size: 14px;
                        font-weight: 700;
                        color: #0b163f;
                        margin-bottom: 6px;
                    }

                    .footer-cta-text {
                        font-size: 11px;
                        line-height: 1.45;
                        color: #5b6574;
                    }

                    .footer-powered {
                        margin-top: 10px;
                        font-size: 11px;
                        text-align: center;
                        color: #7a7a7a;
                    }

                    .footer-powered a {
                        color: #0b163f;
                        text-decoration: none;
                        font-weight: 700;
                    }
                </style>
            </head>
            <body>
            <div class="header">
                <div class="logo">
                    <?php if ( $logo_base64 ) : ?>
                        <img src="<?php echo esc_attr( $logo_base64 ); ?>" style="height:100px;" />
                    <?php endif; ?>
                </div>
                <div class="title">
                    <h1>Picking Routes</h1>
                    <div class="meta">
                        Generated on <?php echo esc_html( wp_date( 'd-m-Y H:i' ) ); ?>
                    </div>
                </div>
            </div>
            <?php $this->orderpickingapp_render_export_tree_html( $tree ); ?>
            <div class="footer">
                <table class="footer-cta-table" width="100%" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td class="footer-cta-cell">
                            <div class="footer-cta-title">Pick 3 times faster</div>
                            <div class="footer-cta-text">No more inefficient routes for order picking.</div>
                        </td>
                        <td class="footer-cta-cell">
                            <div class="footer-cta-title">Paperless</div>
                            <div class="footer-cta-text">No need for prints anymore. Use your phone instead.</div>
                        </td>
                        <td class="footer-cta-cell">
                            <div class="footer-cta-title">No more mistakes</div>
                            <div class="footer-cta-text">Scan a barcode before picking.</div>
                        </td>
                    </tr>
                </table>
            </div>
            </body>
            </html>
            <?php
            return ob_get_clean();
        }

        protected function orderpickingapp_render_export_tree_html( $nodes ) {
            if ( empty( $nodes ) ) {
                return;
            }

            echo '<ul>';
            foreach ( $nodes as $node ) {
                echo '<li>' . esc_html( $node['term']->name );
                if ( ! empty( $node['children'] ) ) {
                    $this->orderpickingapp_render_export_tree_html( $node['children'] );
                }
                echo '</li>';
            }
            echo '</ul>';
        }

        protected function orderpickingapp_render_tree_list( $nodes, $selected_id = 0, $search = '' ) {
            if ( empty( $nodes ) ) {
                return;
            }

            echo '<ul>';
            foreach ( $nodes as $node ) {
                $term = $node['term'];

                if ( $search && false === stripos( $term->name, $search ) && ! $this->orderpickingapp_tree_contains_match( $node, $search ) ) {
                    continue;
                }

                $is_selected = (int) $selected_id === (int) $term->term_id;
                $link        = add_query_arg(
                    array(
                        'post_type' => 'product',
                        'page'      => $this->menu_slug,
                        'tab'       => 'overview',
                        'term_id'   => $term->term_id,
                        's'         => $search,
                    ),
                    admin_url( 'edit.php' )
                );

                echo '<li>';
                echo '<a class="orderpickingapp-tree-node' . ( $is_selected ? ' is-active' : '' ) . '" href="' . esc_url( $link ) . '">';
                echo '<span class="dashicons dashicons-category" style="font-size:16px;width:16px;height:16px;"></span>';
                echo '<span>' . esc_html( $term->name ) . '</span>';
                echo '</a>';

                if ( ! empty( $node['children'] ) ) {
                    $this->orderpickingapp_render_tree_list( $node['children'], $selected_id, $search );
                }

                echo '</li>';
            }
            echo '</ul>';
        }

        protected function orderpickingapp_tree_contains_match( $node, $search ) {
            if ( empty( $node['children'] ) ) {
                return false;
            }

            foreach ( $node['children'] as $child ) {
                if ( false !== stripos( $child['term']->name, $search ) ) {
                    return true;
                }

                if ( $this->orderpickingapp_tree_contains_match( $child, $search ) ) {
                    return true;
                }
            }

            return false;
        }

        protected function orderpickingapp_get_terms_tree() {
            $terms = get_terms(array(
                'taxonomy'=>$this->taxonomy,
                'hide_empty'=>false
            ));

            $indexed=[];
            foreach($terms as $t){
                $indexed[$t->term_id]=['term'=>$t,'children'=>[]];
            }

            $tree=[];
            foreach($indexed as $id=>&$node){
                $parent=$node['term']->parent;
                if($parent && isset($indexed[$parent])){
                    $indexed[$parent]['children'][]=&$node;
                } else {
                    $tree[]=&$node;
                }
            }

            return $tree;
        }

        protected function orderpickingapp_get_term_breadcrumb( $term_id ) {
            $ancestors = array_reverse( get_ancestors( $term_id, $this->taxonomy, 'taxonomy' ) );
            $names     = array();

            foreach ( $ancestors as $ancestor_id ) {
                $ancestor = get_term( $ancestor_id, $this->taxonomy );
                if ( $ancestor && ! is_wp_error( $ancestor ) ) {
                    $names[] = $ancestor->name;
                }
            }

            $term = get_term( $term_id, $this->taxonomy );
            if ( $term && ! is_wp_error( $term ) ) {
                $names[] = $term->name;
            }

            return implode( ' > ', $names );
        }

        protected function orderpickingapp_get_admin_url( $tab = 'input' ) {
            return add_query_arg(
                array(
                    'post_type' => 'product',
                    'page'      => $this->menu_slug,
                    'tab'       => $tab,
                ),
                admin_url( 'edit.php' )
            );
        }

        protected function orderpickingapp_render_inline_styles() {
            echo '<style>
                .orderpickingapp-shell { margin-top: 8px; }
                .orderpickingapp-grid { display: grid; gap: 20px; }
                .orderpickingapp-grid-2 { grid-template-columns: minmax(420px, 1.1fr) minmax(320px, 0.9fr); }
                .orderpickingapp-grid-overview { grid-template-columns: minmax(420px, 1.2fr) minmax(320px, 0.8fr); }
                .orderpickingapp-card { background: #fff; border: 1px solid #dcdcde; border-radius: 14px; overflow: hidden; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
                .orderpickingapp-card-header { padding: 18px 20px; border-bottom: 1px solid #f0f0f1; background: #fff; }
                .orderpickingapp-card-header h2 { margin: 0 0 4px; font-size: 18px; }
                .orderpickingapp-card-header p { margin: 0; color: #50575e; }
                .orderpickingapp-card-body { padding: 20px; }
                .orderpickingapp-toolbar { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; flex-wrap: wrap; }
                .orderpickingapp-tree ul { list-style: none; margin: 0; padding-left: 18px; }
                .orderpickingapp-tree > ul { padding-left: 0; }
                .orderpickingapp-tree li { margin: 6px 0; }
                .orderpickingapp-tree-node { display: inline-flex; align-items: center; gap: 8px; padding: 8px 10px; border-radius: 10px; text-decoration: none; color: #1d2327; }
                .orderpickingapp-tree-node:hover { background: #f6f7f7; }
                .orderpickingapp-tree-node.is-active { background: #edf4ff; color: #0a4b78; font-weight: 600; }
                @media (max-width: 1080px) {
                    .orderpickingapp-grid-2,
                    .orderpickingapp-grid-overview { grid-template-columns: 1fr; }
                }
                .orderpickingapp-pickingroute .nav-tab { border-top-left-radius: 5px; border-top-right-radius: 5px; background: #1377b3; color: #fff; border-top: none; }
                .orderpickingapp-pickingroute .nav-tab-wrapper { border-bottom: 1px solid #1377b3; }
                .orderpickingapp-pickingroute .orderpickingapp-card-body .button:hover, .orderpickingapp-pickingroute .orderpickingapp-card-body .button:active, .orderpickingapp-pickingroute .orderpickingapp-card-body .button:focus, .orderpickingapp-pickingroute .orderpickingapp-card-body .button.active, .orderpickingapp-pickingroute .orderpickingapp-card-body .button { color: #fff; border-color: #13a940; background-color: #13a940; }
            </style>';
        }

        protected function orderpickingapp_render_linked_products_table( $term_id ) {
            $query = new WP_Query( array(
                'post_type'      => array( 'product', 'product_variation' ),
                'post_status'    => array( 'publish', 'private' ),
                'posts_per_page' => 100,
                'orderby'        => 'title',
                'order'          => 'ASC',
                'tax_query'      => array(
                    array(
                        'taxonomy' => 'pickingroute',
                        'field'    => 'term_id',
                        'terms'    => $term_id,
                    ),
                ),
            ) );

            echo '<h3 style="margin-top:24px;">' . esc_html__( 'Linked Products', 'order-picking-app' ) . '</h3>';

            if ( ! $query->have_posts() ) {
                echo '<p>' . esc_html__( 'No products are linked to this location yet.', 'order-picking-app' ) . '</p>';
                return;
            }

            echo '<table class="widefat striped" style="margin-top:12px;">';
            echo '<thead>';
            echo '<tr>';
            echo '<th style="width:70px;">' . esc_html__( 'Image', 'order-picking-app' ) . '</th>';
            echo '<th>' . esc_html__( 'Product Name', 'order-picking-app' ) . '</th>';
            echo '<th style="width:140px;">' . esc_html__( 'SKU', 'order-picking-app' ) . '</th>';
            echo '<th style="width:120px;">' . esc_html__( 'Stock', 'order-picking-app' ) . '</th>';
            echo '</tr>';
            echo '</thead>';
            echo '<tbody>';

            while ( $query->have_posts() ) {
                $query->the_post();

                $product = wc_get_product( get_the_ID() );

                if ( ! $product ) {
                    continue;
                }

                $product_id   = $product->get_id();
                $image        = $product->get_image( array( 48, 48 ) );
                $name         = $product->get_name();
                $sku          = $product->get_sku();
                $stock_amount = $product->get_stock_quantity();
                $stock_status = $product->get_stock_status();
                $edit_link    = get_edit_post_link( $product_id );

                if ( null === $stock_amount ) {
                    $stock_display = $stock_status ? ucfirst( $stock_status ) : '—';
                } else {
                    $stock_display = $stock_amount;
                }

                echo '<tr>';
                echo '<td>' . ( $image ? wp_kses_post( $image ) : '&mdash;' ) . '</td>';
                echo '<td>';
                if ( $edit_link ) {
                    echo '<a href="' . esc_url( $edit_link ) . '"><strong>' . esc_html( $name ) . '</strong></a>';
                } else {
                    echo '<strong>' . esc_html( $name ) . '</strong>';
                }

                if ( $product->is_type( 'variation' ) ) {
                    $parent_id = $product->get_parent_id();
                    if ( $parent_id ) {
                        echo '<br><small style="color:#646970;">' . esc_html__( 'Variation of', 'order-picking-app' ) . ' ';
                        echo esc_html( get_the_title( $parent_id ) );
                        echo '</small>';
                    }
                }
                echo '</td>';
                echo '<td>' . ( $sku ? esc_html( $sku ) : '—' ) . '</td>';
                echo '<td>' . esc_html( $stock_display ) . '</td>';
                echo '</tr>';
            }

            echo '</tbody>';
            echo '</table>';

            wp_reset_postdata();
        }
    }


}

new OPA_Picking_Route();