<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * WooCommerce Quick View Functions
 *
 * @package pawfect
 */

// AJAX handler for quick view
add_action('wp_ajax_pawfect_quick_view', 'pawfect_quick_view_ajax');
add_action('wp_ajax_nopriv_pawfect_quick_view', 'pawfect_quick_view_ajax');

function pawfect_quick_view_ajax() {
    try {
        // Check if WooCommerce is active
        if (!class_exists('WooCommerce') || !function_exists('wc_get_product')) {
            wp_send_json_error('WooCommerce not available');
            return;
        }

        // Verify nonce - mandatory for CSRF protection
        if ( ! check_ajax_referer( 'pawfect_quick_view_nonce', 'nonce', false ) ) {
            wp_send_json_error( 'Invalid security token' );
            return;
        }

        $product_id = isset( $_POST['product_id'] ) ? intval( wp_unslash( $_POST['product_id'] ) ) : 0;

        if ( ! $product_id ) {
            wp_send_json_error( 'Invalid product ID' );
            return;
        }

        $current_product = wc_get_product($product_id);

        if (!$current_product) {
            wp_send_json_error('Product not found');
            return;
        }

        if (!$current_product->is_visible()) {
            wp_send_json_error('Product not visible for ID: ' . $product_id);
            return;
        }
        
        // Start output buffering
        ob_start();
        
        // Set global product for WooCommerce hooks
        global $woocommerce, $product;
        $product = $current_product;
        $GLOBALS['product'] = $current_product;
        
        // Enhanced Quick View content with product images
        ?>
        <div class="pawfect-quick-view-content">
            <div class="pawfect-grid pawfect-grid-cols-1 md:pawfect-grid-cols-2 pawfect-gap-6">
                <!-- Product Images -->
                <div class="pawfect-product-images">
                    <?php
                    $attachment_ids = $current_product->get_gallery_image_ids();
                    $main_image_id = $current_product->get_image_id();

                    // Combine main image with gallery images
                    $all_image_ids = array();
                    if ($main_image_id) {
                        $all_image_ids[] = $main_image_id;
                    }
                    $all_image_ids = array_merge($all_image_ids, $attachment_ids);
                    $all_image_ids = array_unique($all_image_ids);

                    if (!empty($all_image_ids)): ?>
                        <!-- Main Image -->
                        <div class="pawfect-main-image pawfect-mb-4">
                            <?php
                            $main_image_url = wp_get_attachment_image_url($all_image_ids[0], 'woocommerce_single');
                            $main_image_alt = get_post_meta($all_image_ids[0], '_wp_attachment_image_alt', true);
                            ?>
                            <img src="<?php echo esc_url($main_image_url); ?>"
                                 alt="<?php echo esc_attr($main_image_alt ?: $current_product->get_name()); ?>"
                                 class="pawfect-w-full pawfect-h-auto pawfect-rounded-lg pawfect-shadow-sm">
                        </div>

                        <?php if (count($all_image_ids) > 1): ?>
                            <!-- Thumbnail Gallery -->
                            <div class="pawfect-thumbnail-gallery pawfect-flex pawfect-space-x-2 pawfect-overflow-x-auto">
                                <?php foreach ($all_image_ids as $index => $image_id):
                                    $thumb_url = wp_get_attachment_image_url($image_id, 'woocommerce_gallery_thumbnail');
                                    $full_url = wp_get_attachment_image_url($image_id, 'woocommerce_single');
                                    $thumb_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
                                ?>
                                    <button class="pawfect-thumb-btn pawfect-flex-shrink-0 pawfect-w-16 pawfect-h-16 pawfect-rounded-md pawfect-overflow-hidden pawfect-border-2 pawfect-border-transparent hover:pawfect-border-pawfect-primary pawfect-transition-colors <?php echo esc_attr( $index === 0 ? 'pawfect-border-pawfect-primary' : '' ); ?>"
                                            data-full-image="<?php echo esc_url($full_url); ?>">
                                        <img src="<?php echo esc_url($thumb_url); ?>"
                                             alt="<?php echo esc_attr($thumb_alt ?: $current_product->get_name()); ?>"
                                             class="pawfect-w-full pawfect-h-full pawfect-object-cover">
                                    </button>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <!-- Placeholder if no images -->
                        <div class="pawfect-w-full pawfect-h-64 pawfect-bg-gray-100 pawfect-rounded-lg pawfect-flex pawfect-items-center pawfect-justify-center">
                            <svg class="pawfect-w-16 pawfect-h-16 pawfect-text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                            </svg>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Product Details -->
                <div class="pawfect-product-details">
                    <h2 class="pawfect-text-2xl pawfect-font-bold pawfect-text-gray-900 pawfect-mb-3">
                        <?php echo esc_html($current_product->get_name()); ?>
                    </h2>

                    <div class="pawfect-text-2xl pawfect-font-semibold pawfect-text-pawfect-primary pawfect-mb-4">
                        <?php echo wp_kses_post( $current_product->get_price_html() ); ?>
                    </div>

                    <?php if ($current_product->get_short_description()): ?>
                        <div class="pawfect-text-gray-600 pawfect-mb-6 pawfect-leading-relaxed">
                            <?php echo wp_kses_post($current_product->get_short_description()); ?>
                        </div>
                    <?php endif; ?>

                    <!-- Add to Cart Section -->
                    <?php if ($current_product->is_purchasable() && $current_product->is_in_stock()): ?>
                        <div class="pawfect-add-to-cart-section pawfect-mb-6">
                            <button type="button" class="pawfect-btn">
                                <?php esc_html_e('Add to Cart', 'pawfect'); ?>
                            </button>
                        </div>
                    <?php endif; ?>

                    <!-- View Full Product Link -->
                    <div class="pawfect-pt-4 pawfect-border-t pawfect-border-gray-100">
                        <a href="<?php echo esc_url($current_product->get_permalink()); ?>"
                           class="pawfect-inline-flex pawfect-items-center pawfect-text-pawfect-primary hover:pawfect-text-pawfect-primary-dark pawfect-transition-colors">
                            <span><?php esc_html_e('View Full Product Details', 'pawfect'); ?></span>
                            <svg class="pawfect-w-4 pawfect-h-4 pawfect-ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                            </svg>
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php
        
        $content = ob_get_clean();

        // Ensure we have content
        if (empty($content)) {
            wp_send_json_error('No content generated for product');
            return;
        }

        wp_send_json_success(array(
            'content' => $content,
            'product_name' => $current_product->get_name(),
            'product_id' => $product_id
        ));
        
    } catch (Exception $e) {
        wp_send_json_error('Internal server error occurred');
    }
}

// Generate quick view button HTML
function pawfect_get_quick_view_button($product_id, $classes = '') {
    return sprintf(
        '<button class="pawfect-quick-view-btn %s" data-product-id="%d" title="%s" aria-label="%s">
            <svg class="pawfect-w-5 pawfect-h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
            </svg>
        </button>',
        esc_attr($classes),
        esc_attr($product_id),
        esc_attr(__('Quick View', 'pawfect')),
        esc_attr(__('Quick View', 'pawfect'))
    );
}

// Enqueue quick view scripts - Use higher priority to ensure main script is enqueued first
add_action('wp_enqueue_scripts', 'pawfect_enqueue_quick_view_scripts', 20);

function pawfect_enqueue_quick_view_scripts() {
    // Only localize if the main script is enqueued or registered
    if (wp_script_is('pawfect-main', 'enqueued') || wp_script_is('pawfect-main', 'registered')) {
        wp_localize_script('pawfect-main', 'pawfect_quick_view', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('pawfect_quick_view_nonce'),
            'loading_text' => __('Loading...', 'pawfect'),
            'error_text' => __('Error loading product', 'pawfect'),
        ));
    } else {
        // If script not found, add data via wp_add_inline_script as fallback
        add_action('wp_footer', function() {
            wp_register_script( 'pawfect-quick-view-fallback', '', array(), '', true );
            wp_enqueue_script( 'pawfect-quick-view-fallback' );
            wp_add_inline_script( 'pawfect-quick-view-fallback',
                'window.pawfect_quick_view = ' . wp_json_encode( array(
                    'ajax_url'     => admin_url( 'admin-ajax.php' ),
                    'nonce'        => wp_create_nonce( 'pawfect_quick_view_nonce' ),
                    'loading_text' => __( 'Loading...', 'pawfect' ),
                    'error_text'   => __( 'Error loading product', 'pawfect' ),
                ) ) . ';'
            );
        });
    }
}

// Add quick view button to product loops (only for themes that don't have it in template)
// Commented out since we're adding it directly in the product template
// add_action('woocommerce_after_shop_loop_item', 'pawfect_add_quick_view_button_to_loop', 20);

function pawfect_add_quick_view_button_to_loop() {
    global $product;

    if (!$product) return;

    echo '<div class="pawfect-quick-view-wrapper pawfect-absolute pawfect-top-3 pawfect-left-3 pawfect-z-10">';
    echo wp_kses_post( pawfect_get_quick_view_button($product->get_id(), 'pawfect-bg-white pawfect-bg-opacity-90 pawfect-backdrop-blur-sm pawfect-rounded-full pawfect-p-2 pawfect-shadow-md hover:pawfect-bg-opacity-100 pawfect-text-gray-600 hover:pawfect-text-pawfect-primary') );
    echo '</div>';
}
