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

/**
 * SVLD_Product_Loop — adds Print Labels bulk action and column button
 * to the WooCommerce Products admin list.
 */
class SVLD_Product_Loop {

    public function __construct() {
        // Quick print column
        add_filter( 'manage_product_posts_columns', [ $this, 'add_print_column' ] );
        add_action( 'manage_product_posts_custom_column', [ $this, 'render_print_column' ], 10, 2 );

        // Bulk print action
        if ( get_option( 'svld_print_bulk_action', '1' ) === '1' ) {
            add_filter( 'bulk_actions-edit-product',        [ $this, 'register_bulk_action' ] );
            add_filter( 'handle_bulk_actions-edit-product', [ $this, 'handle_bulk_action' ], 10, 3 );
            add_action( 'admin_notices',                    [ $this, 'bulk_action_notice' ] );
        }

        // Script enqueue always (needed for metabox print, free users can print default template)
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_list_scripts' ] );
    }

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

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

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

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

        $redirect = add_query_arg( [
            'svld_bulk_done'  => count( $ids ),
            'svld_bulk_key'   => $transient_key,
            'svld_bulk_nonce' => wp_create_nonce( 'svld_bulk_action' ),
        ], $redirect );

        return $redirect;
    }

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

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

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

        $count        = absint( wp_unslash( $_GET['svld_bulk_done'] ) );
        $transient_key = 'svld_bulk_' . sanitize_key( wp_unslash( $_GET['svld_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 label queued for printing.',
                        '%d labels queued for printing.',
                        $count,
                        'scanvault-label-designer'
                    ) ),
                    esc_html( $count )
                ); ?>
                <button type="button"
                        class="button svld-trigger-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 add_print_column( array $columns ): array {
        $columns['svld_print'] = 'Print Label';
        return $columns;
    }

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

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

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

    public function enqueue_list_scripts( string $hook ): void {
        if ( $hook !== 'edit.php' || sanitize_text_field( wp_unslash( $_GET['post_type'] ?? '' ) ) !== 'product' ) {
            return;
        }

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

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

        wp_localize_script( 'svld-product-list', 'svld_list_params', [
            'ajax_url'   => admin_url( 'admin-ajax.php' ),
            'nonce'      => wp_create_nonce( 'svld_nonce' ),
            'print_url'  => admin_url( 'admin-ajax.php' ) . '?action=svld_bulk_print',
            'generating' => __( 'Generating PDF…', 'scanvault-label-designer' ),
            'error'      => __( 'PDF generation failed. Please try again.', 'scanvault-label-designer' ),
        ] );
    }
}
