<?php

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class storylmajaxes
{
    public function __construct()
    {
        add_action('wp_ajax_story_shop_search_products', [$this, 'story_shop_search_products']);
        add_action('wp_ajax_nopriv_story_shop_search_products', [$this, 'story_shop_search_products']);
        // AJAX handler for toggling likes
        add_action('wp_ajax_story_shop_toggle_like', [$this, 'story_shop_toggle_like']);
        add_action('wp_ajax_nopriv_story_shop_toggle_like', [$this, 'story_shop_toggle_like']);
        // AJAX handler for loading comments
        add_action('wp_ajax_story_shop_load_comments', [$this, 'story_shop_load_comments']);
        add_action('wp_ajax_nopriv_story_shop_load_comments', [$this, 'story_shop_load_comments']);

        // AJAX handler for posting comments
        add_action('wp_ajax_story_shop_post_comment', [$this, 'story_shop_post_comment']);
        add_action('wp_ajax_nopriv_story_shop_post_comment', [$this, 'story_shop_post_comment']);
        // AJAX handler for loading product details
        add_action('wp_ajax_story_shop_load_product', [$this, 'story_shop_load_product']);
        add_action('wp_ajax_nopriv_story_shop_load_product', [$this, 'story_shop_load_product']);
        // AJAX handler for loading individual story content
        add_action('wp_ajax_story_shop_load_story', [$this, 'story_shop_load_story']);
        add_action('wp_ajax_nopriv_story_shop_load_story', [$this, 'story_shop_load_story']);
        // AJAX handler for loading all stories in swiper
        add_action('wp_ajax_story_shop_load_all_stories', [$this, 'story_shop_load_all_stories']);
        add_action('wp_ajax_nopriv_story_shop_load_all_stories', [$this, 'story_shop_load_all_stories']);
    }


    // AJAX handlers (same as original but adapted for Carbon Fields data structure)
    public function story_shop_search_products()
    {
        check_ajax_referer('story_shop_nonce', 'nonce');

        $search_term = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';

        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 20,
            's' => $search_term,
            'orderby' => 'title',
            'order' => 'ASC',
        );

        $query = new WP_Query($args);
        $products = array();

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $product = wc_get_product(get_the_ID());
                if ($product) {
                    $products[] = array(
                        'id' => get_the_ID(),
                        'title' => get_the_title(),
                        'price' => $product->get_price_html(),
                        'image' => wp_get_attachment_image_url($product->get_image_id(), 'thumbnail'),
                    );
                }
            }
            wp_reset_postdata();
        }

        wp_send_json_success($products);
    }


    public function story_shop_toggle_like()
    {
        check_ajax_referer('story_shop_nonce', 'nonce');

        $story_id = isset($_POST['story_id']) ? intval($_POST['story_id']) : -1;

        if ($story_id < 0) {
            wp_send_json_error(__('Invalid story ID', 'kavehTheme'));
        }

        // Verify the post exists and is a story_shop post type
        $post = get_post($story_id);
        if (!$post || $post->post_type !== 'story_shop') {
            wp_send_json_error(__('Invalid story', 'kavehTheme'));
        }

        if (is_user_logged_in()) {
            $user_id = get_current_user_id();

            // Check if user already liked this story using user meta
            $liked_stories = get_user_meta($user_id, '_liked_stories', true);
            if (!is_array($liked_stories)) {
                $liked_stories = array();
            }

            $user_liked = in_array($story_id, $liked_stories);

            if ($user_liked) {
                // Unlike - remove from user meta
                $liked_stories = array_diff($liked_stories, array($story_id));
                update_user_meta($user_id, '_liked_stories', $liked_stories);

                // Decrease like count in post meta
                $current_count = get_post_meta($story_id, '_like_count', true);
                $new_count = max(0, intval($current_count) - 1);
                update_post_meta($story_id, '_like_count', $new_count);

                $liked = false;
            } else {
                // Like - add to user meta
                $liked_stories[] = $story_id;
                update_user_meta($user_id, '_liked_stories', $liked_stories);

                // Increase like count in post meta
                $current_count = get_post_meta($story_id, '_like_count', true);
                $new_count = intval($current_count) + 1;
                update_post_meta($story_id, '_like_count', $new_count);

                $liked = true;
            }
        } else {
            // For non-logged users, use IP-based tracking in post meta
            $user_ip = $_SERVER['REMOTE_ADDR'];
            $liked_ips = get_post_meta($story_id, '_liked_ips', true);
            if (!is_array($liked_ips)) {
                $liked_ips = array();
            }

            $ip_liked = in_array($user_ip, $liked_ips);

            if ($ip_liked) {
                // Unlike - remove IP
                $liked_ips = array_diff($liked_ips, array($user_ip));
                update_post_meta($story_id, '_liked_ips', $liked_ips);

                // Decrease like count
                $current_count = get_post_meta($story_id, '_like_count', true);
                $new_count = max(0, intval($current_count) - 1);
                update_post_meta($story_id, '_like_count', $new_count);

                $liked = false;
            } else {
                // Like - add IP
                $liked_ips[] = $user_ip;
                update_post_meta($story_id, '_liked_ips', $liked_ips);

                // Increase like count
                $current_count = get_post_meta($story_id, '_like_count', true);
                $new_count = intval($current_count) + 1;
                update_post_meta($story_id, '_like_count', $new_count);

                $liked = true;
            }
        }

        // Get updated like count
        $like_count = get_post_meta($story_id, '_like_count', true);

        wp_send_json_success(array(
            'liked' => $liked,
            'count' => intval($like_count),
            'message' => $liked ? __('Story liked', 'kavehTheme') : __('Story unliked', 'kavehTheme')
        ));
    }


    public function story_shop_load_comments()
    {
        check_ajax_referer('story_shop_nonce', 'nonce');

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

        // Verify the post exists and is a story_shop post type
        $post = get_post($story_id);
        if (!$post || $post->post_type !== 'story_shop') {
            wp_send_json_error(__('Invalid story', 'kavehTheme'));
        }

        // Get WordPress comments for this post
        $comments = get_comments(array(
            'post_id' => $story_id,
            'status' => 'approve',
            'parent' => 0,
            'order' => 'DESC'
        ));

        ob_start();

        if (!empty($comments)) {
            foreach ($comments as $comment) {
                $this->story_shop_render_comment($comment, $story_id);
            }
        }

        $html = ob_get_clean();

        wp_send_json_success(array(
            'html' => $html,
            'count' => count($comments)
        ));
    }


    // Render single comment
    public function story_shop_render_comment($comment, $story_id)
    {
        // Get replies using WordPress comments
        $replies = get_comments(array(
            'post_id' => $story_id,
            'status' => 'approve',
            'parent' => $comment->comment_ID,
            'order' => 'ASC'
        ));
?>
        <li class="comments-story__item">
            <div class="content p-2">
                <div class="text fs-12 line-height-26 fw-normal text-dark"><?php echo esc_html($comment->comment_content); ?></div>
                <div class="info d-flex align-items-center gap-2 py-1">
                    <a href="#" class="info-user d-flex align-items-center gap-2 text-truncate">
                        <?php echo get_avatar($comment->comment_author_email, 20, '', '', array('class' => 'rounded-circle flex-fill-2')); ?>
                        <span class="name fs-11 fw-normal text-gray-9 text-truncate dir-ltr"><?php echo esc_html($comment->comment_author); ?></span>
                    </a>
                    <span class="rounded-circle flex-fill-2"></span>
                    <div class="date fs-11 fw-normal text-gray-9 ms-1 flex-fill-2">
                        <?php echo sprintf(__('%s ago', 'kavehTheme'), human_time_diff(strtotime($comment->comment_date), current_time('timestamp'))); ?>
                    </div>
                </div>
            </div>

            <?php if (!empty($replies)): ?>
                <ul class="replys">
                    <?php foreach ($replies as $reply): ?>
                        <li class="reply">
                            <div class="content p-2">
                                <div class="text fs-12 line-height-26 fw-normal text-dark">
                                    @<?php echo esc_html($comment->comment_author); ?> <?php echo esc_html($reply->comment_content); ?>
                                </div>
                                <div class="info d-flex align-items-center gap-2 py-1">
                                    <a href="#" class="info-user d-flex align-items-center gap-2 text-truncate">
                                        <?php echo get_avatar($reply->comment_author_email, 20, '', '', array('class' => 'rounded-circle flex-fill-2')); ?>
                                        <span class="name fs-11 fw-normal text-gray-9 text-truncate dir-ltr"><?php echo esc_html($reply->comment_author); ?></span>
                                    </a>
                                    <span class="rounded-circle flex-fill-2"></span>
                                    <div class="date fs-11 fw-normal text-gray-9 ms-1 flex-fill-2">
                                        <?php echo sprintf(__('%s ago', 'kavehTheme'), human_time_diff(strtotime($reply->comment_date), current_time('timestamp'))); ?>
                                    </div>
                                </div>
                            </div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </li>
    <?php
    }




    public function story_shop_post_comment()
    {
        check_ajax_referer('story_shop_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(__('Please login to comment', 'kavehTheme'));
        }

        $story_id = isset($_POST['story_id']) ? intval($_POST['story_id']) : 0;
        $comment_content = isset($_POST['comment']) ? sanitize_text_field($_POST['comment']) : '';
        $parent_id = isset($_POST['parent_id']) ? intval($_POST['parent_id']) : 0;

        if (empty($comment_content)) {
            wp_send_json_error(__('Comment cannot be empty', 'kavehTheme'));
        }

        // Verify the post exists and is a story_shop post type
        $post = get_post($story_id);
        if (!$post || $post->post_type !== 'story_shop') {
            wp_send_json_error(__('Invalid story', 'kavehTheme'));
        }

        $user = wp_get_current_user();

        // Prepare comment data for WordPress
        $comment_data = array(
            'comment_post_ID' => $story_id,
            'comment_author' => $user->display_name,
            'comment_author_email' => $user->user_email,
            'comment_author_url' => $user->user_url,
            'comment_content' => $comment_content,
            'comment_type' => '',
            'comment_parent' => $parent_id,
            'user_id' => get_current_user_id(),
            'comment_approved' => 1, // Auto-approve comments
        );

        // Insert comment using WordPress function
        $comment_id = wp_insert_comment($comment_data);

        if ($comment_id) {
            wp_send_json_success(array(
                'message' => __('Comment posted successfully', 'kavehTheme'),
                'comment_id' => $comment_id
            ));
        } else {
            wp_send_json_error(__('Failed to post comment', 'kavehTheme'));
        }
    }


    public function story_shop_load_product()
    {
        check_ajax_referer('story_shop_nonce', 'nonce');

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

        if (!$product_id) {
            wp_send_json_error(__('Invalid product ID', 'kavehTheme'));
        }

        // Check if WooCommerce is active
        if (!function_exists('wc_get_product')) {
            wp_send_json_error(__('WooCommerce is not active', 'kavehTheme'));
        }

        $product = wc_get_product($product_id);

        if (!$product || !is_object($product)) {
            wp_send_json_error(__('Product not found', 'kavehTheme'));
        }

        try {
            ob_start();
        ?>
            <div class="product-story scrollbar">
                <?php echo $product->get_image('medium', array('class' => 'd-block mx-auto mb-12')); ?>
                <div class="title rounded-6 fs-16 line-height-24 fw-bold text-truncate text-dark-15 mb-3">
                    <?php echo esc_html($product->get_name()); ?>
                </div>
                <div class="rate gap-1 d-flex align-items-center gap-1 text-dark fs-12 line-height-18 fw-normal">
                    <i class="icon-star-5 fs-12 lh-1 text-warning-8"></i>
                    <?php echo esc_html($product->get_average_rating()); ?>
                    <span class="rate__buy fs-11"><?php printf(__('(%s buyer ratings)', 'kavehTheme'), esc_html($product->get_review_count())); ?></span>
                    <span class="dot rounded-circle mr-6"></span>
                </div>

            <?php
            // Display product variations or attributes
            $attributes = $product->get_attributes();
            if (!empty($attributes)):
                foreach ($attributes as $attribute):
                    if ($attribute->is_taxonomy()):
                        $terms = wp_get_post_terms($product->get_id(), $attribute->get_name());
                        if (!empty($terms)):
            ?>
                            <div class="color mt-17 mb-12">
                                <div class="text fs-16 line-height-24 fw-bold text-dark-15 mb-17">
                                    <?php echo esc_html(wc_attribute_label($attribute->get_name())) . ': ' . esc_html($terms[0]->name); ?>
                                </div>
                            </div>
            <?php
                        endif;
                    endif;
                endforeach;
            endif;
            ?>

            <a href="<?php echo get_permalink($product_id); ?>"
                class="btn btn-outline-danger-7 text-center d-block w-100 fs-12 line-height-18 fw-bold rounded-8">
                <?php _e('View full product details', 'kavehTheme'); ?>
            </a>
        </div>
        <div class="bottom d-flex align-items-center justify-content-between gap-3">
            <a href="<?php echo esc_url($product->add_to_cart_url()); ?>"
                class="btn btn-danger-7 rounded-8 fs-12 line-height-18 fw-bold ajax_add_to_cart add_to_cart_button"
                data-product_id="<?php echo $product_id; ?>">
                <?php _e('Add to cart', 'kavehTheme'); ?>
            </a>
            <div>
                <?php if ($product->is_on_sale()): 
                    $regular_price = $product->get_regular_price();
                    $sale_price = $product->get_sale_price();
                    if ($regular_price && $sale_price && $regular_price > 0): ?>
                    <div class="off d-flex align-items-center justify-content-end gap-2">
                        <del class="fs-12 line-height-26 fw-normal"><?php echo wc_price($regular_price); ?></del>
                        <span class="rounded-pill text-white fs-12 line-height-18 d-flex align-items-center justify-content-center">
                            <?php echo round((($regular_price - $sale_price) / $regular_price) * 100); ?>%
                        </span>
                    </div>
                <?php endif; endif; ?>
                <div class="price fs-19 line-height-24 fw-bold d-flex align-items-center justify-content-end gap-1">
                    <?php echo wc_price($product->get_price()); ?>
                </div>
            </div>
        </div>
<?php
            $html = ob_get_clean();

            wp_send_json_success(array('html' => $html));
        } catch (Exception $e) {
            ob_end_clean(); // Clean any output buffer
            wp_send_json_error(__('Error loading product: ', 'kavehTheme') . $e->getMessage());
        }
    }

    // AJAX handler for loading individual story content
    public function story_shop_load_story()
    {
        check_ajax_referer('story_shop_nonce', 'nonce');

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

        if (!$story_id) {
            wp_send_json_error(__('Invalid story ID', 'kavehTheme'));
        }

        try {
            ob_start();

            // Get story data
            $story = get_post($story_id);
            if (!$story || $story->post_type !== 'story_shop') {
                wp_send_json_error(__('Story not found', 'kavehTheme'));
            }

            // Get story meta data
            $story_data = array(
                'ID' => $story->ID,
                'title' => $story->post_title,
                'content' => $story->post_content,
                'attached_products' => get_post_meta($story_id, '_attached_products', true) ?: array(),
                'enable_products' => get_post_meta($story_id, '_enable_products', true),
                'enable_comments' => get_post_meta($story_id, '_enable_comments', true)
            );

            // Include the views class to access helper methods
            $views = new storylmviews();
            $like_data = $views->story_shop_get_like_data($story_id);

            // Get the main media URL with proper fallback logic
            $main_media_url = '';
            $is_video = false;
            $mime_type = '';
            
            // Get media type and corresponding media
            $media_type = get_post_meta($story_id, '_media_type', true) ?: 'image';
            
            if ($media_type === 'video') {
                $story_video_id = get_post_meta($story_id, '_story_video', true);
                if (!empty($story_video_id)) {
                    $main_media_url = wp_get_attachment_url($story_video_id);
                    $mime_type = get_post_mime_type($story_video_id);
                    $is_video = true;
                }
            } else {
                $story_image_id = get_post_meta($story_id, '_story_image', true);
                if (!empty($story_image_id)) {
                    $main_media_url = wp_get_attachment_url($story_image_id);
                    $is_video = false;
                }
            }
            
            // Fallback to WordPress featured image
            if (empty($main_media_url)) {
                $main_media_url = get_the_post_thumbnail_url($story_id, 'full');
                $is_video = false; // Featured images are always images
            }
            
            // Final fallback to placeholder
            if (empty($main_media_url)) {
                $main_media_url = KSTORY_URL . 'assets/images/placeholder-story.jpg';
                $is_video = false;
            }

            // Generate the story slide HTML
?>
            <div class="story-shop__story position-relative h-100">
                <div class="heading d-flex align-items-center position-absolute top-0 end-0 w-100">
                    <button type="button" class="modal-close text-white fs-24 lh-1"
                        data-bs-dismiss="modal">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                            <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" />
                        </svg>
                    </button>
                </div>
                <div class="video position-relative h-100">
                    <?php if ($is_video): ?>
                        <video src="<?php echo esc_url($main_media_url); ?>" 
                               class="d-block w-100 h-100" 
                               style="object-fit: cover;" 
                               controls 
                               autoplay 
                               muted 
                               loop>
                            <source src="<?php echo esc_url($main_media_url); ?>" type="<?php echo esc_attr($mime_type); ?>">
                            Your browser does not support the video tag.
                        </video>
                    <?php else: ?>
                        <img src="<?php echo esc_url($main_media_url); ?>"
                            alt="<?php echo esc_attr($story_data['title']); ?>" class="d-block w-100 h-100"
                            style="object-fit: cover;" />
                    <?php endif; ?>

                    <div class="content__text position-absolute">
                        <div class="title fs-16 line-height-25 text-white">
                            <?php echo esc_html($story_data['title']); ?>
                        </div>
                        <div class="description fs-14 fw-normal line-height-30 text-white overflow-hidden mt-2">
                            <?php echo wp_kses_post($story_data['content']); ?>
                        </div>
                    </div>

                    <ul class="icons d-flex flex-column gap-3 position-absolute">
                        <li class="story-like d-flex align-items-center justify-content-center flex-column cursor-pointer fs-14 line-height-30 fw-bold text-white <?php echo $like_data['user_liked'] ? 'liked' : ''; ?>" data-story-id="<?php echo $story_id; ?>">
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                                <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                            </svg>
                            <span class="like-count"><?php echo $like_data['count']; ?></span>
                        </li>
                        <?php if (isset($story_data['enable_comments']) && $story_data['enable_comments']):
                            $comment_count = get_comments_number($story_id);
                        ?>
                            <li class="btn-comments-story d-flex align-items-center justify-content-center flex-column cursor-pointer fs-14 line-height-30 fw-bold text-white"
                                data-story-id="<?php echo $story_id; ?>">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                                    <path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z" />
                                </svg>
                                <span class="comment-count"><?php echo $comment_count; ?></span>
                            </li>
                        <?php endif; ?>
                    </ul>
                </div>

                <?php 
                // Ensure attached_products is an array
                $attached_products = $story_data['attached_products'];
                if (!is_array($attached_products)) {
                    $attached_products = !empty($attached_products) ? array($attached_products) : array();
                }
                
                if (isset($story_data['enable_products']) && $story_data['enable_products'] && !empty($attached_products)): ?>
                    <div class="bottom">
                        <div class="story-shop__story__products products p-2 overflow-hidden">
                            <!-- Start Carousel -->
                            <div class="swiper swiper-products-story overflow-visible">
                                <div class="swiper-wrapper">
                                    <?php foreach ($attached_products as $product_id):
                                        $product = wc_get_product($product_id);
                                        if ($product):
                                        ?>
                                            <!-- Start Slide -->
                                            <div class="swiper-slide">
                                                <div class="story-shop__story__product d-flex bg-white rounded-8 align-items-center gap-2 cursor-pointer"
                                                    data-product-id="<?php echo $product_id; ?>">
                                                    <?php echo $product->get_image('thumbnail', array('width' => 60, 'height' => 60)); ?>
                                                    <div class="title fs-12 line-height-26 fw-bold text-dark-15 line-clamp-2 overflow-hidden">
                                                        <?php echo wp_trim_words( $product->get_name(), 10, '...' ); ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <!-- End Slide -->
                                    <?php endif;
                                    endforeach; ?>
                                </div>
                            </div>
                            <!-- End Carousel -->
                        </div>
                    </div>
                <?php endif; ?>
            </div>
<?php
            $html = ob_get_clean();
            wp_send_json_success(array('html' => $html));
        } catch (Exception $e) {
            ob_end_clean();
            wp_send_json_error(__('Error loading story: ', 'kavehTheme') . $e->getMessage());
        }
    }

    public function story_shop_load_all_stories()
    {
        check_ajax_referer('story_shop_nonce', 'nonce');

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

        try {
            ob_start();

            // Get all published stories
            $stories = get_posts(array(
                'post_type' => 'story_shop',
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'orderby' => 'date',
                'order' => 'DESC'
            ));

            if (empty($stories)) {
                wp_send_json_error(__('No stories found', 'kavehTheme'));
            }

            // Include the views class to access helper methods
            $views = new storylmviews();
            $current_index = 0;

            // Find the index of current story
            foreach ($stories as $index => $story) {
                if ($story->ID == $current_story_id) {
                    $current_index = $index;
                    break;
                }
            }
?>
                <?php foreach ($stories as $story_index => $story): 
                    $story_id = $story->ID;
                    
                    // Get story meta data
                    $story_data = array(
                        'ID' => $story->ID,
                        'title' => $story->post_title,
                        'content' => $story->post_content,
                        'attached_products' => get_post_meta($story_id, '_attached_products', true) ?: array(),
                        'enable_products' => get_post_meta($story_id, '_enable_products', true),
                        'enable_comments' => get_post_meta($story_id, '_enable_comments', true)
                    );

                    $like_data = $views->story_shop_get_like_data($story_id);

                    // Get the main media URL with proper fallback logic
                    $main_media_url = '';
                    $is_video = false;
                    $mime_type = '';
                    
                    // Get media type and corresponding media
                    $media_type = get_post_meta($story_id, '_media_type', true) ?: 'image';
                    
                    if ($media_type === 'video') {
                        $story_video_id = get_post_meta($story_id, '_story_video', true);
                        if (!empty($story_video_id)) {
                            $main_media_url = wp_get_attachment_url($story_video_id);
                            $mime_type = get_post_mime_type($story_video_id);
                            $is_video = true;
                        }
                    } else {
                        $story_image_id = get_post_meta($story_id, '_story_image', true);
                        if (!empty($story_image_id)) {
                            $main_media_url = wp_get_attachment_url($story_image_id);
                            $is_video = false;
                        }
                    }
                    
                    // Fallback to WordPress featured image
                    if (empty($main_media_url)) {
                        $main_media_url = get_the_post_thumbnail_url($story_id, 'full');
                        $is_video = false;
                    }
                    
                    // Final fallback to placeholder
                    if (empty($main_media_url)) {
                        $main_media_url = KSTORY_URL . 'assets/images/placeholder-story.jpg';
                        $is_video = false;
                    }
                ?>
                    <div class="swiper-slide" data-story-id="<?php echo $story_id; ?>">
                        <div class="story-shop__story position-relative h-100">
                            <div class="heading d-flex align-items-center position-absolute top-0 end-0 w-100">
                                <button type="button" class="modal-close text-white fs-24 lh-1"
                                    data-bs-dismiss="modal">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                                        <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" />
                                    </svg>
                                </button>
                            </div>
                            <div class="video position-relative h-100">
                                <?php if ($is_video): ?>
                                    <video src="<?php echo esc_url($main_media_url); ?>" 
                                           class="d-block w-100 h-100" 
                                           style="object-fit: cover;" 
                                           controls 
                                           autoplay 
                                           muted 
                                           loop>
                                        <source src="<?php echo esc_url($main_media_url); ?>" type="<?php echo esc_attr($mime_type); ?>">
                                        Your browser does not support the video tag.
                                    </video>
                                <?php else: ?>
                                    <img src="<?php echo esc_url($main_media_url); ?>"
                                        alt="<?php echo esc_attr($story_data['title']); ?>" class="d-block w-100 h-100"
                                        style="object-fit: cover;" />
                                <?php endif; ?>

                                <div class="content__text position-absolute">
                                    <div class="title fs-16 line-height-25 text-white">
                                        <?php echo esc_html($story_data['title']); ?>
                                    </div>
                                    <div class="description fs-14 fw-normal line-height-30 text-white overflow-hidden mt-2">
                                        <?php echo wp_kses_post($story_data['content']); ?>
                                    </div>
                                </div>

                                <ul class="icons d-flex flex-column gap-3 position-absolute">
                                    <li class="story-like d-flex align-items-center justify-content-center flex-column cursor-pointer fs-14 line-height-30 fw-bold text-white <?php echo $like_data['user_liked'] ? 'liked' : ''; ?>" data-story-id="<?php echo $story_id; ?>">
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                                            <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                                        </svg>
                                        <span class="like-count"><?php echo $like_data['count']; ?></span>
                                    </li>
                                    <?php if (isset($story_data['enable_comments']) && $story_data['enable_comments']):
                                        $comment_count = get_comments_number($story_id);
                                    ?>
                                        <li class="btn-comments-story d-flex align-items-center justify-content-center flex-column cursor-pointer fs-14 line-height-30 fw-bold text-white"
                                            data-story-id="<?php echo $story_id; ?>">
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                                                <path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z" />
                                            </svg>
                                            <span class="comment-count"><?php echo $comment_count; ?></span>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </div>

                            <?php 
                            // Ensure attached_products is an array
                            $attached_products = $story_data['attached_products'];
                            if (!is_array($attached_products)) {
                                $attached_products = !empty($attached_products) ? array($attached_products) : array();
                            }
                            
                            if (isset($story_data['enable_products']) && $story_data['enable_products'] && !empty($attached_products)): ?>
                                <div class="bottom">
                                    <div class="story-shop__story__products products p-2 overflow-hidden">
                                        <!-- Start Carousel -->
                                        <div class="swiper swiper-products-story overflow-visible">
                                            <div class="swiper-wrapper">
                                                <?php foreach ($attached_products as $product_id):
                                                    $product = wc_get_product($product_id);
                                                    if ($product):
                                                    ?>
                                                        <!-- Start Slide -->
                                                        <div class="swiper-slide">
                                                            <div class="story-shop__story__product d-flex bg-white rounded-8 align-items-center gap-2 cursor-pointer"
                                                                data-product-id="<?php echo $product_id; ?>">
                                                                <?php echo $product->get_image('thumbnail', array('width' => 60, 'height' => 60)); ?>
                                                                <div class="title fs-12 line-height-26 fw-bold text-dark-15 line-clamp-2 overflow-hidden">
                                                                    <?php echo wp_trim_words( $product->get_name(), 10, '...' ); ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <!-- End Slide -->
                                                <?php endif;
                                                endforeach; ?>
                                            </div>
                                        </div>
                                        <!-- End Carousel -->
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
<?php
            $html = ob_get_clean();
            wp_send_json_success(array(
                'html' => $html,
                'current_index' => $current_index,
                'total_stories' => count($stories)
            ));
        } catch (Exception $e) {
            ob_end_clean();
            wp_send_json_error(__('Error loading stories: ', 'kavehTheme') . $e->getMessage());
        }
    }
}

new storylmajaxes();
