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

/**
 * SVLD_Order_Loop — adds Print Labels bulk action
 * to the WooCommerce Orders admin list.
 */
class SVLD_Order_Loop {

    public function __construct() {
        // Legacy post-based orders
        add_filter( 'bulk_actions-edit-shop_order',        [ $this, 'register_bulk_action' ] );
        add_filter( 'handle_bulk_actions-edit-shop_order', [ $this, 'handle_bulk_action' ], 10, 3 );

        // HPOS orders list
        add_filter( 'bulk_actions-woocommerce_page_wc-orders',        [ $this, 'register_bulk_action' ] );
        add_filter( 'handle_bulk_actions-woocommerce_page_wc-orders', [ $this, 'handle_bulk_action' ], 10, 3 );

        add_action( 'admin_notices', [ $this, 'bulk_action_notice' ] );

        // Per-row print button in the Actions column (works for both HPOS and legacy)
        add_action( 'woocommerce_admin_order_actions_end', [ $this, 'render_row_print_button' ] );

        // Custom print column
        add_filter( 'manage_edit-shop_order_columns', [ $this, 'add_print_column' ] );
        add_filter( 'manage_woocommerce_page_wc-orders_columns', [ $this, 'add_print_column' ] );
        add_action( 'manage_shop_order_posts_custom_column', [ $this, 'render_print_column' ], 10, 2 );
        add_action( 'manage_woocommerce_page_wc-orders_custom_column', [ $this, 'render_print_column_hpos' ], 10, 2 );

        // Enqueue JS for the orders list page
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_list_scripts' ] );
    }

    // -----------------------------------------------------------------------

    public function render_row_print_button( WC_Order $order ): void {
        $nonce = wp_create_nonce( 'svld_nonce' );
        printf(
            '<button type="button"
                class="button wc-action-button svld-print-order-row"
                data-order-id="%d"
                data-nonce="%s"
                aria-label="%s"
                title="%s"
                style="display:inline-flex;align-items:center;justify-content:center;">
                <span class="dashicons dashicons-printer" style="font-size:16px;width:16px;height:16px;"></span>
            </button>',
            absint( $order->get_id() ),
            esc_attr( $nonce ),
            esc_attr__( 'Print Label', 'scanvault-label-designer' ),
            esc_attr__( 'Print Label', 'scanvault-label-designer' )
        );
    }

    // -----------------------------------------------------------------------

    public function add_print_column( array $columns ): array {
        $columns['svld_print_order'] = 'Print Label';
        return $columns;
    }

    public function render_print_column( string $column, int $post_id ): void {
        if ( $column !== 'svld_print_order' ) return;

        $order = wc_get_order( $post_id );
        if ( ! $order ) return;

        $nonce = wp_create_nonce( 'svld_nonce' );
        printf(
            '<button type="button" class="button svld-quick-print-order" data-id="%d" data-nonce="%s" title="%s">
                <span class="dashicons dashicons-printer"></span>
            </button>',
            absint( $order->get_id() ),
            esc_attr( $nonce ),
            esc_attr__( 'Print Label', 'scanvault-label-designer' )
        );
    }

    public function render_print_column_hpos( string $column, $order_id ): void {
        if ( $column !== 'svld_print_order' ) return;

        $order = wc_get_order( $order_id );
        if ( ! $order ) return;

        $nonce = wp_create_nonce( 'svld_nonce' );
        printf(
            '<button type="button" class="button svld-quick-print-order" data-id="%d" data-nonce="%s" title="%s">
                <span class="dashicons dashicons-printer"></span>
            </button>',
            absint( $order->get_id() ),
            esc_attr( $nonce ),
            esc_attr__( 'Print Label', 'scanvault-label-designer' )
        );
    }

    // -----------------------------------------------------------------------

    public function register_bulk_action( array $actions ): array {
        $actions['svld_print_order_labels'] = __( 'Print Order Labels', 'scanvault-label-designer' );
        return $actions;
    }

    public function handle_bulk_action( string $redirect, string $action, array $ids ): string {
        if ( $action !== 'svld_print_order_labels' ) {
            return $redirect;
        }

        // Store the IDs in a transient so we can trigger the PDF download
        $transient_key = 'svld_order_bulk_' . get_current_user_id();
        set_transient( $transient_key, $ids, 5 * MINUTE_IN_SECONDS );

        $redirect = add_query_arg( [
            'svld_order_bulk_done'  => count( $ids ),
            'svld_order_bulk_key'   => $transient_key,
            'svld_order_bulk_nonce' => wp_create_nonce( 'svld_order_bulk_action' ),
        ], $redirect );

        return $redirect;
    }

    public function bulk_action_notice(): void {
        if ( ! isset( $_GET['svld_order_bulk_done'] ) || ! isset( $_GET['svld_order_bulk_key'] ) ) {
            return;
        }

        if ( ! isset( $_GET['svld_order_bulk_nonce'] ) ||
             ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['svld_order_bulk_nonce'] ) ), 'svld_order_bulk_action' ) ) {
            return;
        }

        if ( ! current_user_can( 'edit_shop_orders' ) ) {
            return;
        }

        $count        = absint( wp_unslash( $_GET['svld_order_bulk_done'] ) );
        $transient_key = 'svld_order_bulk_' . sanitize_key( wp_unslash( $_GET['svld_order_bulk_key'] ?? '' ) );
        $ids          = get_transient( $transient_key );

        if ( ! is_array( $ids ) || empty( $ids ) ) {
            return;
        }

        $ids_csv = implode( ',', array_map( 'intval', $ids ) );
        $nonce   = wp_create_nonce( 'svld_nonce' );
        ?>
        <div class="notice notice-success svld-bulk-notice">
            <p>
                <?php
                printf(
                    // translators: %d is the number of labels printed
                    esc_html( _n(
                        '%d order queued for label printing.',
                        '%d orders queued for label printing.',
                        $count,
                        'scanvault-label-designer'
                    ) ),
                    esc_html( $count )
                ); ?>
                <button type="button"
                        class="button svld-trigger-order-bulk-print"
                        data-ids="<?php echo esc_attr( $ids_csv ); ?>"
                        data-nonce="<?php echo esc_attr( $nonce ); ?>">
                    <span class="dashicons dashicons-printer" style="vertical-align:middle;"></span>
                    <?php esc_html_e( 'Download PDF', 'scanvault-label-designer' ); ?>
                </button>
                <span class="svld-bulk-spinner" style="display:none;">
                    <span class="spinner is-active" style="float:none;margin:0 4px;"></span>
                    <?php esc_html_e( 'Generating PDF…', 'scanvault-label-designer' ); ?>
                </span>
            </p>
        </div>
        <?php
        delete_transient( $transient_key );
    }

    // -----------------------------------------------------------------------

    public function enqueue_list_scripts( string $hook ): void {
        $screen = get_current_screen();
        $is_orders_list = (
            ( $hook === 'edit.php' && sanitize_text_field( wp_unslash( $_GET['post_type'] ?? '' ) ) === 'shop_order' ) ||
            ( $screen && (
                $screen->id === 'woocommerce_page_wc-orders' ||
                str_contains( $screen->id, 'wc-orders' ) ||
                str_contains( $hook, 'wc-orders' )
            ) )
        );

        if ( ! $is_orders_list ) {
            return;
        }

        wp_enqueue_style(
            'svld-designer',
            SVLD_PLUGIN_URL . 'assets/css/designer.css',
            [],
            SVLD_VERSION
        );

        wp_enqueue_script(
            'svld-order-list',
            SVLD_PLUGIN_URL . 'assets/js/order-list.js',
            [ 'jquery' ],
            SVLD_VERSION,
            true
        );

        wp_localize_script( 'svld-order-list', 'svld_order_list_params', [
            'ajax_url'          => admin_url( 'admin-ajax.php' ),
            'nonce'             => wp_create_nonce( 'svld_nonce' ),
            'generating'        => __( 'Generating PDF…', 'scanvault-label-designer' ),
            'error'             => __( 'PDF generation failed. Please try again.', 'scanvault-label-designer' ),
            'bulk_action_label' => __( 'Print Order Labels', 'scanvault-label-designer' ),
        ] );
    }
}
