<?php
/**
 * Single Product Template - Uses AI Theme Elementor Widgets
 *
 * This template renders WooCommerce products using saved template blocks
 * from the AI Generator project's "product" page.
 *
 * @package AI_Theme
 */

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

get_header();

// Get current product - must use wc_get_product() as global may be string
$product = wc_get_product(get_the_ID());

if (!$product || !is_a($product, 'WC_Product')) {
    echo '<div class="ai-error p-8 text-center">Product not found</div>';
    get_footer();
    return;
}

// Get saved template blocks from option
$template_blocks = get_option('ai_product_page_blocks', array());

// Get product data for dynamic substitution
$product_id = $product->get_id();
$product_name = $product->get_name();
$product_price = $product->get_price_html();
$product_regular_price = $product->get_regular_price();
$product_sale_price = $product->get_sale_price();
$product_description = $product->get_description();
$product_short_description = $product->get_short_description();
$product_sku = $product->get_sku();
$product_categories = wc_get_product_category_list($product_id, ', ');

// Get product images
$gallery_image_ids = $product->get_gallery_image_ids();
$main_image_id = $product->get_image_id();

// Build gallery array
$gallery = [];
if ($main_image_id) {
    $gallery[] = ['image' => ['url' => wp_get_attachment_url($main_image_id), 'id' => $main_image_id]];
}
foreach ($gallery_image_ids as $image_id) {
    $gallery[] = ['image' => ['url' => wp_get_attachment_url($image_id), 'id' => $image_id]];
}

// Format prices
$formatted_price = wc_price($product->get_price());
$formatted_old_price = '';
if ($product->is_on_sale() && $product_regular_price) {
    $formatted_old_price = wc_price($product_regular_price);
}

// Strip HTML from category list for clean display
$category_text = wp_strip_all_tags($product_categories);
?>

<div data-theme="<?php echo esc_attr(get_option('ai_theme_style', 'modern')); ?>">

<?php
// If we have saved template blocks, render them
if (!empty($template_blocks)) {
    $product_block_rendered = false;

    foreach ($template_blocks as $block) {
        $block_type = $block['type'] ?? '';
        $block_content = $block['content'] ?? array();
        $block_variant = $block['variant'] ?? '';

        // Build full widget type name
        $widget_type = $block_type;
        if ($block_variant) {
            $widget_type = $block_type . '-' . $block_variant;
        }

        // For product block, render our custom product detail
        if ($block_type === 'product') {
            $product_block_rendered = true;
            // Render the product detail section
            render_product_detail_section($product, $gallery, $category_text);
        } else {
            // Render other blocks using the template block renderer
            echo ai_theme_render_widget($widget_type, $block_content, $product);
        }
    }

    // If no product block was in the template, still render product detail
    if (!$product_block_rendered) {
        render_product_detail_section($product, $gallery, $category_text);
    }

} else {
    // Fallback: render default template if no blocks saved

    // Breadcrumbs
    $breadcrumb_items = [
        ['text' => __('Home', 'ai-theme'), 'link' => ['url' => home_url('/')]],
        ['text' => __('Shop', 'ai-theme'), 'link' => ['url' => get_permalink(wc_get_page_id('shop'))]],
    ];

    $categories = get_the_terms($product_id, 'product_cat');
    if ($categories && !is_wp_error($categories)) {
        $main_category = $categories[0];
        $breadcrumb_items[] = [
            'text' => $main_category->name,
            'link' => ['url' => get_term_link($main_category)]
        ];
    }
    $breadcrumb_items[] = ['text' => $product_name, 'link' => ['url' => '']];

    ai_render_breadcrumbs_block(array('items' => $breadcrumb_items), null);

    // Product Detail
    render_product_detail_section($product, $gallery, $category_text);
}
?>

</div>

<?php
get_footer();

/**
 * Render product detail section
 */
function render_product_detail_section($product, $gallery, $category_text) {
    $product_id = $product->get_id();
    $product_name = $product->get_name();
    $product_description = $product->get_description();
    $product_short_description = $product->get_short_description();
    $product_sku = $product->get_sku();
    ?>
    <!-- Product Detail -->
    <div class="ai-product ai-product-detail w-full bg-white py-12">
        <div class="ai-container">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-12">
                <!-- Left Column - Gallery -->
                <div class="ai-product-gallery space-y-4">
                    <?php if (!empty($gallery)) : ?>
                    <!-- Main Image -->
                    <div class="ai-product-main-image relative aspect-square bg-gray-100 rounded-xl overflow-hidden" id="product-main-image">
                        <img src="<?php echo esc_url($gallery[0]['image']['url']); ?>" alt="<?php echo esc_attr($product_name); ?>" class="w-full h-full object-cover" id="main-product-image">
                    </div>

                    <!-- Thumbnails -->
                    <?php if (count($gallery) > 1) : ?>
                    <div class="ai-product-thumbnails grid grid-cols-4 gap-3">
                        <?php foreach ($gallery as $i => $img) : ?>
                        <button
                            onclick="document.getElementById('main-product-image').src = '<?php echo esc_url($img['image']['url']); ?>'; document.querySelectorAll('.ai-product-thumbnails button').forEach(b => b.classList.remove('border-primary', 'ring-2', 'ring-blue-200')); this.classList.add('border-primary', 'ring-2', 'ring-blue-200');"
                            class="aspect-square bg-gray-100 rounded-lg overflow-hidden border-2 transition-all <?php echo $i === 0 ? 'border-primary ring-2 ring-blue-200' : 'border-transparent hover:border-gray-300'; ?>">
                            <img src="<?php echo esc_url($img['image']['url']); ?>" alt="" class="w-full h-full object-cover">
                        </button>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                    <?php else : ?>
                    <div class="ai-product-main-image relative aspect-square bg-gray-100 rounded-xl overflow-hidden flex items-center justify-center">
                        <span class="text-gray-400"><?php _e('No image', 'ai-theme'); ?></span>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Right Column - Product Info -->
                <div class="ai-product-info space-y-6">
                    <!-- Title -->
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900 mb-2"><?php echo esc_html($product_name); ?></h1>
                    </div>

                    <!-- Price -->
                    <div class="ai-product-price flex items-baseline gap-3">
                        <?php if ($product->is_on_sale()) : ?>
                            <span class="ai-product-current-price text-4xl font-bold text-gray-900"><?php echo wc_price($product->get_sale_price()); ?></span>
                            <span class="ai-product-old-price text-xl text-gray-500 line-through"><?php echo wc_price($product->get_regular_price()); ?></span>
                        <?php else : ?>
                            <span class="ai-product-current-price text-4xl font-bold text-gray-900"><?php echo wc_price($product->get_price()); ?></span>
                        <?php endif; ?>
                    </div>

                    <!-- Short Description -->
                    <?php if ($product_short_description) : ?>
                    <div class="ai-product-short-description text-gray-600 text-lg">
                        <?php echo wp_kses_post($product_short_description); ?>
                    </div>
                    <?php endif; ?>

                    <!-- Add to Cart Form -->
                    <div class="ai-product-add-to-cart-form">
                        <?php if ($product->is_purchasable() && $product->is_in_stock()) : ?>
                        <form class="cart flex items-center gap-4" action="<?php echo esc_url(apply_filters('woocommerce_add_to_cart_form_action', $product->get_permalink())); ?>" method="post" enctype='multipart/form-data'>
                            <div class="ai-quantity-wrapper flex items-center border border-gray-300 rounded-lg">
                                <button type="button" onclick="var qty = this.parentNode.querySelector('input'); qty.value = Math.max(1, parseInt(qty.value) - 1);" class="px-4 py-3 text-gray-600 hover:text-gray-900 transition-colors">-</button>
                                <input type="number" name="quantity" value="1" min="1" max="<?php echo $product->get_stock_quantity() ?: 999; ?>" class="w-16 text-center border-0 focus:ring-0 py-3" />
                                <button type="button" onclick="var qty = this.parentNode.querySelector('input'); qty.value = parseInt(qty.value) + 1;" class="px-4 py-3 text-gray-600 hover:text-gray-900 transition-colors">+</button>
                            </div>
                            <button type="submit" name="add-to-cart" value="<?php echo esc_attr($product_id); ?>" class="flex-1 bg-primary text-white py-4 px-6 rounded-lg font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2">
                                <i class="fas fa-shopping-cart"></i>
                                <?php echo esc_html($product->single_add_to_cart_text()); ?>
                            </button>
                        </form>
                        <?php elseif (!$product->is_in_stock()) : ?>
                        <p class="stock out-of-stock bg-red-100 text-red-800 py-3 px-4 rounded-lg font-medium">
                            <?php echo esc_html(apply_filters('woocommerce_out_of_stock_message', __('This product is currently out of stock and unavailable.', 'woocommerce'))); ?>
                        </p>
                        <?php endif; ?>
                    </div>

                    <!-- Meta Information -->
                    <div class="ai-product-meta border-t border-gray-200 pt-6 space-y-2 text-sm text-gray-600">
                        <?php if ($product_sku) : ?>
                        <p><strong class="text-gray-900"><?php _e('SKU:', 'ai-theme'); ?></strong> <?php echo esc_html($product_sku); ?></p>
                        <?php endif; ?>
                        <?php if ($category_text) : ?>
                        <p><strong class="text-gray-900"><?php _e('Category:', 'ai-theme'); ?></strong> <?php echo esc_html($category_text); ?></p>
                        <?php endif; ?>
                        <?php if ($product->get_stock_status() === 'instock') : ?>
                        <p><strong class="text-gray-900"><?php _e('Availability:', 'ai-theme'); ?></strong> <span class="text-green-600"><?php _e('In Stock', 'ai-theme'); ?></span></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Tabs: Description, Specifications, Reviews -->
            <div class="ai-product-tabs mt-16 pt-8 border-t border-gray-200">
                <!-- Tab Navigation -->
                <div class="flex border-b border-gray-200 mb-8">
                    <?php if ($product_description) : ?>
                    <button onclick="showProductTab('description')" id="tab-btn-description" class="ai-tab-btn px-6 py-3 text-lg font-medium border-b-2 border-primary text-primary transition-colors">
                        <?php _e('Description', 'ai-theme'); ?>
                    </button>
                    <?php endif; ?>
                    <?php
                    $attributes = $product->get_attributes();
                    if (!empty($attributes)) : ?>
                    <button onclick="showProductTab('specifications')" id="tab-btn-specifications" class="ai-tab-btn px-6 py-3 text-lg font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700 transition-colors">
                        <?php _e('Specifications', 'ai-theme'); ?>
                    </button>
                    <?php endif; ?>
                    <?php
                    $reviews_count = $product->get_review_count();
                    if ($reviews_count > 0 || comments_open($product_id)) : ?>
                    <button onclick="showProductTab('reviews')" id="tab-btn-reviews" class="ai-tab-btn px-6 py-3 text-lg font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700 transition-colors">
                        <?php printf(__('Reviews (%d)', 'ai-theme'), $reviews_count); ?>
                    </button>
                    <?php endif; ?>
                </div>

                <!-- Tab Content: Description -->
                <?php if ($product_description) : ?>
                <div id="tab-description" class="ai-tab-content">
                    <div class="prose prose-lg max-w-none text-gray-600">
                        <?php echo wp_kses_post($product_description); ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Tab Content: Specifications -->
                <?php if (!empty($attributes)) : ?>
                <div id="tab-specifications" class="ai-tab-content hidden">
                    <div class="overflow-hidden rounded-lg border border-gray-200">
                        <table class="w-full">
                            <tbody class="divide-y divide-gray-200">
                                <?php foreach ($attributes as $attribute) :
                                    $attr_name = wc_attribute_label($attribute->get_name());
                                    $attr_values = $attribute->is_taxonomy()
                                        ? wc_get_product_terms($product_id, $attribute->get_name(), array('fields' => 'names'))
                                        : $attribute->get_options();
                                    $attr_value = is_array($attr_values) ? implode(', ', $attr_values) : $attr_values;
                                ?>
                                <tr class="hover:bg-gray-50">
                                    <th class="px-6 py-4 text-left text-sm font-semibold text-gray-900 bg-gray-50 w-1/3"><?php echo esc_html($attr_name); ?></th>
                                    <td class="px-6 py-4 text-sm text-gray-600"><?php echo esc_html($attr_value); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Tab Content: Reviews -->
                <?php if ($reviews_count > 0 || comments_open($product_id)) : ?>
                <div id="tab-reviews" class="ai-tab-content hidden">
                    <?php
                    // Get reviews
                    $reviews = get_comments(array(
                        'post_id' => $product_id,
                        'status' => 'approve',
                        'type' => 'review',
                        'orderby' => 'comment_date',
                        'order' => 'DESC',
                    ));

                    // Average rating
                    $average_rating = $product->get_average_rating();
                    ?>

                    <!-- Rating Summary -->
                    <div class="flex items-center gap-6 mb-8 p-6 bg-gray-50 rounded-xl">
                        <div class="text-center">
                            <div class="text-5xl font-bold text-gray-900"><?php echo number_format($average_rating, 1); ?></div>
                            <div class="flex items-center justify-center gap-1 mt-2">
                                <?php for ($i = 1; $i <= 5; $i++) : ?>
                                    <i class="fas fa-star <?php echo $i <= round($average_rating) ? 'text-yellow-400' : 'text-gray-300'; ?>"></i>
                                <?php endfor; ?>
                            </div>
                            <div class="text-sm text-gray-500 mt-1"><?php printf(__('%d reviews', 'ai-theme'), $reviews_count); ?></div>
                        </div>
                    </div>

                    <!-- Reviews List -->
                    <?php if (!empty($reviews)) : ?>
                    <div class="space-y-6">
                        <?php foreach ($reviews as $review) :
                            $rating = get_comment_meta($review->comment_ID, 'rating', true);
                        ?>
                        <div class="ai-review-card bg-white border border-gray-200 rounded-xl p-6">
                            <div class="flex items-start justify-between mb-4">
                                <div class="flex items-center gap-3">
                                    <?php echo get_avatar($review->comment_author_email, 48, '', '', array('class' => 'rounded-full')); ?>
                                    <div>
                                        <h4 class="font-semibold text-gray-900"><?php echo esc_html($review->comment_author); ?></h4>
                                        <p class="text-sm text-gray-500"><?php echo date_i18n(get_option('date_format'), strtotime($review->comment_date)); ?></p>
                                    </div>
                                </div>
                                <div class="flex items-center gap-1">
                                    <?php for ($i = 1; $i <= 5; $i++) : ?>
                                        <i class="fas fa-star text-sm <?php echo $i <= $rating ? 'text-yellow-400' : 'text-gray-300'; ?>"></i>
                                    <?php endfor; ?>
                                </div>
                            </div>
                            <div class="text-gray-600">
                                <?php echo wp_kses_post($review->comment_content); ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php else : ?>
                    <p class="text-gray-500 text-center py-8"><?php _e('No reviews yet. Be the first to review this product!', 'ai-theme'); ?></p>
                    <?php endif; ?>

                    <!-- Review Form -->
                    <?php if (comments_open($product_id)) : ?>
                    <div class="mt-8 pt-8 border-t border-gray-200">
                        <h3 class="text-xl font-bold text-gray-900 mb-6"><?php _e('Write a Review', 'ai-theme'); ?></h3>
                        <?php
                        // Simple review form
                        if (is_user_logged_in()) :
                            $commenter = wp_get_current_commenter();
                        ?>
                        <form action="<?php echo site_url('/wp-comments-post.php'); ?>" method="post" class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2"><?php _e('Your Rating', 'ai-theme'); ?></label>
                                <div class="flex gap-2" id="rating-stars">
                                    <?php for ($i = 1; $i <= 5; $i++) : ?>
                                    <button type="button" onclick="setRating(<?php echo $i; ?>)" class="rating-star text-2xl text-gray-300 hover:text-yellow-400 transition-colors">
                                        <i class="fas fa-star"></i>
                                    </button>
                                    <?php endfor; ?>
                                </div>
                                <input type="hidden" name="rating" id="rating-input" value="5">
                            </div>
                            <div>
                                <label for="comment" class="block text-sm font-medium text-gray-700 mb-2"><?php _e('Your Review', 'ai-theme'); ?></label>
                                <textarea name="comment" id="comment" rows="4" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="<?php _e('Share your thoughts about this product...', 'ai-theme'); ?>"></textarea>
                            </div>
                            <input type="hidden" name="comment_post_ID" value="<?php echo $product_id; ?>">
                            <input type="hidden" name="comment_parent" value="0">
                            <button type="submit" class="bg-primary text-white px-6 py-3 rounded-lg font-semibold hover:opacity-90 transition-opacity">
                                <?php _e('Submit Review', 'ai-theme'); ?>
                            </button>
                        </form>
                        <?php else : ?>
                        <p class="text-gray-500">
                            <?php printf(__('You must be <a href="%s" class="text-primary hover:underline">logged in</a> to post a review.', 'ai-theme'), wp_login_url(get_permalink())); ?>
                        </p>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- Tab JS -->
            <script>
            function showProductTab(tabId) {
                // Hide all tabs
                document.querySelectorAll('.ai-tab-content').forEach(tab => tab.classList.add('hidden'));
                // Deactivate all buttons
                document.querySelectorAll('.ai-tab-btn').forEach(btn => {
                    btn.classList.remove('border-primary', 'text-primary');
                    btn.classList.add('border-transparent', 'text-gray-500');
                });
                // Show selected tab
                const tab = document.getElementById('tab-' + tabId);
                if (tab) tab.classList.remove('hidden');
                // Activate button
                const btn = document.getElementById('tab-btn-' + tabId);
                if (btn) {
                    btn.classList.add('border-primary', 'text-primary');
                    btn.classList.remove('border-transparent', 'text-gray-500');
                }
            }
            function setRating(rating) {
                document.getElementById('rating-input').value = rating;
                document.querySelectorAll('.rating-star').forEach((star, i) => {
                    star.classList.toggle('text-yellow-400', i < rating);
                    star.classList.toggle('text-gray-300', i >= rating);
                });
            }
            // Initialize rating stars
            document.addEventListener('DOMContentLoaded', function() { setRating(5); });
            </script>
        </div>
    </div>
    <?php
}
