<?php

namespace Devikit\Infakt\Admin;

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

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

    const COLUMN_SLUG = 'infakt_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
        add_action( 'admin_head', [ $this, 'add_inline_styles' ] );
    }

    /**
     * Add InFakt 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 ] = __( 'InFakt', 'invoicing-integration-for-infakt-and-woocommerce' );
            return $columns;
        }
        
        // Insert before actions column
        return array_merge(
            array_slice( $columns, 0, $actions_pos ),
            [ self::COLUMN_SLUG => __( 'InFakt', 'invoicing-integration-for-infakt-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( '_infakt_invoice_id' );
            $invoice_number = $order->get_meta( '_infakt_invoice_number' );

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

            // Display invoice number with download link
            ?>
            <div class="infakt-invoice-column">
                <div>
                    <a href="#" 
                       class="infakt-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-infakt-and-woocommerce' ); ?>">
                        <?php echo esc_html( $invoice_number ?: $invoice_id ); ?>
                    </a>
                    <span class="infakt-loading" style="display:none;">⏳</span>
                </div>
                <?php
                $invoice_mismatch = $order->get_meta( '_infakt_invoice_total_mismatch' ) === 'yes';
                if ( $invoice_mismatch ) {
                    $order_total = floatval( $order->get_meta( '_infakt_invoice_order_total' ) );
                    $invoice_total = floatval( $order->get_meta( '_infakt_invoice_infakt_total' ) );
                    $difference = floatval( $order->get_meta( '_infakt_invoice_total_difference' ) );
                    ?>
                    <div class="infakt-mismatch-warning" title="<?php echo esc_attr__( 'Total Mismatch Detected – sums do not match', 'invoicing-integration-for-infakt-and-woocommerce' ); ?>">
                        <?php
                        printf(
                            /* translators: 1: Order total, 2: Invoice total, 3: Difference */
                            esc_html__( '⚠ FV: order %1$s | invoice %2$s | diff. %3$s', 'invoicing-integration-for-infakt-and-woocommerce' ),
                            number_format( $order_total, 2, ',', ' ' ),
                            number_format( $invoice_total, 2, ',', ' ' ),
                            number_format( $difference, 2, ',', ' ' )
                        );
                        ?>
                    </div>
                    <?php
                }
                ?>
            </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' );
    }

    /**
     * Add inline styles for the column
     */
    public function add_inline_styles() {
        $screen = get_current_screen();
        if ( ! $screen || ( $screen->id !== 'edit-shop_order' && $screen->id !== 'woocommerce_page_wc-orders' ) ) {
            return;
        }

        // Enqueue jQuery
        wp_enqueue_script( 'jquery' );
        
        // Add CSS
        wp_add_inline_style( 'admin-bar', '
            .infakt-invoice-column {
                display: flex;
                flex-direction: column;
                gap: 4px;
            }
            .infakt-invoice-column > div:first-child {
                display: flex;
                align-items: center;
                gap: 5px;
            }
            .infakt-download-pdf-link {
                color: #2271b1;
                text-decoration: none;
                font-weight: 500;
            }
            .infakt-download-pdf-link:hover {
                color: #135e96;
                text-decoration: underline;
            }
            .infakt-no-invoice {
                color: #999;
            }
            .infakt-loading {
                font-size: 14px;
            }
            .infakt-mismatch-warning {
                font-size: 11px;
                color: #856404;
                background: #fff3cd;
                padding: 4px 6px;
                border-left: 3px solid #ffc107;
                border-radius: 2px;
            }
        ' );
        
        // Add JS
        $script = "
            jQuery(document).ready(function($) {
                $(document).on('click', '.infakt-download-pdf-link', function(e) {
                    e.preventDefault();
                    
                    var \$link = $(this);
                    var \$loading = \$link.siblings('.infakt-loading');
                    var invoiceId = \$link.data('invoice-id');
                    var invoiceNumber = \$link.data('invoice-number');
                    
                    \$link.hide();
                    \$loading.show();
                    
                    $.post(ajaxurl, {
                        action: 'devikit_infakt_download_pdf',
                        invoice_id: invoiceId,
                        invoice_number: invoiceNumber,
                        nonce: '" . wp_create_nonce( 'infakt_download_pdf' ) . "'
                    }, function(response) {
                        \$loading.hide();
                        \$link.show();
                        
                        if (response.success && response.data.pdf) {
                            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 || '" . esc_js( __( 'Failed to download PDF', 'invoicing-integration-for-infakt-and-woocommerce' ) ) . "');
                        }
                    }).fail(function() {
                        \$loading.hide();
                        \$link.show();
                        alert('" . esc_js( __( 'Failed to download PDF', 'invoicing-integration-for-infakt-and-woocommerce' ) ) . "');
                    });
                });
            });
        ";
        
        wp_add_inline_script( 'jquery', $script );
    }
}
