<?php

namespace ShopyPress\Views\Frontend;

use ShopyPress\Utils\OptionUtils;

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

class AllProductsView
{

    // used by [synckube_all_products_grid] shortcode
    static function render(array $atts = [], mixed $content = null)
    {

        // Parse shortcode attributes with defaults
        $atts = shortcode_atts([
            'products_per_page' => 12,
        ], $atts, 'synckube_all_products_grid');

        // Get current page
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

        // Query shopypress-product CPT
        $args = [
            'post_type' => \ShopyPress\Models\ShopyPressProduct::PRODUCT_SLUG,
            'posts_per_page' => (int) $atts['products_per_page'],
            'paged' => $paged,
            'post_status' => 'publish',
            'orderby' => 'date',
            'order' => 'DESC'
        ];
        

        $products_query = new \WP_Query($args);

        ob_start();
?>
        <main class="grid gap-7 sm:grid-cols-2 md:grid-cols-3 [grid-template-columns:repeat(auto-fit,minmax(350px,1fr))] shopypress-products">

            <?php if ($products_query->have_posts()): ?>
                <?php while ($products_query->have_posts()): $products_query->the_post();
                    $product_id = get_the_ID();
                    $product_title = get_the_title();
                    $product_url = get_permalink();

                    // Get product meta
                    $featured_media = get_post_meta($product_id, '_shopify_featured_media', true);
                    $images = get_post_meta($product_id, '_shopify_images', true);
                    $price_min = get_post_meta($product_id, '_shopify_price_min', true);
                    $price_max = get_post_meta($product_id, '_shopify_price_max', true);

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

                    // Get image URL
                    $image_url = '';
                    $image_alt = $product_title;

                    if ($featured_media && isset($featured_media['preview']['url'])) {
                        $image_url = $featured_media['preview']['url'];
                        $image_alt = $featured_media['preview']['alt_text'] ?: $product_title;
                    } elseif (!empty($images) && is_array($images) && isset($images[0]['url'])) {
                        $image_url = $images[0]['url'];
                        $image_alt = $images[0]['alt_text'] ?: $product_title;
                    }

                    // Format price using shop currency settings
                    $price_display = '';
                    if ($price_min && $price_max) {
                        if ($price_min === $price_max) {
                            $price_display = self::formatPrice($price_min);
                        } else {
                            $price_display = self::formatPrice($price_min) . ' - ' . self::formatPrice($price_max);
                        }
                    }
                ?>
                <div class="product-card" data-product-id="<?php echo esc_attr($product_id); ?>" data-product-type="simple">
                    <a target="_self" href="<?php echo esc_url($product_url); ?>" class="!no-underline !outline-none !focus:outline-none !hover:no-underline block relative mb-3 w-full h-[300px] rounded-lg overflow-hidden product-card-image">
                        <div id="skeleton" class="absolute inset-0 bg-gray-200 overflow-hidden z-0">
                            <div class="absolute inset-0
                            bg-gradient-to-r from-gray-200 via-gray-100 to-gray-200
                            animate-[shimmer_1.5s_infinite]">
                            </div>
                        </div>
                        <?php if ($image_url): ?>
                        <img class="relative z-5 w-full h-full object-cover object-center" src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($image_alt); ?>" loading="lazy">
                        <?php endif; ?>

                        <div data-product-id="<?php echo esc_attr($product_id); ?>" class="z-6 opacity-100 md:opacity-0 absolute w-full h-full left-0 top-0 bg-black bg-opacity-10 md:bg-opacity-40
            transition-opacity duration-700 ease-in-out md:hover:opacity-100 shopypress-card-image-preview-ui">
                            <div class="absolute left-0 top-0 w-full h-full flex items-center justify-center">
                                <button onclick="<?php echo esc_attr("window.location.href='". $product_url ."'") ?>" data-product-id="<?php echo esc_attr($product_id); ?>" type="button" class="mb-3 !block !no-underline !outline-none !focus:outline-none !hover:no-underline bg-[#F2F2F2] hover:bg-[#d8d8d8] transition-colors duration-500 text-black hover:text-black font-medium text-center rounded-full py-2 px-4 backdrop-blur-lg">
                                    <?php esc_html_e('View', 'synckube-products-sync-for-shopify'); ?>
                                </button>
                            </div>
                            
                        </div>

                    </a>
                    <div class="product-card-content">
                        <a target="_self" href="<?php echo esc_url($product_url); ?>" class="!no-underline !outline-none !focus:outline-none !hover:no-underline text-lg font-semibold mb-2 block shopypress-product-card-title"><?php echo esc_html($product_title); ?></a>

                        <div class="mb-4 shopypress-product-card-actions">
                            <div class="cart-actions-shopypress">
                                <button type="button" class="mb-3 !block !no-underline !outline-none !focus:outline-none !hover:no-underline
                        w-full bg-[#F2F2F2] hover:bg-[#000000] transition-colors duration-200 text-black font-medium text-center rounded-lg py-2 px-3 shopypress-button-primary">
                                    <?php esc_html_e('View product', 'synckube-products-sync-for-shopify'); ?>
                                </button>
                            </div>
                        </div>

                        <?php if ($price_display): ?>
                        <div class="font-semibold product-card-price"><?php esc_html_e('Price:', 'synckube-products-sync-for-shopify'); ?> <?php echo esc_html($price_display); ?></div>
                        <?php endif; ?>

                        <?php if (!empty($collection_names)): ?>
                        <div class="shopypress-product-card-categories"><?php echo esc_html(implode(', ', $collection_names)); ?></div>
                        <?php endif; ?>

                    </div>
                </div>

                <?php endwhile; ?>
                <?php wp_reset_postdata(); ?>
            <?php else: ?>
                <div class="col-span-full text-center py-12">
                    <p class="text-gray-500 text-lg"><?php esc_html_e('No products found.', 'synckube-products-sync-for-shopify'); ?></p>
                </div>
            <?php endif; ?>

        </main>

        <?php if ($products_query->max_num_pages > 1): ?>
        <div class="mt-8 flex justify-center items-center gap-2 shopypress-pagination">
            <?php
            $current_page = max(1, $paged);
            $total_pages = $products_query->max_num_pages;

            // Previous button
            if ($current_page > 1):
                $prev_link = get_pagenum_link($current_page - 1);
            ?>
                <a href="<?php echo esc_url($prev_link); ?>" class="px-4 py-2 bg-[#F2F2F2] hover:bg-[#000000] hover:text-white transition-colors duration-200 rounded-lg font-medium">
                    <?php esc_html_e('&laquo; Previous', 'synckube-products-sync-for-shopify'); ?>
                </a>
            <?php endif; ?>

            <?php
            // Page numbers
            $range = 2; // Number of pages to show on each side of current page
            $start = max(1, $current_page - $range);
            $end = min($total_pages, $current_page + $range);

            // Show first page + ellipsis if needed
            if ($start > 1):
            ?>
                <a href="<?php echo esc_url(get_pagenum_link(1)); ?>" class="px-4 py-2 bg-[#F2F2F2] hover:bg-[#000000] hover:text-white transition-colors duration-200 rounded-lg font-medium">
                    1
                </a>
                <?php if ($start > 2): ?>
                    <span class="px-2">...</span>
                <?php endif; ?>
            <?php endif; ?>

            <?php for ($i = $start; $i <= $end; $i++): ?>
                <?php if ($i == $current_page): ?>
                    <span class="px-4 py-2 bg-[#000000] text-white rounded-lg font-medium">
                        <?php echo esc_html($i); ?>
                    </span>
                <?php else: ?>
                    <a href="<?php echo esc_url(get_pagenum_link($i)); ?>" class="px-4 py-2 bg-[#F2F2F2] hover:bg-[#000000] hover:text-white transition-colors duration-200 rounded-lg font-medium">
                        <?php echo esc_html($i); ?>
                    </a>
                <?php endif; ?>
            <?php endfor; ?>

            <?php
            // Show ellipsis + last page if needed
            if ($end < $total_pages):
                if ($end < $total_pages - 1):
            ?>
                    <span class="px-2">...</span>
                <?php endif; ?>
                <a href="<?php echo esc_url(get_pagenum_link($total_pages)); ?>" class="px-4 py-2 bg-[#F2F2F2] hover:bg-[#000000] hover:text-white transition-colors duration-200 rounded-lg font-medium">
                    <?php echo esc_html($total_pages); ?>
                </a>
            <?php endif; ?>

            <?php
            // Next button
            if ($current_page < $total_pages):
                $next_link = get_pagenum_link($current_page + 1);
            ?>
                <a href="<?php echo esc_url($next_link); ?>" class="px-4 py-2 bg-[#F2F2F2] hover:bg-[#000000] hover:text-white transition-colors duration-200 rounded-lg font-medium">
                    <?php esc_html_e('Next &raquo;', 'synckube-products-sync-for-shopify'); ?>
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
<?php
        return ob_get_clean();
    }

    /**
     * Format price using shop currency settings
     *
     * @param string|float $amount The price amount
     * @return string Formatted price with currency
     */
    private static function formatPrice($amount): string
    {
        // Get shop currency settings
        $currency_settings = OptionUtils::getInstance()->getOption('shop_currency_settings', null);

        // Format the amount to 2 decimal places
        $formatted_amount = number_format((float)$amount, 2, '.', '');

        // If currency settings exist, use them
        if ($currency_settings && isset($currency_settings['currency_formats']['money_format'])) {
            $money_format = $currency_settings['currency_formats']['money_format'];

            // Replace {{amount}} placeholder with the formatted amount
            $formatted_price = str_replace('{{amount}}', $formatted_amount, $money_format);

            return $formatted_price;
        }

        // Fallback to default format if no currency settings
        return '$' . $formatted_amount;
    }
}
