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

/**
 * SVLD_Scanner_Bridge — injects a "Print Label" button into the ScanVault
 * Barcode Scanner modal, using the Label Designer's layout and TCPDF renderer
 * instead of the main plugin's built-in label printer.
 *
 * This bridge is opt-in: it only activates when the main ScanVault plugin
 * (barcode-scanner-molay) is active.
 */
class SVLD_Scanner_Bridge {

    public function __construct() {
        if ( ! $this->is_scanvault_active() ) {
            return;
        }

        // Bridge is a Business-tier feature — only activate for Business users
        if ( ! $this->can_use_bridge() ) {
            return;
        }

        // Inject our own Print button into the scanner modal via JS
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_bridge_script' ] );

        // Override the scanner's print AJAX with our renderer
        add_action( 'wp_ajax_svld_bridge_print', [ $this, 'handle_bridge_print' ] );
    }

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

    private function can_use_bridge(): bool {
        return true;
    }

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

    private function get_scanner_template_name(): string {
        $template_id = get_option( 'svld_scanner_modal_template', '' );
        if ( ! $template_id ) return '';
        $templates = get_option( 'svld_templates', [] );
        return isset( $templates[ $template_id ] ) ? (string) $templates[ $template_id ]['name'] : '';
    }

    private function is_scanvault_active(): bool {
        return defined( 'WBS_VERSION' );
    }

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

    public function enqueue_bridge_script( string $hook ): void {
        // Only load on pages where the scanner modal loads
        // The scanner loads on all admin pages — match that behavior
        wp_enqueue_script(
            'svld-scanner-bridge',
            SVLD_PLUGIN_URL . 'assets/js/scanner-bridge.js',
            [ 'jquery' ],
            SVLD_VERSION,
            true
        );

        wp_localize_script( 'svld-scanner-bridge', 'svld_bridge', [
            'ajax_url'               => admin_url( 'admin-ajax.php' ),
            'nonce'                  => wp_create_nonce( 'svld_nonce' ),
            'print_action'           => 'svld_bridge_print',
            'designer_url'           => admin_url( 'admin.php?page=svld-designer' ),
            'is_business'            => true,
            'scanner_template_name'  => $this->get_scanner_template_name(),
            'settings_url'           => admin_url( 'admin.php?page=svld-settings' ),
            'btn_label'              => __( 'Print (Designer)', 'scanvault-label-designer' ),
            'generating'             => __( 'Generating…', 'scanvault-label-designer' ),
            'error'                  => __( 'Print failed. Check Label Designer settings.', 'scanvault-label-designer' ),
        ] );
    }

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

    public function handle_bridge_print(): void {
        check_ajax_referer( 'svld_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => __( 'Unauthorized', 'scanvault-label-designer' ) ] );
        }

        $product_id = absint( wp_unslash( $_POST['product_id'] ?? 0 ) );
        if ( ! $product_id ) {
            wp_send_json_error( [ 'message' => __( 'No product ID.', 'scanvault-label-designer' ) ] );
        }

        $product = wc_get_product( $product_id );
        if ( ! $product ) {
            wp_send_json_error( [ 'message' => __( 'Product not found.', 'scanvault-label-designer' ) ] );
        }

        require_once SVLD_PLUGIN_DIR . 'includes/class-svld-renderer.php';
        $scanner_template_id = get_option( 'svld_scanner_modal_template', '' );
        $renderer = new SVLD_Renderer( $scanner_template_id ?: null );
        $pdf_url  = $renderer->generate_label_pdf( [ $product_id => 1 ] );

        if ( $pdf_url ) {
            wp_send_json_success( [ 'pdf_url' => $pdf_url ] );
        } else {
            $error_msg = $renderer->get_last_error();
            if ( empty( $error_msg ) ) {
                $error_msg = __( 'PDF generation failed.', 'scanvault-label-designer' );
            }
            wp_send_json_error( [ 'message' => $error_msg ] );
        }
    }
}
