<?php
/**
 * Order Bump Display Class
 * Handles order bump display functionality in checkout
 * 
 * @package Checkoutify_Lite
 * @since 1.0.0
 */

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

/**
 * Order Bump Display Class
 * Manages order bump display and functionality in checkout templates
 */
class CKFYLT25_Order_Bump_Display {

    /**
     * Constructor - Initialize order bump display hooks
     */
    public function __construct() {
        add_action( 'ckfylt25_before_testimonials', array( $this, 'ckfylt25_display_order_bump' ) );
        add_action( 'wp_ajax_ckfylt25_add_order_bump_to_cart', array( $this, 'ckfylt25_add_order_bump_to_cart' ) );
        add_action( 'wp_ajax_nopriv_ckfylt25_add_order_bump_to_cart', array( $this, 'ckfylt25_add_order_bump_to_cart' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'ckfylt25_enqueue_scripts' ) );
        add_filter( 'woocommerce_add_to_cart_fragments', array( $this, 'ckfylt25_add_cart_fragments' ) );
        add_action( 'woocommerce_add_to_cart', array( $this, 'ckfylt25_force_checkout_update' ), 10, 6 );
    }

    /**
     * Display order bump in checkout
     */
    public function ckfylt25_display_order_bump() {
        $order_bumps = get_option( 'ckfylt25_order_bumps', [] );
        if ( empty( $order_bumps ) ) {
            return;
        }

        $design = get_option( 'ckfylt25_order_bump_design', 'minimalista' );

        $cart_items = WC()->cart->get_cart();
        $bump_product_id = 0;

        foreach ( $cart_items as $cart_item ) {
            foreach ( $order_bumps as $bump ) {
                if ( $cart_item['product_id'] == $bump['trigger_product_id'] ) {
                    $bump_product_id = $bump['bump_product_id'];
                    break 2;
                }
            }
        }

        if ( ! $bump_product_id ) {
            return;
        }

        $product = wc_get_product( $bump_product_id );
        if ( ! $product ) {
            return;
        }

        // Check if the bump product is already in the cart
        foreach ($cart_items as $cart_item) {
            if ($cart_item['product_id'] == $bump_product_id) {
                return; // Don't show the bump if the product is already in the cart
            }
        }

        // Get product image
        $product_image = $product->get_image('thumbnail');
        $product_price = $product->get_price_html();
        $product_name = $product->get_name();
        
        // Render based on selected design
        switch ($design) {
            case 'divertido':
                $this->render_funny_design($product, $product_image, $product_price, $product_name);
                break;
            case 'creativo':
                $this->render_creative_design($product, $product_image, $product_price, $product_name);
                break;
            default: // minimalista
                $this->render_minimalist_design($product, $product_image, $product_price, $product_name);
                break;
        }
        // Styles moved to external file: assets/css/order-bump.css (enqueued above)
    }

    private function render_minimalist_design($product, $product_image, $product_price, $product_name) {
        ?>
        <div id="ckfylt25-order-bump" class="ckfylt25-order-bump-container" style="
            background: #ffffff;
            border: 2px dashed #10b981;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
            position: relative;
            box-shadow: 0 2px 8px rgba(16, 185, 129, 0.1);
        ">
            <div style="display: flex; align-items: center; gap: 15px;">
                <!-- Product Image -->
                <div style="flex-shrink: 0;">
                    <?php if ($product_image) : ?>
                        <div style="
                            width: 60px;
                            height: 60px;
                            border-radius: 6px;
                            overflow: hidden;
                            background: white;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            border: 1px solid #e5e7eb;
                        ">
                            <?php echo wp_kses_post($product_image); ?>
                        </div>
                    <?php else : ?>
                        <div style="
                            width: 60px;
                            height: 60px;
                            border-radius: 6px;
                            background: #f3f4f6;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            font-size: 20px;
                            border: 1px solid #e5e7eb;
                        ">
                            📦
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Content -->
                <div style="flex-grow: 1;">
                    <div style="
                        background: #10b981;
                        color: white;
                        padding: 4px 8px;
                        border-radius: 4px;
                        display: inline-block;
                        margin-bottom: 8px;
                        font-size: 11px;
                        font-weight: bold;
                        text-transform: uppercase;
                    ">
                        Exclusive Offer
                    </div>
                    
                    <h3 style="
                        margin: 0 0 8px 0;
                        font-size: 16px;
                        font-weight: 600;
                        color: #374151;
                    ">
                        Add this to your order
                    </h3>
                    
                    <p style="
                        margin: 0 0 12px 0;
                        font-size: 14px;
                        color: #6b7280;
                        line-height: 1.4;
                    ">
                        Add <strong><?php echo esc_html( $product_name ); ?></strong> for just <strong><?php echo wp_kses_post( $product_price ); ?></strong>
                    </p>
                    
                    <button type="button" 
                            class="button alt ckfylt25-order-bump-btn" 
                            id="ckfylt25-add-order-bump-button" 
                            data-product-id="<?php echo esc_attr( $product->get_id() ); ?>"
                            style="
                                background: #10b981;
                                color: white;
                                border: none;
                                padding: 10px 20px;
                                border-radius: 6px;
                                font-weight: 600;
                                font-size: 14px;
                                cursor: pointer;
                                transition: all 0.2s ease;
                                text-transform: uppercase;
                                letter-spacing: 0.5px;
                            "
                            onmouseover="this.style.background='#059669';"
                            onmouseout="this.style.background='#10b981';">
                        Add to Order
                    </button>
                </div>
            </div>
            
            <!-- Close button -->
            <button type="button" 
                    onclick="document.getElementById('ckfylt25-order-bump').style.display='none';"
                    style="
                        position: absolute;
                        top: 8px;
                        right: 8px;
                        background: none;
                        border: none;
                        color: #9ca3af;
                        width: 24px;
                        height: 24px;
                        cursor: pointer;
                        font-size: 14px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        transition: color 0.2s ease;
                    "
                    onmouseover="this.style.color='#6b7280';"
                    onmouseout="this.style.color='#9ca3af';">
                ×
            </button>
        </div>
        <?php
    }

    private function render_funny_design($product, $product_image, $product_price, $product_name) {
        ?>
        <div id="ckfylt25-order-bump" class="ckfylt25-order-bump-container" style="
            background: linear-gradient(135deg, #ff6b6b, #ffa500);
            border: 3px solid #ff4757;
            border-radius: 20px;
            padding: 25px;
            margin: 20px 0;
            position: relative;
            box-shadow: 0 8px 25px rgba(255, 107, 107, 0.3);
        ">
            <div style="display: flex; align-items: center; gap: 20px;">
                <!-- Product Image -->
                <div style="flex-shrink: 0;">
                    <?php if ($product_image) : ?>
                        <div style="
                            width: 80px;
                            height: 80px;
                            border-radius: 15px;
                            overflow: hidden;
                            background: white;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            border: 3px solid white;
                            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                        ">
                            <?php echo wp_kses_post($product_image); ?>
                        </div>
                    <?php else : ?>
                        <div style="
                            width: 80px;
                            height: 80px;
                            border-radius: 15px;
                            background: white;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            font-size: 30px;
                            border: 3px solid white;
                            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                        ">
                            🎉
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Content -->
                <div style="flex-grow: 1;">
                    <div style="
                        background: #ff4757;
                        color: white;
                        padding: 8px 12px;
                        border-radius: 25px;
                        display: inline-block;
                        margin-bottom: 10px;
                        font-size: 12px;
                        font-weight: bold;
                        text-transform: uppercase;
                        animation: pulse 2s infinite;
                    ">
                        🎊 ¡OFERTA ESPECIAL! 🎊
                    </div>
                    
                    <h3 style="
                        margin: 0 0 10px 0;
                        font-size: 20px;
                        font-weight: 700;
                        color: white;
                        text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
                    ">
                        ¡No te lo pierdas! 🚀
                    </h3>
                    
                    <p style="
                        margin: 0 0 15px 0;
                        font-size: 16px;
                        color: white;
                        text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
                    ">
                        ¡Añade <strong><?php echo esc_html( $product_name ); ?></strong> por solo <strong><?php echo wp_kses_post( $product_price ); ?></strong>! 🎁
                    </p>
                    
                    <button type="button" 
                            class="button alt ckfylt25-order-bump-btn" 
                            id="ckfylt25-add-order-bump-button" 
                            data-product-id="<?php echo esc_attr( $product->get_id() ); ?>"
                            style="
                                background: linear-gradient(45deg, #ff4757, #ff3742);
                                color: white;
                                border: none;
                                padding: 12px 24px;
                                border-radius: 25px;
                                font-weight: 600;
                                font-size: 16px;
                                cursor: pointer;
                                transition: all 0.3s ease;
                                box-shadow: 0 4px 15px rgba(255, 71, 87, 0.4);
                                text-transform: uppercase;
                            "
                            onmouseover="this.style.transform='scale(1.05)'; this.style.boxShadow='0 6px 20px rgba(255, 71, 87, 0.6)';"
                            onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 4px 15px rgba(255, 71, 87, 0.4)';">
                        🛒 ¡AÑADIR AHORA!
                    </button>
                </div>
            </div>
            
            <!-- Close button -->
            <button type="button" 
                    onclick="document.getElementById('ckfylt25-order-bump').style.display='none';"
                    style="
                        position: absolute;
                        top: 10px;
                        right: 10px;
                        background: rgba(255,255,255,0.2);
                        border: 2px solid white;
                        color: white;
                        width: 30px;
                        height: 30px;
                        cursor: pointer;
                        font-size: 16px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border-radius: 50%;
                        transition: all 0.3s ease;
                    "
                    onmouseover="this.style.background='rgba(255,255,255,0.3)';"
                    onmouseout="this.style.background='rgba(255,255,255,0.2)';">
                ×
            </button>
        </div>
        <?php
    }

    private function render_creative_design($product, $product_image, $product_price, $product_name) {
        ?>
        <div id="ckfylt25-order-bump" class="ckfylt25-order-bump-container" style="
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 15px;
            padding: 30px;
            margin: 20px 0;
            position: relative;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
            overflow: hidden;
        ">
            <!-- Background decoration -->
            <div style="
                position: absolute;
                top: -50px;
                right: -50px;
                width: 100px;
                height: 100px;
                background: rgba(255,255,255,0.1);
                border-radius: 50%;
                z-index: 1;
            "></div>
            <div style="
                position: absolute;
                bottom: -30px;
                left: -30px;
                width: 60px;
                height: 60px;
                background: rgba(255,255,255,0.1);
                border-radius: 50%;
                z-index: 1;
            "></div>
            
            <div style="display: flex; align-items: center; gap: 25px; position: relative; z-index: 2;">
                <!-- Product Image -->
                <div style="flex-shrink: 0;">
                    <?php if ($product_image) : ?>
                        <div style="
                            width: 90px;
                            height: 90px;
                            border-radius: 20px;
                            overflow: hidden;
                            background: white;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            border: 4px solid rgba(255,255,255,0.3);
                            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
                            transform: rotate(-5deg);
                        ">
                            <?php echo wp_kses_post($product_image); ?>
                        </div>
                    <?php else : ?>
                        <div style="
                            width: 90px;
                            height: 90px;
                            border-radius: 20px;
                            background: white;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            font-size: 35px;
                            border: 4px solid rgba(255,255,255,0.3);
                            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
                            transform: rotate(-5deg);
                        ">
                            ✨
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Content -->
                <div style="flex-grow: 1;">
                    <div style="
                        background: rgba(255,255,255,0.2);
                        color: white;
                        padding: 6px 12px;
                        border-radius: 20px;
                        display: inline-block;
                        margin-bottom: 12px;
                        font-size: 11px;
                        font-weight: 600;
                        text-transform: uppercase;
                        backdrop-filter: blur(10px);
                        border: 1px solid rgba(255,255,255,0.3);
                    ">
                        ✨ Oferta Exclusiva ✨
                    </div>
                    
                    <h3 style="
                        margin: 0 0 12px 0;
                        font-size: 22px;
                        font-weight: 700;
                        color: white;
                        text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
                    ">
                        Descubre algo especial
                    </h3>
                    
                    <p style="
                        margin: 0 0 18px 0;
                        font-size: 16px;
                        color: rgba(255,255,255,0.9);
                        text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
                        line-height: 1.4;
                    ">
                        Completa tu experiencia con <strong><?php echo esc_html( $product_name ); ?></strong> por <strong><?php echo wp_kses_post( $product_price ); ?></strong>
                    </p>
                    
                    <button type="button" 
                            class="button alt ckfylt25-order-bump-btn" 
                            id="ckfylt25-add-order-bump-button" 
                            data-product-id="<?php echo esc_attr( $product->get_id() ); ?>"
                            style="
                                background: linear-gradient(45deg, #ff6b6b, #ee5a24);
                                color: white;
                                border: none;
                                padding: 14px 28px;
                                border-radius: 30px;
                                font-weight: 600;
                                font-size: 16px;
                                cursor: pointer;
                                transition: all 0.3s ease;
                                box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
                                text-transform: uppercase;
                                letter-spacing: 1px;
                            "
                            onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 8px 25px rgba(255, 107, 107, 0.6)';"
                            onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 6px 20px rgba(255, 107, 107, 0.4)';">
                        ✨ <?php esc_html_e( 'Add to Order', 'checkoutify-lite' ); ?>
                    </button>
                </div>
            </div>
            
            <!-- Close button -->
            <button type="button" 
                    onclick="document.getElementById('ckfylt25-order-bump').style.display='none';"
                    style="
                        position: absolute;
                        top: 15px;
                        right: 15px;
                        background: rgba(255,255,255,0.2);
                        border: 2px solid rgba(255,255,255,0.3);
                        color: white;
                        width: 35px;
                        height: 35px;
                        cursor: pointer;
                        font-size: 18px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border-radius: 50%;
                        transition: all 0.3s ease;
                        backdrop-filter: blur(10px);
                        z-index: 3;
                    "
                    onmouseover="this.style.background='rgba(255,255,255,0.3)';"
                    onmouseout="this.style.background='rgba(255,255,255,0.2)';">
                ×
            </button>
        </div>
        <?php
    }

    /**
     * AJAX handler to add order bump product to cart
     */
    public function ckfylt25_add_order_bump_to_cart() {
        // Verify nonce for security
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'ckfylt25_order_bump_nonce' ) ) {
            wp_send_json_error( __( 'Invalid nonce.', 'checkoutify-lite' ) );
        }

        if ( ! isset( $_POST['product_id'] ) || ! is_numeric( $_POST['product_id'] ) ) {
            wp_send_json_error( __( 'Invalid product ID.', 'checkoutify-lite' ) );
        }

        $product_id = absint( $_POST['product_id'] );
        
        // Add product to cart using WooCommerce's standard method
        $cart_item_key = WC()->cart->add_to_cart( $product_id, 1 );
        
        if ( $cart_item_key ) {
            // Force WooCommerce to recalculate totals
            WC()->cart->calculate_totals();
            
            wp_send_json_success( array(
                'cart_item_key' => $cart_item_key,
                'message' => esc_html__('Product added to cart successfully', 'checkoutify-lite')
            ) );
        } else {
            wp_send_json_error( esc_html__('Failed to add product to cart.', 'checkoutify-lite') );
        }
    }

    /**
     * Enqueue order bump scripts
     */
    public function ckfylt25_enqueue_scripts() {
        if ( is_checkout() ) {
            wp_enqueue_style( 'ckfylt25-order-bump', CKFYLT25_PLUGIN_URL . 'assets/css/order-bump.css', array(), '1.0.0' );
            wp_enqueue_script( 'ckfylt25-order-bump', CKFYLT25_PLUGIN_URL . 'assets/js/order-bump.js', array( 'jquery', 'wp-i18n' ), '1.0.0', true );
            if ( function_exists( 'wp_set_script_translations' ) ) {
                wp_set_script_translations( 'ckfylt25-order-bump', 'checkoutify-lite', CKFYLT25_PLUGIN_DIR . 'languages' );
            }
            wp_localize_script( 'ckfylt25-order-bump', 'ckfylt25_ajax', array( 
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce' => wp_create_nonce( 'ckfylt25_order_bump_nonce' )
            ) );
        }
    }
    
    /**
     * Add cart fragments for AJAX updates
     * 
     * @param array $fragments Existing cart fragments
     * @return array Modified cart fragments
     */
    public function ckfylt25_add_cart_fragments( $fragments ) {
        // Add cart totals to fragments
        ob_start();
        ?>
        <div class="cart-subtotal">
            <strong><?php esc_html_e( 'Subtotal', 'checkoutify-lite' ); ?></strong>
            <span><?php echo wp_kses_post(WC()->cart->get_cart_subtotal()); ?></span>
        </div>
        <?php
        $fragments['.cart-subtotal'] = ob_get_clean();
        
        ob_start();
        ?>
        <div class="order-total">
            <strong><?php esc_html_e( 'Total', 'checkoutify-lite' ); ?></strong>
            <span><?php echo wp_kses_post(WC()->cart->get_total()); ?></span>
        </div>
        <?php
        $fragments['.order-total'] = ob_get_clean();
        
        return $fragments;
    }
    
    /**
     * Force checkout update after adding product to cart
     * 
     * @param string $cart_item_key Cart item key
     * @param int $product_id Product ID
     * @param int $quantity Quantity
     * @param int $variation_id Variation ID
     * @param array $variation Variation data
     * @param array $cart_item_data Cart item data
     */
    public function ckfylt25_force_checkout_update( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
        // Force WooCommerce to recalculate totals
        WC()->cart->calculate_totals();
        
        // Trigger checkout update if we're on checkout page
        if ( is_checkout() ) {
            add_action( 'wp_footer', function() {
                wp_add_inline_script( 'ckfylt25-order-bump', 'jQuery(document).ready(function($) { $(document.body).trigger("update_checkout"); });' );
            });
        }
    }
}
