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

/**
 * SVLD_Metabox — adds a Print Label metabox to the product edit page,
 * and a Print All Labels metabox to the order edit page.
 */
class SVLD_Metabox {

    public function __construct() {
        add_action( 'add_meta_boxes', [ $this, 'register_metaboxes' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_metabox_scripts' ] );
    }

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

    public function register_metaboxes(): void {
        if ( get_option( 'svld_print_on_product_page', '1' ) === '1' ) {
            add_meta_box(
                'svld_print_label',
                __( 'Print Label', 'scanvault-label-designer' ),
                [ $this, 'render_product_metabox' ],
                'product',
                'side',
                'default'
            );
        }

        if ( get_option( 'svld_print_on_order_page', '1' ) === '1' ) {
            // Support both legacy post-based orders and HPOS
            add_meta_box(
                'svld_print_order_labels',
                __( 'Print Labels', 'scanvault-label-designer' ),
                [ $this, 'render_order_metabox' ],
                [ 'shop_order', 'woocommerce_page_wc-orders' ],
                'side',
                'default'
            );
        }
    }

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

    public function render_product_metabox( WP_Post $post ): void {
        $product = wc_get_product( $post->ID );
        if ( ! $product ) return;

        $nonce = wp_create_nonce( 'svld_nonce' );
        ?>
        <div class="svld-product-metabox">
            <p class="svld-product-meta-name">
                <strong><?php echo esc_html( $product->get_name() ); ?></strong>
                <?php if ( $product->get_sku() ) : ?>
                <br><small><?php esc_html_e( 'SKU:', 'scanvault-label-designer' ); ?> <?php echo esc_html( $product->get_sku() ); ?></small>
                <?php endif; ?>
            </p>

            <div class="svld-metabox-row">
                <label for="svld-print-qty-<?php echo esc_attr( $post->ID ); ?>"><?php esc_html_e( 'Quantity:', 'scanvault-label-designer' ); ?></label>
                <input type="number"
                       id="svld-print-qty-<?php echo esc_attr( $post->ID ); ?>"
                       class="svld-qty-input"
                       value="1" min="1" max="500"
                       style="width:60px; margin-left:6px;">
            </div>

            <button type="button"
                    class="button button-primary svld-print-single"
                    data-id="<?php echo esc_attr( $post->ID ); ?>"
                    data-nonce="<?php echo esc_attr( $nonce ); ?>"
                    style="width:100%; margin-top:8px; justify-content:center; display:flex; align-items:center; gap:4px;">
                <span class="dashicons dashicons-printer" style="margin-top:3px;"></span>
                <?php esc_html_e( 'Print Label', 'scanvault-label-designer' ); ?>
            </button>

            <div class="svld-print-status" style="margin-top:6px; font-size:12px; color:#666;"></div>

            <p style="margin-top:10px;">
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=svld-designer' ) ); ?>" style="font-size:12px;">
                    <?php esc_html_e( 'Edit Label Design →', 'scanvault-label-designer' ); ?>
                </a>
            </p>
        </div>
        <?php
    }

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

    public function render_order_metabox( $post_or_order ): void {
        // Support both WP_Post and WC_Order (HPOS)
        if ( $post_or_order instanceof WP_Post ) {
            $order = wc_get_order( $post_or_order->ID );
        } elseif ( $post_or_order instanceof WC_Abstract_Order ) {
            $order = $post_or_order;
        } else {
            $order = wc_get_order( absint( $post_or_order ) );
        }

        if ( ! $order ) return;

        $nonce = wp_create_nonce( 'svld_nonce' );
        ?>
        <div class="svld-order-metabox">
            <button type="button"
                    class="button button-primary svld-print-order"
                    data-order-id="<?php echo esc_attr( $order->get_id() ); ?>"
                    data-nonce="<?php echo esc_attr( $nonce ); ?>"
                    style="width:100%; justify-content:center; display:flex; align-items:center; gap:4px;">
                <span class="dashicons dashicons-printer" style="margin-top:3px;"></span>
                <?php esc_html_e( 'Print All Labels', 'scanvault-label-designer' ); ?>
            </button>

            <div class="svld-print-status" style="margin-top:6px; font-size:12px; color:#666;"></div>
        </div>
        <?php
    }

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

    public function enqueue_metabox_scripts( string $hook ): void {
        $screen = get_current_screen();
        if ( ! $screen ) return;

        $is_product = ( $screen->post_type === 'product' );
        // Detect order edit page: legacy post-based or HPOS (screen ID contains shop_order or wc-orders)
        $is_order = (
            $screen->post_type === 'shop_order' ||
            in_array( $screen->id, [ 'shop_order', 'woocommerce_page_wc-orders' ], true ) ||
            str_contains( $screen->id, 'wc-orders' ) ||
            str_contains( $hook, 'wc-orders' )
        );

        if ( ! $is_product && ! $is_order ) {
            return;
        }

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

        wp_localize_script( 'svld-metabox', 'svld_metabox_params', [
            'ajax_url'          => admin_url( 'admin-ajax.php' ),
            'nonce'             => wp_create_nonce( 'svld_nonce' ),
            'generating'        => __( 'Generating PDF…', 'scanvault-label-designer' ),
            'open_pdf'          => __( 'Open PDF', 'scanvault-label-designer' ),
            'error'             => __( 'Failed to generate PDF. Please try again.', 'scanvault-label-designer' ),
            'print_action'      => 'svld_print_label',
            'order_print_action' => 'svld_print_order_labels',
        ] );
    }
}
