<?php

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

class storylmviews
{
    public function __construct()
    {
        // Create shortcode to display stories
        add_shortcode('story_shop', [$this, 'story_shop_shortcode']);
    }



    // Helper function to get like data for a story
    public function story_shop_get_like_data($story_id)
    {
        // Get total likes count from post meta
        $like_count = get_post_meta($story_id, '_like_count', true);
        $like_count = $like_count ? intval($like_count) : 0;

        // Check if current user has liked this story
        $user_has_liked = false;
        if (is_user_logged_in()) {
            $user_id = get_current_user_id();
            $liked_stories = get_user_meta($user_id, '_liked_stories', true);
            $liked_stories = $liked_stories ? $liked_stories : array();
            $user_has_liked = in_array($story_id, $liked_stories);
        } else {
            // For non-logged-in users, check by IP in post meta
            $user_ip = $_SERVER['REMOTE_ADDR'];
            $liked_ips = get_post_meta($story_id, '_liked_ips', true);
            $liked_ips = $liked_ips ? $liked_ips : array();
            $user_has_liked = in_array($user_ip, $liked_ips);
        }

        return array(
            'count' => $like_count,
            'user_liked' => $user_has_liked
        );
    }

    // Function to get all published stories
    public function story_shop_get_stories()
    {
        $args = array(
            'post_type' => 'story_shop',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'date',
            'order' => 'DESC'
        );

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

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $story_id = get_the_ID();

                // Get story meta data
                $stories[] = array(
                    'ID' => $story_id,
                    'title' => get_the_title(),
                    'content' => get_the_content(),
                    'thumbnail' => $this->get_story_thumbnail_url($story_id),

                    'enable_badge' => get_post_meta($story_id, '_enable_badge', true),
                    'story_badge' => get_post_meta($story_id, '_story_badge', true),
                    'enable_comments' => get_post_meta($story_id, '_enable_comments', true),
                    'enable_products' => get_post_meta($story_id, '_enable_products', true),
                    'media_type' => get_post_meta($story_id, '_media_type', true),
                    'story_image' => get_post_meta($story_id, '_story_image', true),
                    'story_video' => get_post_meta($story_id, '_story_video', true),
                    'attached_products' => get_post_meta($story_id, '_attached_products', true),
                    // Style meta
                    'gradient_start' => get_post_meta($story_id, '_gradient_start', true) ?: '#833AB4',
                    'gradient_middle' => get_post_meta($story_id, '_gradient_middle', true) ?: '#FD1D1D',
                    'gradient_end' => get_post_meta($story_id, '_gradient_end', true) ?: '#FCB045',
                    'container_width' => get_post_meta($story_id, '_container_width', true) ?: '90',
                    'container_height' => get_post_meta($story_id, '_container_height', true) ?: '90',
                    'image_width' => get_post_meta($story_id, '_image_width', true) ?: '80',
                    'image_height' => get_post_meta($story_id, '_image_height', true) ?: '80',
                    // Badge style meta
                    'badge_gradient_start' => get_post_meta($story_id, '_badge_gradient_start', true) ?: '#833AB4',
                    'badge_gradient_middle' => get_post_meta($story_id, '_badge_gradient_middle', true) ?: '#FD1D1D',
                    'badge_gradient_end' => get_post_meta($story_id, '_badge_gradient_end', true) ?: '#FCB045',
                    'badge_font_size' => get_post_meta($story_id, '_badge_font_size', true) ?: '11',
                    'badge_margin_top' => get_post_meta($story_id, '_badge_margin_top', true) ?: '-20',
                    'badge_border_radius' => get_post_meta($story_id, '_badge_border_radius', true) ?: '8',
                    'badge_padding' => get_post_meta($story_id, '_badge_padding', true) ?: '7',
                    'badge_font_weight' => get_post_meta($story_id, '_badge_font_weight', true) ?: '600',
                );
            }
            wp_reset_postdata();
        }

        return $stories;
    }

    // Helper function to get story thumbnail URL
    public function get_story_thumbnail_url($story_id)
    {
        // First try to get custom thumbnail from post meta
        $thumbnail_id = get_post_meta($story_id, '_story_thumbnail', true);
        if ($thumbnail_id) {
            $thumbnail_url = wp_get_attachment_url($thumbnail_id);
            if ($thumbnail_url) {
                return $thumbnail_url;
            }
        }

        // Fallback to WordPress featured image
        $featured_image_url = get_the_post_thumbnail_url($story_id, 'full');
        if ($featured_image_url) {
            return $featured_image_url;
        }

        // Fallback to story media if available
    $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 ($story_video_id) {
            $media_url = wp_get_attachment_url($story_video_id);
            if ($media_url) {
                return $media_url;
            }
        }
    } else {
        $story_image_id = get_post_meta($story_id, '_story_image', true);
        if ($story_image_id) {
            $media_url = wp_get_attachment_url($story_image_id);
            if ($media_url) {
                return $media_url;
            }
        }
    }

        // Default placeholder
        return KSTORY_URL . 'assets/images/placeholder-story.jpg';
    }


    public function story_shop_shortcode($atts)
    {
        ob_start();

        $stories = $this->story_shop_get_stories();


        if (!empty($stories)): ?>
            <!-- Start Story -->
            <section class="story-shop">
                    <div class="swiper swiper-story-shop">
                        <div class="swiper-wrapper">
                            <?php foreach ($stories as $index => $story): ?>
                                <!-- Start Slide -->
                                <div class="swiper-slide">
                                    <div class="story-shop__item d-flex flex-column gap-2 cursor-pointer" data-bs-toggle="modal"
                                        data-bs-target="#modal-story-shop" data-story-index="<?php echo $index; ?>" data-story-id="<?php echo $story['ID']; ?>">
                                        <div class="image rounded-circle d-flex align-items-center justify-content-center" style="
                                            background: linear-gradient(90deg, 
                                                <?php echo esc_attr($story['gradient_start']); ?> 0%, 
                                                <?php echo esc_attr($story['gradient_middle']); ?> 50%, 
                                                <?php echo esc_attr($story['gradient_end']); ?> 100%);
                                            padding: 2px;
                                            width: <?php echo esc_attr($story['container_width']); ?>px;
                                            height: <?php echo esc_attr($story['container_height']); ?>px;
                                        ">
                                            <span class="rounded-circle d-flex align-items-center justify-content-center" style="
                                                background-color: #fff;
                                                width: <?php echo esc_attr($story['image_width']); ?>px;
                                                height: <?php echo esc_attr($story['image_height']); ?>px;
                                            ">
                                                <?php
                                                // Get thumbnail URL using helper function
                                                $thumbnail_url = '';

                                                // Use WordPress thumbnail
                                                if (!empty($story['thumbnail'])) {
                                                    $thumbnail_url = $story['thumbnail'];
                                                } else {
                                                    // Default placeholder if still empty
                                                    $thumbnail_url = KSTORY_URL . 'assets/images/placeholder-story.jpg';
                                                }
                                                ?>
                                                <div class="storyhoverimg">
                                                    <img src="<?php echo esc_url($thumbnail_url); ?>"
                                                        alt="<?php echo esc_attr($story['title']); ?>" width="74" height="74"
                                                        class="rounded-circle">
                                                    <svg xmlns="http://www.w3.org/2000/svg"
                                                        width="18" height="18" viewBox="0 0 18 18" fill="none">
                                                        <path
                                                            d="M4.02734 11.9382V5.56315C4.02734 5.12398 4.04151 4.7344 4.09109 4.38732C4.29651 2.5244 5.17484 2.02148 7.56901 2.02148H10.4023C12.7965 2.02148 13.6748 2.5244 13.8803 4.38732C13.9298 4.7344 13.944 5.12398 13.944 5.56315V11.9382C13.944 12.3773 13.9298 12.7669 13.8803 13.114C13.6748 14.9769 12.7965 15.4798 10.4023 15.4798H7.56901C5.17484 15.4798 4.29651 14.9769 4.09109 13.114C4.04151 12.7669 4.02734 12.3773 4.02734 11.9382Z"
                                                            stroke="white" stroke-width="1.5" stroke-linecap="round"
                                                            stroke-linejoin="round"></path>
                                                        <path d="M0.898438 14.0625V3.4375" stroke="white" stroke-width="1.5"
                                                            stroke-linecap="round" stroke-linejoin="round"></path>
                                                        <path d="M17.0703 13.709V3.08398" stroke="white" stroke-width="1.5"
                                                            stroke-linecap="round" stroke-linejoin="round"></path>
                                                    </svg>
                                                </div>

                                            </span>
                                        </div>
                                        <?php if (isset($story['enable_badge']) && $story['enable_badge']): ?>
                                            <p class="upperstorytitle" style="
                                            color: #fff;
                                            background: linear-gradient(90deg, 
                                                <?php echo esc_attr($story['badge_gradient_start']); ?> 0%, 
                                                <?php echo esc_attr($story['badge_gradient_middle']); ?> 50%, 
                                                <?php echo esc_attr($story['badge_gradient_end']); ?> 100%);
                                            text-align: center;
                                            font-size: <?php echo esc_attr($story['badge_font_size']); ?>px;
                                            margin: <?php echo esc_attr($story['badge_margin_top']); ?>px auto 0 auto;
                                            display: block;
                                            border-radius: <?php echo esc_attr($story['badge_border_radius']); ?>px;
                                            padding: 1px <?php echo esc_attr($story['badge_padding']); ?>px;
                                            font-weight: <?php echo esc_attr($story['badge_font_weight']); ?>;
                                        "><?php echo $story['story_badge'] ?></p>
                                        <?php endif; ?>
                                        <div class="title fs-11 line-height-18 fw-normal text-dark-10 text-center">
                                            <?php echo esc_html($story['title']); ?>
                                        </div>
                                    </div>
                                </div>
                                <!-- End Slide -->
                            <?php endforeach; ?>
                        </div>
                    </div>
            </section>
            <!-- End Story -->

            <!-- Start Modal Story -->
            <div id="modal-story-shop" class="modal modal-story-shop fade">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-body">
                            <div class="swiper swiper-story-items position-unset w-100 overflow-visible">
                                <div class="swiper-wrapper" id="story-modal-content">
                                    <!-- Story content will be loaded via AJAX -->
                                    <div class="swiper-slide">
                                        <div class="story-shop__story position-relative h-100 d-flex align-items-center justify-content-center">
                                            <div class="spinner-border text-white" role="status">
                                                <span class="visually-hidden"><?php echo esc_html__('Loading...', 'kavehTheme'); ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="swiper-button-next d-flex align-items-center justify-content-center rounded-circle text-gray-9 bg-white end-0 fs-20 lh-1 transition-ease-in-out">
                                    <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>
                                </div>
                                <div class="swiper-button-prev d-flex align-items-center justify-content-center rounded-circle text-gray-9 bg-white start-0 fs-20 lh-1 transition-ease-in-out">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                                        <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" />
                                    </svg>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- End Modal Story -->

            <!-- Start Comments Story Modal -->
            <div id="modal-comments-story" class="modal modal-comments-story modal-mobile fade">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <div class="modal-title fs-16 line-height-24 fw-bold text-dark-15">
                                <?php _e('Comments', 'kavehTheme'); ?></div>
                            <button type="button" class="modal-close fs-24 lh-1 text-dark-15" 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="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
                                </svg>
                            </button>
                        </div>
                        <div class="modal-body">
                            <!-- Comments will be loaded dynamically -->
                            <ul class="comments-story scrollbar" id="story-comments-list">
                                <!-- Comments will be injected here via AJAX -->
                            </ul>

                            <!-- Empty Comment -->
                            <div class="empty-comments-story d-none flex-column align-items-center justify-content-center">
                                <img src="<?php echo KSTORY_URL . 'assets/images/empty-comments.svg'; ?>" alt="image"
                                    width="256" height="192" class="mb-12">
                                <div class="text text-center fs-14 fw-normal line-height-22 text-dark">
                                    <?php _e('Be the first to comment!', 'kavehTheme'); ?></div>
                            </div>

                            <!-- Send Comment -->
                            <div class="send-comment-story">
                                <form action="#" method="post" class="send-comment-story__form position-relative">

                                    <input type="text" name="comment"
                                        class="send-comment-story__input form-control border-0 shadow-none"
                                        placeholder="<?php _e('Write your comment...', 'kavehTheme'); ?>">
                                    <input type="hidden" name="story_id" id="current-story-id" value="">
                                    <button type="submit"
                                        class="send-comment-story__btn position-absolute top-50 translate-middle-y fs-18 lh-1 d-none">
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
                                            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" />
                                        </svg>
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- End Comments Story Modal -->

            <!-- Start Info Product Story Modal -->
            <div id="modal-product-story" class="modal modal-product-story modal-mobile fade">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="modal-close fs-24 lh-1 text-dark-15 ms-auto" 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="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
                                </svg>
                            </button>
                        </div>
                        <div class="modal-body" id="product-story-content">
                            <!-- Product info will be loaded dynamically -->
                        </div>
                    </div>
                </div>
            </div>
            <!-- End Info Product Story Modal -->
<?php endif;

        return ob_get_clean();
    }
}

new storylmviews();
