<?php

namespace Devikit\Fakturowo\Admin;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class handling Fakturowo column in orders list
 */
class OrderColumns {

    const COLUMN_SLUG = 'fakturowo_invoice';

    /**
     * Constructor
     */
    public function __construct() {
        // Add column to orders list (classic and HPOS)
        add_filter( 'manage_shop_order_posts_columns', [ $this, 'add_column' ], 20 );
        add_action( 'manage_shop_order_posts_custom_column', [ $this, 'render_column' ], 10, 2 );
        
        // HPOS support
        add_filter( 'manage_woocommerce_page_wc-orders_columns', [ $this, 'add_column' ], 20 );
        add_action( 'manage_woocommerce_page_wc-orders_custom_column', [ $this, 'render_column' ], 10, 2 );
        
        // Add inline styles and scripts
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
    }

    /**
     * Add Fakturowo column
     *
     * @param array $columns
     * @return array
     */
    public function add_column( $columns ) {
        // Find position of actions column
        $actions_key = $this->get_actions_column_name();
        $actions_pos = array_search( $actions_key, array_keys( $columns ), true );
        
        if ( $actions_pos === false ) {
            // If actions column not found, add at the end
            $columns[ self::COLUMN_SLUG ] = __( 'Fakturowo', 'invoicing-integration-for-fakturowo-and-woocommerce' );
            return $columns;
        }
        
        // Insert before actions column
        return array_merge(
            array_slice( $columns, 0, $actions_pos ),
            [ self::COLUMN_SLUG => __( 'Fakturowo', 'invoicing-integration-for-fakturowo-and-woocommerce' ) ],
            array_slice( $columns, $actions_pos )
        );
    }

    /**
     * Get actions column name
     *
     * @return string
     */
    private function get_actions_column_name() {
        if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '3.3', '<' ) ) {
            return 'order_actions';
        }
        return 'wc_actions';
    }

    /**
     * Render column content
     *
     * @param string $column
     * @param int|\WP_Post|\WC_Order $order_or_id
     */
    public function render_column( $column, $order_or_id ) {
        if ( self::COLUMN_SLUG !== $column ) {
            return;
        }

        try {
            $order_id = $this->get_order_id( $order_or_id );
            $order = wc_get_order( $order_id );
            
            if ( ! $order ) {
                return;
            }

            $invoice_id = $order->get_meta( '_fakturowo_invoice_id' );
            $invoice_number = $order->get_meta( '_fakturowo_invoice_number' );

            if ( ! $invoice_id ) {
                echo '<span class="fakturowo-no-invoice">' . esc_html__( '—', 'invoicing-integration-for-fakturowo-and-woocommerce' ) . '</span>';
                return;
            }

            // Display invoice number with download link
            ?>
            <div class="fakturowo-invoice-column" style="line-height: 1.8;">
                <a href="#" 
                   class="fakturowo-download-pdf-link" 
                   data-invoice-id="<?php echo esc_attr( $invoice_id ); ?>"
                   data-invoice-number="<?php echo esc_attr( $invoice_number ); ?>"
                   data-order-id="<?php echo esc_attr( $order_id ); ?>"
                   title="<?php echo esc_attr__( 'Download PDF', 'invoicing-integration-for-fakturowo-and-woocommerce' ); ?>">
                    <?php echo esc_html( $invoice_number ?: $invoice_id ); ?>
                </a>
                <span class="fakturowo-loading" style="display:none;">⏳</span>
            </div>
            <?php
            // Show total mismatch warning (invoice)
            $invoice_mismatch = $order->get_meta( '_fakturowo_invoice_total_mismatch' ) === 'yes';
            if ( $invoice_mismatch ) {
                $order_total = floatval( $order->get_meta( '_fakturowo_invoice_order_total' ) );
                $invoice_total = floatval( $order->get_meta( '_fakturowo_invoice_fakturowo_total' ) );
                $difference = floatval( $order->get_meta( '_fakturowo_invoice_total_difference' ) );
                ?>
                <div class="fakturowo-mismatch-warning" style="margin-top: 4px; font-size: 11px; color: #856404; background: #fff3cd; padding: 4px 6px; border-left: 3px solid #ffc107; border-radius: 2px;" title="<?php echo esc_attr__( 'Total Mismatch Detected – sums do not match', 'invoicing-integration-for-fakturowo-and-woocommerce' ); ?>">
                    <?php
                    printf(
                        /* translators: 1: Order total, 2: Invoice total, 3: Difference */
                        esc_html__( '⚠ FV: zam. %1$s | fv %2$s | diff. %3$s', 'invoicing-integration-for-fakturowo-and-woocommerce' ),
                        number_format( $order_total, 2, ',', ' ' ),
                        number_format( $invoice_total, 2, ',', ' ' ),
                        number_format( $difference, 2, ',', ' ' )
                    );
                    ?>
                </div>
                <?php
            }
        } catch ( \Exception $e ) {
            // Silent fail
        }
    }

    /**
     * Get order ID from various object types
     *
     * @param mixed $object
     * @return int
     * @throws \Exception
     */
    private function get_order_id( $object ) {
        if ( $object instanceof \WP_Post ) {
            return (int) $object->ID;
        } elseif ( $object instanceof \WC_Order ) {
            return (int) $object->get_id();
        } elseif ( is_integer( $object ) ) {
            return (int) $object;
        }

        throw new \Exception( 'Unknown order object' );
    }

    /**
     * Enqueue admin assets for the column
     */
    public function enqueue_admin_assets( $hook_suffix ) {
        $screen = get_current_screen();
        if ( ! $screen || ( $screen->id !== 'edit-shop_order' && $screen->id !== 'woocommerce_page_wc-orders' ) ) {
            return;
        }

        // Add inline styles
        wp_add_inline_style( 'admin-bar', '
            .fakturowo-invoice-column {
                display: flex;
                align-items: center;
                gap: 5px;
            }
            .fakturowo-download-pdf-link {
                color: #2271b1;
                text-decoration: none;
                font-weight: 500;
            }
            .fakturowo-download-pdf-link:hover {
                color: #135e96;
                text-decoration: underline;
            }
            .fakturowo-no-invoice {
                color: #999;
            }
            .fakturowo-loading {
                font-size: 14px;
            }
        ' );
        
        // Enqueue jQuery and add download script
        wp_enqueue_script( 'jquery' );
        
        $nonce = esc_js( wp_create_nonce( 'fakturowo_download_pdf' ) );
        $error_msg = esc_js( __( 'Failed to download PDF', 'invoicing-integration-for-fakturowo-and-woocommerce' ) );
        
        $inline_script = "
            jQuery(document).ready(function($) {
                $(document).on('click', '.fakturowo-download-pdf-link', function(e) {
                    e.preventDefault();
                    
                    var \$link = $(this);
                    var \$loading = \$link.siblings('.fakturowo-loading');
                    var invoiceId = \$link.data('invoice-id');
                    var invoiceNumber = \$link.data('invoice-number');
                    
                    \$link.hide();
                    \$loading.show();
                    
                    $.post(ajaxurl, {
                        action: 'devikit_fakturowo_download_pdf',
                        invoice_id: invoiceId,
                        invoice_number: invoiceNumber,
                        nonce: '" . $nonce . "'
                    }, function(response) {
                        \$loading.hide();
                        \$link.show();
                        
                        if (response.success && response.data.pdf) {
                            // Convert base64 to blob and download
                            var binary = atob(response.data.pdf);
                            var array = new Uint8Array(binary.length);
                            for (var i = 0; i < binary.length; i++) {
                                array[i] = binary.charCodeAt(i);
                            }
                            var blob = new Blob([array], {type: 'application/pdf'});
                            var url = window.URL.createObjectURL(blob);
                            var a = document.createElement('a');
                            a.href = url;
                            a.download = response.data.filename;
                            document.body.appendChild(a);
                            a.click();
                            window.URL.revokeObjectURL(url);
                            document.body.removeChild(a);
                        } else {
                            alert(response.data.message || '" . $error_msg . "');
                        }
                    }).fail(function() {
                        \$loading.hide();
                        \$link.show();
                        alert('" . $error_msg . "');
                    });
                });
            });
        ";
        wp_add_inline_script( 'jquery', $inline_script );
    }
}
