<?php

namespace ShopyPress\Views\Frontend;

use ShopyPress\Utils\OptionUtils;
use ShopyPress\Models\ShopyPressProduct;

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

class ProductSingle
{
    // render single product page
    static function render() {
        global $post;

        // Get product ID
        $product_id = get_the_ID();

        // Retrieve all product meta data
        $product_data = self::getProductData($product_id);

        // Get Shopify handle for context
        $shopify_handle = $product_data['shopify_handle'] ?? '';

        ?>
        <div id="primary" class="content-area">
            <main id="main" class="site-main shopypress-single-product">

                <?php if (!empty($shopify_handle)): ?>
                    <div class="container mx-auto px-4 py-8 max-w-7xl">

                        <!-- Two Column Layout -->
                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12">

                            <!-- LEFT COLUMN: Gallery -->
                            <div class="shopypress-product-gallery">
                                <?php self::renderGallery($product_data); ?>
                            </div>

                            <!-- RIGHT COLUMN: Product Info -->
                            <div class="shopypress-product-info">
                                <?php self::renderProduct($product_data, $shopify_handle) ?>
                            </div>

                        </div>
                    </div>
                <?php endif; ?>

            </main>
        </div>
        <?php
    }

    /**
     * Get all product data needed for the single page
     */
    public static function getProductData($product_id) {
        $data = [
            'id' => $product_id,
            'title' => get_the_title($product_id),
            'description' => get_post_field('post_content', $product_id),
            'featured_media' => get_post_meta($product_id, '_shopify_featured_media', true),
            'images' => get_post_meta($product_id, '_shopify_images', true) ?: [],
            'variants' => get_post_meta($product_id, '_shopify_variants', true) ?: [],
            'options' => get_post_meta($product_id, '_shopify_options', true) ?: [],
            'price_min' => get_post_meta($product_id, '_shopify_price_min', true),
            'price_max' => get_post_meta($product_id, '_shopify_price_max', true),
            'collections' => [],
            'shopify_handle' => get_post_meta($product_id, '_shopify_handle', true),
            'shopify_product_id' => get_post_meta($product_id, '_shopify_product_id', true),
        ];

        // Get collections (categories)
        $collections = get_the_terms($product_id, ShopyPressProduct::COLLECTION_TAXONOMY);
        if ($collections && !is_wp_error($collections)) {
            $data['collections'] = array_map(function($term) {
                return $term->name;
            }, $collections);
        }

        return $data;
    }

    /**
     * Render gallery section with main image and thumbnails
     */
    private static function renderGallery($product_data) {
        $images = self::prepareGalleryImages($product_data);
        ?>
        <div class="product-gallery-container" id="shopypress-single-product-gallery">

            <!-- Main Image -->
            <div class="main-image-container mb-4 bg-gray-100 rounded-lg overflow-hidden relative">
                <div class="swiper shopypress-main-swiper">
                    <div class="swiper-wrapper">
                        <?php foreach ($images as $image): ?>
                        <div class="swiper-slide">
                            <div class="aspect-square w-full relative">
                                <img
                                    src="<?php echo esc_url($image['url']); ?>"
                                    alt="<?php echo esc_attr($image['alt']); ?>"
                                    class="w-full h-full object-cover object-center"
                                    loading="lazy"
                                />
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Navigation arrows -->
                    <div class="swiper-button-prev"></div>
                    <div class="swiper-button-next"></div>
                </div>
            </div>

            <!-- Thumbnails -->
            <?php if (count($images) > 1): ?>
            <div class="thumbnail-container">
                <div class="swiper shopypress-thumbs-swiper">
                    <div class="swiper-wrapper">
                        <?php foreach ($images as $index => $image): ?>
                        <div class="swiper-slide">
                            <div class="thumbnail-wrapper border-2 border-transparent rounded-lg overflow-hidden cursor-pointer transition-all hover:border-gray-400">
                                <div class="aspect-square w-full relative">
                                    <img
                                        src="<?php echo esc_url($image['thumbnail']); ?>"
                                        alt="<?php echo esc_attr($image['alt']); ?>"
                                        class="w-full h-full object-cover"
                                    />
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

        </div>
        <?php
    }

    private static function renderProduct(array $product_data, string $shopify_handle) {
        ?>
        <div class="product-info-container">

            <!-- Product Title -->
            <h1 class="text-3xl md:text-4xl font-bold mb-4"><?php echo esc_html($product_data['title']); ?></h1>

            <!-- Product Description -->
            <?php if (!empty($product_data['description'])): ?>
            <div class="product-description mb-6 text-gray-700">
                <?php echo wp_kses_post($product_data['description']); ?>
            </div>
            <?php endif; ?>

            <shopify-context type="product" handle="<?php echo esc_attr($shopify_handle); ?>">
                <template>
                    <div class="flex font-semibold text-2xl mb-4 shopypress-price-ui">
                        <div class="mr-2 price-label">
                            <?php esc_html_e('Price', 'synckube-products-sync-for-shopify') ?>:
                        </div>
                        <div class="product-modal__price-container shopypress-product-price">
                            <shopify-money query="product.selectedOrFirstAvailableVariant.price"></shopify-money>
                            <shopify-money
                                class="product-modal__compare-price"
                                query="product.selectedOrFirstAvailableVariant.compareAtPrice"
                            ></shopify-money>
                        </div>
                    </div>
                    <div class="mb-8 shopypress-product-variant-selector">
                        <shopify-variant-selector></shopify-variant-selector>
                    </div>
                        <div class="flex flex-col md:flex-row product-action-buttons">
                            <button
                                class="w-full md:w-auto md:mr-4 font-semibold py-3 px-6 rounded-lg transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed shopypress-product-action-btn product__add-button"
                                onclick="getElementById('shopypress-cart').addLine(event).showModal();"
                                shopify-attr--disabled="!product.selectedOrFirstAvailableVariant.availableForSale"
                            >
                                <?php esc_html_e('Add to cart', 'synckube-products-sync-for-shopify') ?>
                            </button>

                            <button
                                class="w-full md:w-auto mt-3 md:mt-0 font-semibold py-3 px-6 rounded-lg disabled:bg-gray-300 disabled:cursor-not-allowed shopypress-product-action-btn product__buy-button"
                                onclick="document.querySelector('shopify-store').buyNow(event)"
                                shopify-attr--disabled="!product.selectedOrFirstAvailableVariant.availableForSale"
                            >
                                <?php esc_html_e('Buy now', 'synckube-products-sync-for-shopify') ?>
                            </button>
                        </div>

                </template>

            </shopify-context>
        </div>
        <?php
    }


    /**
     * Prepare gallery images from product data
     */
    public static function prepareGalleryImages($product_data) {
        $images = [];

        // Add featured media first if exists
        if (!empty($product_data['featured_media']['preview'])) {
            $images[] = [
                'id' => $product_data['featured_media']['id'] ?? '',
                'url' => $product_data['featured_media']['preview']['url'],
                'thumbnail' => $product_data['featured_media']['preview']['url'], // Use same for thumbnail
                'alt' => $product_data['featured_media']['preview']['alt_text'] ?? $product_data['title'],
            ];
        }

        // Add other images
        if (!empty($product_data['images'])) {
            foreach ($product_data['images'] as $image) {
                // Skip if already added as featured
                if (isset($image['id']) && isset($product_data['featured_media']['id'])
                    && $image['id'] === $product_data['featured_media']['id']) {
                    continue;
                }

                $images[] = [
                    'id' => $image['id'] ?? '',
                    'url' => $image['url'],
                    'thumbnail' => $image['url'], // Use same for thumbnail
                    'alt' => $image['alt_text'] ?? $product_data['title'],
                ];
            }
        }

        // Fallback if no images
        if (empty($images)) {
            $images[] = [
                'id' => '',
                'url' => self::getPlaceholderImage(),
                'thumbnail' => self::getPlaceholderImage(),
                'alt' => esc_attr__('No image available', 'synckube-products-sync-for-shopify'),
            ];
        }

        return $images;
    }

    /**
     * Format price range
     */
    private static function formatPriceRange($price_min, $price_max) {
        if (!$price_min && !$price_max) {
            return '';
        }

        if ($price_min === $price_max) {
            return self::formatPrice($price_min);
        }

        return self::formatPrice($price_min) . ' - ' . self::formatPrice($price_max);
    }

    /**
     * Format price with currency
     */
    private static function formatPrice($amount) {
        $currency_settings = OptionUtils::getInstance()->getOption('shop_currency_settings', null);
        $formatted_amount = number_format((float)$amount, 2, '.', '');

        if ($currency_settings && isset($currency_settings['currency_formats']['money_format'])) {
            $money_format = $currency_settings['currency_formats']['money_format'];
            return str_replace('{{amount}}', $formatted_amount, $money_format);
        }

        return '$' . $formatted_amount;
    }

    /**
     * Get placeholder image URL
     */
    private static function getPlaceholderImage() {
        return 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="400" height="400"%3E%3Crect fill="%23f0f0f0" width="400" height="400"/%3E%3Ctext fill="%23999" font-family="sans-serif" font-size="20" text-anchor="middle" x="200" y="200"%3ENo image available%3C/text%3E%3C/svg%3E';
    }

    static function getContent() {
        ob_start();
        self::render();
        return ob_get_clean();
    }
}