/*
 Theme Name:   Woodmart Child
 Description:  Woodmart Child Theme
 Author:       XTemos
 Author URI:   http://xtemos.com
 Template:     woodmart
 Version:      1.0.0
 Text Domain:  woodmart
*/





/**
 * ACF Post Slider for WordPress Elementor (WoodMart Theme Compatible)
 * With Multilingual Support (English detection via /en in URL)
 * Add this code to your theme's functions.php file
 */

// Enqueue styles and scripts
function acf_post_slider_enqueue_assets() {
    if (!wp_script_is('jquery', 'enqueued')) {
        wp_enqueue_script('jquery');
    }
    
    // Inline CSS with higher specificity for WoodMart compatibility
    $css = '
    .acf-post-slider {
        position: relative !important;
        width: 100% !important;
        height: 380px !important;
        overflow: hidden !important;
        border-radius: 8px !important;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
        background: #f8f8f8 !important;
        margin: 0 !important;
        padding: 0 !important;
    }
    
    .acf-slider-container {
        position: relative !important;
        width: 100% !important;
        height: 100% !important;
        overflow: hidden !important;
        margin: 0 !important;
        padding: 0 !important;
    }
    
    .acf-slider-track {
        display: flex !important;
        width: 100% !important;
        height: 100% !important;
        transition: transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) !important;
        will-change: transform !important;
        margin: 0 !important;
        padding: 0 !important;
        list-style: none !important;
    }
    
    .acf-slide {
        flex: 0 0 100% !important;
        min-width: 100% !important;
        width: 100% !important;
        height: 100% !important;
        position: relative !important;
        overflow: hidden !important;
        margin: 0 !important;
        padding: 0 !important;
        display: block !important;
        float: none !important;
    }
    
    .acf-slide a,
    .acf-slide a:hover,
    .acf-slide a:focus,
    .acf-slide a:active {
        display: block !important;
        width: 100% !important;
        height: 100% !important;
        position: relative !important;
        overflow: hidden !important;
        text-decoration: none !important;
        border: none !important;
        outline: none !important;
        margin: 0 !important;
        padding: 0 !important;
    }
    
    .acf-slide img {
        width: 100% !important;
        height: 100% !important;
        object-fit: cover !important;
        object-position: center !important;
        display: block !important;
        transition: transform 0.3s ease !important;
        border: none !important;
        margin: 0 !important;
        padding: 0 !important;
        max-width: none !important;
        max-height: none !important;
    }
    
    .acf-slide a:hover img {
        transform: scale(1.05) !important;
    }
    
    .acf-slider-controls {
        position: absolute !important;
        bottom: 20px !important;
        left: 50% !important;
        transform: translateX(-50%) !important;
        display: flex !important;
        align-items: center !important;
        gap: 15px !important;
        padding: 12px 20px !important;
        background: rgba(0, 0, 0, 0.3) !important;
        backdrop-filter: blur(10px) !important;
        -webkit-backdrop-filter: blur(10px) !important;
        border-radius: 25px !important;
        transition: opacity 0.3s ease !important;
        z-index: 10 !important;
        margin: 0 !important;
    }
    
    .acf-slider-arrow {
        background: rgba(255, 255, 255, 0.2) !important;
        border: 1px solid rgba(255, 255, 255, 0.3) !important;
        border-radius: 50% !important;
        width: 40px !important;
        height: 40px !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        cursor: pointer !important;
        transition: all 0.3s ease !important;
        color: white !important;
        font-size: 16px !important;
        user-select: none !important;
        text-decoration: none !important;
        margin: 0 !important;
        padding: 0 !important;
        line-height: 1 !important;
        font-family: Arial, sans-serif !important;
    }
    
    .acf-slider-arrow:hover {
        background: rgba(255, 255, 255, 0.3) !important;
        transform: scale(1.1) !important;
        text-decoration: none !important;
    }
    
    .acf-slider-arrow:active {
        transform: scale(0.95) !important;
    }
    
    .acf-slider-dots {
        display: flex !important;
        gap: 8px !important;
        margin: 0 !important;
        padding: 0 !important;
        list-style: none !important;
    }
    
    .acf-slider-dot {
        width: 10px !important;
        height: 10px !important;
        border-radius: 50% !important;
        background: rgba(255, 255, 255, 0.4) !important;
        cursor: pointer !important;
        transition: all 0.3s ease !important;
        margin: 0 !important;
        padding: 0 !important;
        border: none !important;
    }
    
    .acf-slider-dot.active {
        background: white !important;
        transform: scale(1.2) !important;
    }
    
    .acf-slider-dot:hover {
        background: rgba(255, 255, 255, 0.7) !important;
    }
    
    /* Mobile Styles */
    @media (max-width: 768px) {
        .acf-post-slider {
            height: auto !important;
            min-height: 250px !important;
        }
        
        .acf-slider-container {
            min-height: 250px !important;
        }
        
        .acf-slide {
            height: auto !important;
            min-height: 250px !important;
        }
        
        .acf-slide img {
            height: auto !important;
            min-height: 250px !important;
            object-fit: cover !important;
        }
        
        .acf-slider-controls {
            padding: 10px 16px !important;
            gap: 12px !important;
            bottom: 15px !important;
        }
        
        .acf-slider-arrow {
            width: 35px !important;
            height: 35px !important;
            font-size: 14px !important;
        }
        
        .acf-slider-dot {
            width: 8px !important;
            height: 8px !important;
        }
    }
    
    /* WoodMart specific overrides */
    .elementor-widget-container .acf-post-slider {
        margin: 0 !important;
    }
    
    .acf-post-slider * {
        box-sizing: border-box !important;
    }
    
    /* Prevent WoodMart image lazy loading conflicts */
    .acf-slide img.lazy {
        opacity: 1 !important;
    }
    ';
    
    wp_add_inline_style('wp-block-library', $css);
    
    // Enhanced JavaScript with WoodMart compatibility
    $js = '
    jQuery(document).ready(function($) {
        function initACFSlider() {
            $(".acf-post-slider").each(function() {
                var slider = $(this);
                
                // Skip if already initialized
                if (slider.hasClass("acf-slider-initialized")) {
                    return;
                }
                
                var track = slider.find(".acf-slider-track");
                var slides = slider.find(".acf-slide");
                var dots = slider.find(".acf-slider-dot");
                var prevBtn = slider.find(".acf-slider-prev");
                var nextBtn = slider.find(".acf-slider-next");
                var currentSlide = 0;
                var totalSlides = slides.length;
                var autoplayInterval;
                var isAnimating = false;
                
                slider.addClass("acf-slider-initialized");
                
                if (totalSlides <= 1) {
                    slider.find(".acf-slider-controls").hide();
                    return;
                }
                
                // Force proper dimensions
                slider.css({
                    "position": "relative",
                    "overflow": "hidden"
                });
                
                track.css({
                    "display": "flex",
                    "width": (totalSlides * 100) + "%",
                    "height": "100%"
                });
                
                slides.each(function(index) {
                    $(this).css({
                        "flex": "0 0 " + (100 / totalSlides) + "%",
                        "width": (100 / totalSlides) + "%"
                    });
                });
                
                function goToSlide(index, animate) {
                    if (isAnimating && animate !== false) return;
                    
                    if (index < 0) index = totalSlides - 1;
                    if (index >= totalSlides) index = 0;
                    
                    currentSlide = index;
                    isAnimating = animate !== false;
                    
                    var translateX = -(100 / totalSlides) * currentSlide;
                    
                    if (animate === false) {
                        track.css("transition", "none");
                    } else {
                        track.css("transition", "transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94)");
                    }
                    
                    track.css("transform", "translateX(" + translateX + "%)");
                    
                    dots.removeClass("active");
                    if (dots.length > 0) {
                        dots.eq(currentSlide).addClass("active");
                    }
                    
                    if (animate !== false) {
                        setTimeout(function() {
                            isAnimating = false;
                        }, 500);
                    }
                }
                
                function nextSlide() {
                    if (isAnimating) return;
                    currentSlide = (currentSlide + 1) % totalSlides;
                    goToSlide(currentSlide);
                }
                
                function prevSlide() {
                    if (isAnimating) return;
                    currentSlide = (currentSlide - 1 + totalSlides) % totalSlides;
                    goToSlide(currentSlide);
                }
                
                function startAutoplay() {
                    stopAutoplay();
                    autoplayInterval = setInterval(nextSlide, 5000);
                }
                
                function stopAutoplay() {
                    if (autoplayInterval) {
                        clearInterval(autoplayInterval);
                        autoplayInterval = null;
                    }
                }
                
                // Event listeners
                nextBtn.on("click", function(e) {
                    e.preventDefault();
                    nextSlide();
                    stopAutoplay();
                    startAutoplay();
                });
                
                prevBtn.on("click", function(e) {
                    e.preventDefault();
                    prevSlide();
                    stopAutoplay();
                    startAutoplay();
                });
                
                dots.on("click", function(e) {
                    e.preventDefault();
                    var index = $(this).index();
                    goToSlide(index);
                    stopAutoplay();
                    startAutoplay();
                });
                
                // Touch/swipe support
                var startX = 0;
                var isDragging = false;
                var threshold = 50;
                
                slider.on("touchstart mousedown", function(e) {
                    if (isAnimating) return;
                    startX = e.type === "touchstart" ? e.originalEvent.touches[0].clientX : e.clientX;
                    isDragging = true;
                    stopAutoplay();
                });
                
                slider.on("touchmove mousemove", function(e) {
                    if (!isDragging || isAnimating) return;
                    e.preventDefault();
                });
                
                slider.on("touchend mouseup mouseleave", function(e) {
                    if (!isDragging || isAnimating) return;
                    isDragging = false;
                    
                    var endX = e.type === "touchend" ? e.originalEvent.changedTouches[0].clientX : e.clientX;
                    var diff = startX - endX;
                    
                    if (Math.abs(diff) > threshold) {
                        if (diff > 0) {
                            nextSlide();
                        } else {
                            prevSlide();
                        }
                    }
                    startAutoplay();
                });
                
                // Pause on hover
                slider.on("mouseenter", stopAutoplay);
                slider.on("mouseleave", function() {
                    if (!isDragging) {
                        startAutoplay();
                    }
                });
                
                // Handle window resize
                $(window).on("resize", function() {
                    goToSlide(currentSlide, false);
                });
                
                // Initialize
                goToSlide(0, false);
                startAutoplay();
            });
        }
        
        // Initialize immediately
        initACFSlider();
        
        // Re-initialize after Elementor preview updates
        if (typeof elementorFrontend !== "undefined") {
            elementorFrontend.hooks.addAction("frontend/element_ready/widget", function() {
                setTimeout(initACFSlider, 100);
            });
        }
        
        // Re-initialize after AJAX content loads
        $(document).ajaxComplete(function() {
            setTimeout(initACFSlider, 100);
        });
    });
    ';
    
    wp_add_inline_script('jquery', $js);
}
add_action('wp_enqueue_scripts', 'acf_post_slider_enqueue_assets');

/**
 * Helper function to check if current URL is English version
 * Detects /en/ or /en at the end of domain path
 */
function acf_slider_is_english() {
    // Use TranslatePress language detection if available
    if (class_exists('TRP_Translate_Press')) {
        global $TRP_LANGUAGE;
        return ($TRP_LANGUAGE === 'en_US' || $TRP_LANGUAGE === 'en_GB');
    }
    
    // Fallback to URL detection
    $current_url = $_SERVER['REQUEST_URI'];
    if (preg_match('/^\/en(\/|$)/', $current_url)) {
        return true;
    }
    return false;
}

// Shortcode function with multilingual support
function acf_post_slider_shortcode($atts) {
    $atts = shortcode_atts(array(
        'post_type' => 'slide',
        'posts_per_page' => -1,
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'class' => ''
    ), $atts);
    
    $args = array(
        'post_type' => sanitize_text_field($atts['post_type']),
        'posts_per_page' => intval($atts['posts_per_page']),
        'orderby' => sanitize_text_field($atts['orderby']),
        'order' => sanitize_text_field($atts['order']),
        'post_status' => 'publish'
    );
    
    $slides = new WP_Query($args);
    
    if (!$slides->have_posts()) {
        return '<div class="acf-post-slider-error"><p>No slides found. Please check your post type and ACF fields.</p></div>';
    }
    
    // Check if we're on English version
    $is_english = acf_slider_is_english();
    
    $extra_class = !empty($atts['class']) ? ' ' . sanitize_html_class($atts['class']) : '';
    
    ob_start();
    ?>
    <div class="acf-post-slider<?php echo esc_attr($extra_class); ?>">
        <div class="acf-slider-container">
            <div class="acf-slider-track">
                <?php 
                $slide_count = 0;
                while ($slides->have_posts()) : $slides->the_post(); 
                    
                    // Get image based on language
                    if ($is_english) {
                        // Try English image first, fallback to default
                        $image_url = get_field('slides_image_eng');
                        if (!$image_url) {
                            $image_url = get_field('slides_image');
                        }
                    } else {
                        // Default language image
                        $image_url = get_field('slides_image');
                    }
                    
                    $click_url = get_field('slides_url');
                    $title = get_the_title();
                    
                    if (!$image_url) continue;
                    $slide_count++;
                ?>
                <div class="acf-slide">
                    <?php if ($click_url) : ?>
                        <a href="<?php echo esc_url($click_url); ?>" title="<?php echo esc_attr($title); ?>" rel="noopener">
                            <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($title); ?>" loading="lazy">
                        </a>
                    <?php else : ?>
                        <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($title); ?>" loading="lazy">
                    <?php endif; ?>
                </div>
                <?php endwhile; ?>
            </div>
            
            <?php if ($slide_count > 1) : ?>
            <div class="acf-slider-controls">
                <div class="acf-slider-arrow acf-slider-prev">‹</div>
                <div class="acf-slider-dots">
                    <?php for ($i = 0; $i < $slide_count; $i++) : ?>
                        <div class="acf-slider-dot <?php echo $i === 0 ? 'active' : ''; ?>"></div>
                    <?php endfor; ?>
                </div>
                <div class="acf-slider-arrow acf-slider-next">›</div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php
    
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('acf_post_slider', 'acf_post_slider_shortcode');

// Optional: Add Elementor widget support with better WoodMart compatibility
function acf_post_slider_register_elementor_widget() {
    // Check if Elementor is active and loaded
    if (!did_action('elementor/loaded')) {
        return;
    }
    
    // Check if Widget_Base class exists
    if (!class_exists('\Elementor\Widget_Base')) {
        return;
    }
    
    class ACF_Post_Slider_Widget extends \Elementor\Widget_Base {
        
        public function get_name() {
            return 'acf_post_slider';
        }
        
        public function get_title() {
            return 'ACF Post Slider';
        }
        
        public function get_icon() {
            return 'eicon-slider-push';
        }
        
        public function get_categories() {
            return ['general'];
        }
        
        public function get_keywords() {
            return ['slider', 'acf', 'post', 'carousel', 'woodmart'];
        }
        
        protected function _register_controls() {
            $this->start_controls_section(
                'content_section',
                [
                    'label' => 'Slider Settings',
                    'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
                ]
            );
            
            $this->add_control(
                'post_type',
                [
                    'label' => 'Post Type',
                    'type' => \Elementor\Controls_Manager::TEXT,
                    'default' => 'slide',
                    'description' => 'Enter the post type slug for your slides',
                ]
            );
            
            $this->add_control(
                'posts_per_page',
                [
                    'label' => 'Number of Slides',
                    'type' => \Elementor\Controls_Manager::NUMBER,
                    'default' => -1,
                    'min' => -1,
                    'description' => 'Number of slides to show (-1 for all)',
                ]
            );
            
            $this->add_control(
                'orderby',
                [
                    'label' => 'Order By',
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'menu_order',
                    'options' => [
                        'menu_order' => 'Menu Order',
                        'date' => 'Date',
                        'title' => 'Title',
                        'rand' => 'Random',
                    ],
                ]
            );
            
            $this->add_control(
                'order',
                [
                    'label' => 'Order',
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'ASC',
                    'options' => [
                        'ASC' => 'Ascending',
                        'DESC' => 'Descending',
                    ],
                ]
            );
            
            $this->end_controls_section();
        }
        
        protected function render() {
            $settings = $this->get_settings_for_display();
            
            $shortcode = '[acf_post_slider';
            $shortcode .= ' post_type="' . esc_attr($settings['post_type']) . '"';
            $shortcode .= ' posts_per_page="' . esc_attr($settings['posts_per_page']) . '"';
            $shortcode .= ' orderby="' . esc_attr($settings['orderby']) . '"';
            $shortcode .= ' order="' . esc_attr($settings['order']) . '"';
            $shortcode .= ']';
            
            echo do_shortcode($shortcode);
        }
    }
    
    // Register the widget
    add_action('elementor/widgets/widgets_registered', function() {
        if (class_exists('ACF_Post_Slider_Widget')) {
            \Elementor\Plugin::instance()->widgets_manager->register_widget_type(new ACF_Post_Slider_Widget());
        }
    });
}

// Initialize Elementor widget after Elementor is loaded
add_action('elementor/loaded', 'acf_post_slider_register_elementor_widget');

// Add admin notice for setup instructions
function acf_post_slider_admin_notice() {
    if (current_user_can('manage_options')) {
        $screen = get_current_screen();
        if ($screen && $screen->id === 'themes') {
            ?>
            <div class="notice notice-info">
                <p><strong>ACF Post Slider:</strong> Don't forget to create your "slide" post type and ACF fields: "slides_image" (Image), "slides_image_eng" (Image for English), and "slides_url" (URL). Use shortcode: <code>[acf_post_slider]</code></p>
            </div>
            <?php
        }
    }
}
add_action('admin_notices', 'acf_post_slider_admin_notice');






/**
 * Product Specifications Widget Shortcode + Elementor Widget
 * Usage: [product_specifications]
 */

if (!function_exists('enqueue_product_specs_assets')) {
    function enqueue_product_specs_assets() {
        // Google font
        wp_enqueue_style(
            'noto-sans-georgian',
            'https://fonts.googleapis.com/css2?family=Noto+Sans+Georgian:wght@300;400;500;700&display=swap',
            array(),
            '1.0.0'
        );

        // CSS
        wp_add_inline_style('noto-sans-georgian', get_product_specs_css());

        // Make sure jQuery is present, then add inline JS
        wp_enqueue_script('jquery');
        wp_add_inline_script('jquery', get_product_specs_js());
    }
    add_action('wp_enqueue_scripts', 'enqueue_product_specs_assets');
}

if (!function_exists('get_product_specs_css')) {
    function get_product_specs_css() {
        return '
        .product-specs-widget {
            font-family: "Noto Sans Georgian", sans-serif;
            background: #F5F7F8;
            overflow: hidden;
            margin: 20px 0;
        }

        .specs-group { margin-bottom: 20px; }
        .specs-group:last-child { margin-bottom: 0; }

        .specs-group-title {
            font-family: "Noto Sans Georgian", sans-serif;
            font-size: 15px;
            font-weight: 800;
            color: #333;
            padding: 0;
            margin: 0 0 16px 0;
        }

        .specs-content {
            position: relative;
            overflow: hidden;
            max-height: 450px;
            transition: max-height 0.6s cubic-bezier(0.4,0,0.2,1);
            will-change: max-height;
        }
        .specs-content.expanded { max-height: 2000px; }

        .specs-list {
            padding: 0;
            margin: 0 0 20px 0;
            list-style: none;
        }
        .specs-list:last-child { margin-bottom: 0; }

        .spec-item {
            display: flex;
            justify-content: left;
            align-items: center;
            height: 42px;
            padding: 0 0 10px 0;
            border-bottom: 1px solid #D2D2D2;
        }
        .spec-item:last-child { border-bottom: none; }

        .spec-name,
        .spec-value {
            font-family: "Noto Sans Georgian", sans-serif;
            font-size: 14px;
            color: #333;
        }
        .spec-name {
            width: 50%;
            font-weight: 500;
            flex: 1;
        }
        .spec-value {
            width: 50%;
            font-weight: 600;
            text-align: left;
            flex-shrink: 0;
            margin-left: 20px;
        }

        .fade-overlay {
            position: absolute;
            bottom: 0; left: 0; right: 0;
            height: 70px;
            background: linear-gradient(transparent, #F5F7F809 50%, #F5F7F810);
            pointer-events: none;
            opacity: 1;
            transition: opacity 0.6s ease;
        }
        .specs-content.expanded .fade-overlay { opacity: 0; }

        .expand-toggle {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 16px 0;
            background: transparent;
            border: solid 1px #273A60;
            width: 100%;
            cursor: pointer;
            font-family: "Noto Sans Georgian", sans-serif;
            font-size: 14px;
            font-weight: 500;
            color: #333;
            transition: all 0.3s ease;
            margin-top: 0;
        }
        .expand-toggle:hover { color: #007cba; }
        .expand-toggle:focus { outline: none; }

        .toggle-text { margin-right: 8px; transition: color 0.3s ease; }

        .toggle-arrow {
            width: 0; height: 0;
            border-left: 5px solid transparent;
            border-right: 5px solid transparent;
            border-top: 6px solid #007cba;
            transition: all 0.4s cubic-bezier(0.4,0,0.2,1);
            transform-origin: center;
        }
        .expand-toggle.expanded .toggle-arrow { transform: rotate(180deg); }

        .product-specs-widget.loading { opacity: 0.7; pointer-events: none; }

        /* Hide specs container when empty */
        .specs_container.empty-specs {
            display: none !important;
        }

        /* Hide expand button when not needed */
        .expand-toggle.hidden {
            display: none !important;
        }

        @media (max-width: 768px) {
            .spec-item {
                flex-direction: column;
                align-items: flex-start;
                height: auto;
                padding: 12px 0;
            }
            .spec-name, .spec-value { width: 100%; }
            .spec-value { margin-left: 0; margin-top: 4px; text-align: left; }
            .specs-group-title { font-size: 15px; }
        }';
    }
}

if (!function_exists('get_product_specs_js')) {
    function get_product_specs_js() {
        return '
        jQuery(document).ready(function($) {
            $(document).on("click", ".product-specs-widget .expand-toggle", function(e) {
                e.preventDefault();
                var $button = $(this);
                var $widget = $button.closest(".product-specs-widget");
                var $content = $widget.find(".specs-content");
                var $text = $button.find(".toggle-text");

                if ($content.hasClass("expanded")) {
                    $content.removeClass("expanded");
                    $text.text("დეტალურად ჩამოშლა");
                    $button.removeClass("expanded");
                } else {
                    $content.addClass("expanded");
                    $text.text("აკეცვა");
                    $button.addClass("expanded");
                }
            });

            // Check if expand button is needed after content loads
            function checkExpandButton() {
                $(".product-specs-widget").each(function() {
                    var $widget = $(this);
                    var $content = $widget.find(".specs-content");
                    var $button = $widget.find(".expand-toggle");
                    var $fadeOverlay = $widget.find(".fade-overlay");

                    // Get actual content height
                    var actualHeight = $content.prop("scrollHeight");
                    var maxHeight = 450; // matches CSS max-height

                    if (actualHeight <= maxHeight) {
                        $button.addClass("hidden");
                        $fadeOverlay.hide();
                        $content.css("max-height", "none");
                    } else {
                        $button.removeClass("hidden");
                        $fadeOverlay.show();
                    }
                });
            }

            // Run check on load and after any dynamic content changes
            checkExpandButton();
            
            // Also check after images load (in case they affect height)
            $(window).on("load", checkExpandButton);
        });';
    }
}

if (!function_exists('product_specifications_shortcode')) {
    function product_specifications_shortcode($atts) {
        // Get current product
        $product = wc_get_product();
        if (!$product) {
            global $post;
            if ($post && $post->post_type === 'product') {
                $product = wc_get_product($post->ID);
            }
        }
        if (!$product) {
            return '<p>Product not found.</p>';
        }

        $product_id = $product->get_id();

        // Safely fetch ACF fields (if ACF exists). Support both spellings.
        $groups = array();
        if (function_exists('get_field')) {
            $groups = get_field('specifications_group', $product_id);
            if (empty($groups)) {
                $groups = get_field('speacifications_group', $product_id); // fallback to misspelled key
            }
        }

        // Check if groups are empty or invalid
        $has_valid_specs = false;
        if (!empty($groups) && is_array($groups)) {
            foreach ($groups as $group) {
                $group_title = isset($group['specification_group_title']) ? $group['specification_group_title'] : '';
                
                // Check inner list (both spellings)
                $spec_list = array();
                if (!empty($group['specifications']) && is_array($group['specifications'])) {
                    $spec_list = $group['specifications'];
                } elseif (!empty($group['speacifications']) && is_array($group['speacifications'])) {
                    $spec_list = $group['speacifications'];
                }
                
                if (!empty($group_title) && !empty($spec_list)) {
                    // Check if at least one spec has both name and value
                    foreach ($spec_list as $spec) {
                        $spec_name  = isset($spec['specification']) ? trim($spec['specification']) : '';
                        $spec_value = isset($spec['value']) ? trim($spec['value']) : '';
                        if ($spec_name !== '' && $spec_value !== '') {
                            $has_valid_specs = true;
                            break 2; // break out of both loops
                        }
                    }
                }
            }
        }

        // If no valid specs, add class to hide container and return empty
        if (!$has_valid_specs) {
            // Add JavaScript to hide the specs_container
            add_action('wp_footer', function() {
                echo '<script>
                jQuery(document).ready(function($) {
                    $(".specs_container").addClass("empty-specs");
                });
                </script>';
            });
            return '';
        }

        ob_start(); ?>
        <div class="product-specs-widget">
            <div class="specs-content">
                <?php foreach ($groups as $group):
                    $group_title = isset($group['specification_group_title']) ? $group['specification_group_title'] : '';
                    // inner list can be spelled both ways
                    $spec_list = array();
                    if (!empty($group['specifications']) && is_array($group['specifications'])) {
                        $spec_list = $group['specifications'];
                    } elseif (!empty($group['speacifications']) && is_array($group['speacifications'])) {
                        $spec_list = $group['speacifications'];
                    }
                    if (empty($group_title) || empty($spec_list)) continue; ?>
                    <div class="specs-group">
                        <h3 class="specs-group-title"><?php echo esc_html($group_title); ?></h3>
                        <ul class="specs-list">
                            <?php foreach ($spec_list as $spec):
                                $spec_name  = isset($spec['specification']) ? $spec['specification'] : '';
                                $spec_value = isset($spec['value']) ? $spec['value'] : '';
                                if ($spec_name === '' || $spec_value === '') continue; ?>
                                <li class="spec-item">
                                    <span class="spec-name"><?php echo esc_html($spec_name); ?></span>
                                    <span class="spec-value"><?php echo esc_html($spec_value); ?></span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endforeach; ?>
                <div class="fade-overlay"></div>
            </div>
            <button class="expand-toggle" type="button">
                <span class="toggle-text">დეტალურად ჩამოშლა</span>
                <span class="toggle-arrow"></span>
            </button>
        </div>
        <?php
        return ob_get_clean();
    }
    add_shortcode('product_specifications', 'product_specifications_shortcode');
}

/** Elementor Widget (modern API) */
add_action('elementor/widgets/register', function($widgets_manager) {
    if (!class_exists('\Elementor\Widget_Base')) return;

    class Product_Specs_Elementor_Widget extends \Elementor\Widget_Base {
        public function get_name() { return 'product_specifications'; }
        public function get_title() { return __('Product Specifications', 'your-textdomain'); }
        public function get_icon() { return 'eicon-table-of-contents'; }
        public function get_categories() { return ['general']; } // safer category

        protected function register_controls() {
            $this->start_controls_section(
                'content_section',
                [
                    'label' => __('Content', 'your-textdomain'),
                    'tab'   => \Elementor\Controls_Manager::TAB_CONTENT,
                ]
            );

            $this->add_control(
                'info',
                [
                    'label' => __('Info', 'your-textdomain'),
                    'type'  => \Elementor\Controls_Manager::RAW_HTML,
                    'raw'   => __('This widget displays product specifications from ACF fields. Accepted keys: specifications_group OR speacifications_group; inner list: specifications OR speacifications.', 'your-textdomain'),
                ]
            );

            $this->end_controls_section();
        }

        protected function render() {
            echo do_shortcode('[product_specifications]');
        }
    }

    // Register widget with modern method
    $widgets_manager->register(new Product_Specs_Elementor_Widget());
});









/**
 * Safe execution wrapper - only runs once and includes additional safety checks
 */
function run_bulk_delete_products_safely() {
    // Safety check: Only run if we're in wp-admin or CLI
    if (!is_admin() && !defined('WP_CLI')) {
        error_log("Bulk delete attempted from non-admin context - blocked for safety");
        return;
    }
    
    // Safety check: Only run for administrators
    if (!current_user_can('manage_woocommerce')) {
        error_log("Bulk delete attempted by non-administrator - blocked for safety");
        return;
    }
    
    // Check if WooCommerce is active
    if (!class_exists('WooCommerce')) {
        error_log("WooCommerce not active - bulk delete cancelled");
        return;
    }
    
    // One-time execution check using transient
    $executed_key = 'bulk_delete_products_executed';
    if (get_transient($executed_key)) {
        error_log("Bulk delete already executed - skipping to prevent accidental re-runs");
        return;
    }
    
    // Set transient to prevent re-execution (expires in 1 hour)
    set_transient($executed_key, true, HOUR_IN_SECONDS);
    
    // Run the actual deletion
    bulk_delete_products();
}

// EXECUTION METHODS - Choose one:

// Method 1: Hook to init (most common)
// Uncomment this line to run once, then comment/remove after execution
// add_action('init', 'run_bulk_delete_products_safely');

// Method 2: Direct execution (for testing or immediate run)
// Uncomment this line to run immediately
// run_bulk_delete_products_safely();

// Method 3: WP-CLI command (if you prefer command line)
// Run with: wp eval-file this-file.php
// Or add to functions.php and run: wp eval "run_bulk_delete_products_safely();"

/**
 * USAGE INSTRUCTIONS:
 * 
 * 1. BACKUP YOUR DATABASE FIRST!
 * 
 * 2. Choose one execution method above and uncomment it
 * 
 * 3. If using Method 1 (init hook):
 *    - Add this code to your theme's functions.php or a custom plugin
 *    - Visit any page on your site (logged in as admin)
 *    - Check error logs for results
 *    - Comment out or remove the add_action line after execution
 * 
 * 4. If using Method 2 (direct execution):
 *    - Save this as a separate PHP file
 *    - Include WordPress: require_once 'wp-load.php';
 *    - Run the file via browser or command line
 * 
 * 5. Check your error logs (usually in /wp-content/debug.log) for detailed results
 * 
 * 6. Verify deletion by checking your products in WooCommerce admin
 */


// Only force TranslatePress search for WoodMart AJAX search, not menus
add_filter('trp_force_search', 'conditional_trp_force_search');

function conditional_trp_force_search($force) {
    // Only force search on WoodMart AJAX search requests
    if (wp_doing_ajax()) {
        $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
        if (in_array($action, ['woodmart_ajax_search', 'woodmart_get_product_suggestions'])) {
            return true;
        }
    }
    return $force; // Return original value for everything else (menus, etc.)
}
?>