<?php
/**
 * File to handle the web stories.
 *
 * @package Purenote
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$enable_stories = purenote_get_customizer_option_value( 'purenote_web_stories_enable' );
$section_title  = purenote_get_customizer_option_value( 'purenote_web_stories_title' );
$hover_effect   = purenote_get_customizer_option_value( 'purenote_web_stories_hover_effect' );

if ( ! $enable_stories ) return;

$stories = purenote_get_swiper_stories_data();
if ( empty( $stories ) ) {
    return;
}
?>

<section class="purenote-web-stories hover-<?php echo esc_attr( $hover_effect ); ?>">
    <div class="purenote-container">
        <div class="row">

            <?php if ( ! empty( $section_title ) ) : ?>
                <div class="section-head">
                    <h2 class="section-title">
                        <span class="divider"></span>
                        <span class="purenote-title"><?php echo esc_html( $section_title ); ?></span>
                    </h2>
                </div>
            <?php endif; ?>

            <div class="stories-wrap">
                <?php foreach ( $stories as $story ) :
                    $first_post_id = $story['first_post_id'] ?? 0;
                    $thumb_url = $first_post_id
                        ? get_the_post_thumbnail_url( $first_post_id, 'large' )
                        : get_template_directory_uri() . '/assets/images/default-avatar.png';
                    $post_title = $first_post_id
                        ? get_the_title( $first_post_id )
                        : __( 'No Title', 'purenote' );
                    $count = $story['count'] ?? 0;

                    // Array to store slides (no $post global overwritten)
                    $story_slides = array();

                    if ( $first_post_id ) {

                        $args = array(
                            'post_type'      => 'post',
                            'post_status'    => 'publish',
                            'posts_per_page' => 10,
                            'cat'            => (int) $story['id'],
                            'meta_query'     => array(
                                array(
                                    'key'     => '_thumbnail_id',
                                    'compare' => 'EXISTS',
                                ),
                            ),
                            'no_found_rows'  => true,
                            'update_post_term_cache' => false,
                            'update_post_meta_cache' => false,
                        );

                        $query = new WP_Query( $args );

                        if ( $query->have_posts() ) :
                            foreach ( $query->posts as $post_item ) {

                                // --- SAFE: Explicit post ID, no global $post usage ---
                                $img    = get_the_post_thumbnail_url( $post_item->ID, 'large' );
                                $title  = get_the_title( $post_item->ID );
                                $date   = get_the_date( 'F j, Y', $post_item->ID );
                                $author = get_the_author_meta( 'display_name', $post_item->post_author );
                                $categories = get_the_category( $post_item->ID );

                                // Categories HTML
                                $cats_html = '<ul class="post-categories">';
                                if ( ! empty( $categories ) ) {
                                    foreach ( $categories as $cat_item ) {
                                        $cats_html .= '<li class="cat-item cat-' . esc_attr( $cat_item->term_id ) . '">
                                            <a href="' . esc_url( get_category_link( $cat_item->term_id ) ) . '">' . esc_html( $cat_item->name ) . '</a>
                                        </li>';
                                    }
                                }
                                $cats_html .= '</ul>';

                                // Slide HTML
                                $story_slides[] = '
                                <div class="swiper-slide" data-category="' . esc_attr( $story['id'] ) . '">
                                    <div class="story-item">
                                        <div class="story-cover-wrap">
                                            <figure class="story-cover">
                                                <img src="' . esc_url( $img ) . '" alt="' . esc_attr( $title ) . '" loading="eager">
                                            </figure>
                                        </div>
                                        <div class="content-wrap">
                                            ' . $cats_html . '
                                            <h2 class="title">
                                                <a href="' . esc_url( get_permalink( $post_item->ID ) ) . '">' . esc_html( $title ) . '</a>
                                            </h2>
                                            <div class="meta-wrap">
                                                <span class="byline">
                                                    <span class="author">
                                                        <a href="' . esc_url( get_author_posts_url( $post_item->post_author ) ) . '">' . esc_html( $author ) . '</a>
                                                    </span>
                                                </span>
                                                <span class="post-date">
                                                    <i class="fa-solid fa-calendar"></i>
                                                    <time datetime="' . esc_attr( get_the_date( 'c', $post_item->ID ) ) . '">' . esc_html( $date ) . '</time>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>';
                            }
                        endif;
                        
                        wp_reset_postdata();
                    }


                    // Encode slides as JSON (safe, no base64)
                    $slides_json = htmlspecialchars( wp_json_encode( $story_slides ), ENT_QUOTES, 'UTF-8' );
                ?>
                    <div class="story"
                         data-id="<?php echo esc_attr( $story['id'] ); ?>"
                         data-count="<?php echo esc_attr( $count ); ?>"
                         data-slides="<?php echo $slides_json; ?>">
                        <div class="preview">
                            <figure class="preview-thumb">
                                <img src="<?php echo esc_url( $thumb_url ); ?>"
                                     alt="<?php echo esc_attr( $post_title ); ?>"
                                     loading="eager">
                            </figure>
                            <a href="<?php echo esc_url( get_category_link( $story['id'] ) ); ?>" 
                               class="story-count">
                                <span class="label"><?php echo esc_html( $count ); ?></span>
                                <span class="text"><?php esc_html_e( 'Stories', 'purenote' ); ?></span>
                            </a>
                            <div class="story-title-wrap">
                                <h2 class="story-title">
                                    <span class="title-text"><?php echo esc_html( $post_title ); ?></span>
                                </h2>
                            </div>
                            <div class="indicators">
                                <?php for ( $i = 0; $i < $count; $i++ ) : ?>
                                    <span class="indicator"></span>
                                <?php endfor; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="inner-stories-wrap">
                <div class="inner-stories swiper">
                    <div class="swiper-wrapper"></div>

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

                    <div class="action-buttons">
                        <button class="action-btn close" aria-label="Close stories">
                            <i class="fa-solid fa-xmark"></i>
                        </button>
                        <button class="action-btn pause" data-state="playing" aria-label="Pause/Play">
                            <i class="fa-solid fa-pause"></i>
                        </button>
                    </div>
                </div>
            </div>

        </div>
    </div>
</section>
