<?php
function allNews_shortcode($atts) {
    ob_start();

    // Get shortcode attributes
    $atts = shortcode_atts(array(
        'posts_per_page' => 9, // Changed to 9
    ), $atts);

    // Get current page
    if (get_query_var('paged')) {
        $paged = get_query_var('paged');
    } elseif (get_query_var('page')) {
        $paged = get_query_var('page');
    } else {
        $paged = 1;
    }

    // Clear any cached query
    wp_reset_query();
    
    $news_args = array(
        'post_type' => array('post'),
        'posts_per_page' => 9, // Force 9 posts
        'category_name' => 'news, blog',
        'paged' => $paged,
        'post_status' => 'publish',
        'no_found_rows' => false, // Ensure pagination works
        'update_post_meta_cache' => false,
        'update_post_term_cache' => false,
    );
    
    $news_query = new WP_Query($news_args); 
    ?>

    <div class="kpy-news-container">
        <?php if ($news_query->have_posts()) : ?>
        <div class="kpy-news-grid">
            <?php while ($news_query->have_posts()) :
                $news_query->the_post();
                $categories = get_the_category();
                $primary_category = !empty($categories) ? $categories[0]->name : 'News';
            ?>
            <article class="kpy-news-card">
                <a href="<?= esc_url(get_permalink()); ?>" class="kpy-news-card-link">
                    <div class="kpy-news-thumb">
                        <?php if (has_post_thumbnail()) : ?>
                            <?php the_post_thumbnail('medium_large', ['class' => 'kpy-news-img']); ?>
                        <?php else : ?>
                            <img src="<?= get_template_directory_uri(); ?>/assets/images/photo-placeholder.jpg" alt="<?php the_title(); ?>" class="kpy-news-img"/>
                        <?php endif; ?>
                        <span class="kpy-news-badge"><?= esc_html($primary_category); ?></span>
                    </div>
                    <div class="kpy-news-body">
                        <span class="kpy-news-date">
                            <i class="bi bi-calendar-check"></i>
                            <?php echo get_the_date(); ?>
                        </span>
                        <h3 class="kpy-news-title"><?php the_title(); ?></h3>
                        <p class="kpy-news-excerpt"><?php echo wp_trim_words(get_the_excerpt(), 18); ?></p>
                        <span class="kpy-news-btn">
                            Read More <i class="bi bi-arrow-right"></i>
                        </span>
                    </div>
                </a>
            </article>
            <?php endwhile; ?>
        </div>

        <!-- Pagination -->
        <?php if ($news_query->max_num_pages > 1) : ?>
        <div class="kpy-news-pagination">
            <nav class="pagination-nav" aria-label="News pagination">
                <?php
                $big = 999999999;
                
                echo paginate_links(array(
                    'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
                    'format' => '?paged=%#%',
                    'current' => max(1, $paged),
                    'total' => $news_query->max_num_pages,
                    'prev_text' => '&laquo; Prev',
                    'next_text' => 'Next &raquo;',
                    'mid_size' => 2,
                    'end_size' => 1,
                    'show_all' => false,
                    'type' => 'plain',
                ));
                ?>
            </nav>
            
            <div class="kpy-page-info">
                Page <?php echo $paged; ?> of <?php echo $news_query->max_num_pages; ?> 
                (<?php echo $news_query->found_posts; ?> total posts)
            </div>
        </div>
        <?php endif; ?>

        <?php 
            wp_reset_postdata();
        else :
            echo '<p class="text-center py-5">No news found.</p>';
        endif;
        ?>
    </div>

    <?php
    return ob_get_clean();
}
add_shortcode('all_news', 'allNews_shortcode');


function news_slider_shortcode() {
    ob_start();

    $news_args = array(
        'post_type' => array('post'),
        'posts_per_page' => 6,
        'category_name' => 'news, blog',
    );
    
    $news_query = new WP_Query($news_args); ?>
    
    <div class="kpy-news-slider-container">
        <!-- Header Section -->
        <div class="kpy-news-slider-header">
            <h2 class="uegcl-about-subtitle">Latest News and Stories</h2>
            <p class="uegcl-about-title">Discover our community impact through these inspiring updates</p>
        </div>
        
        <!-- Slider Section -->
        <div class="kpy-news-slider-wrapper">
            <div class="kpy-news-slider">
                <?php if ($news_query->have_posts()) : ?>
                    <?php while ($news_query->have_posts()) : $news_query->the_post(); ?>
                    <div class="kpy-news-slide">
                        <article class="kpy-news-card">
                            <a href="<?= esc_url(get_permalink()); ?>" class="kpy-news-card-link">
                                <div class="kpy-news-card-thumbnail">
                                    <?php if (has_post_thumbnail()) {
                                        the_post_thumbnail('medium_large', ['class' => 'kpy-news-card-image']); 
                                    } else {
                                        echo '<img src="'. get_template_directory_uri().'/assets/images/photo-placeholder.jpg" alt="News thumbnail" class="kpy-news-card-image"/>';
                                    } ?>
                                   
                                </div>
                                <div class="kpy-news-card-content">
                                    <div class="kpy-news-card-meta">
                                        <span class="kpy-news-date" style="color: var(--kpy-secondary);"><?php echo get_the_date(); ?></span>
                                    </div>
                                    <h3 class="kpy-news-card-title"><?php the_title(); ?></h3>
                                    <div class="kpy-news-card-excerpt"><?php echo wp_trim_words(get_the_excerpt(), 18); ?></div>
                                    <span class="kpy-news-card-button">
                                        Read More
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M5 12h14M12 5l7 7-7 7"></path>
                                        </svg>
                                    </span>
                                </div>
                            </a>
                        </article>
                    </div>
                    <?php endwhile; ?>
                    <?php wp_reset_postdata(); ?>
                <?php else : ?>
                    <p class="kpy-news-slider-empty">No stories found. Check back soon for updates.</p>
                <?php endif; ?>
            </div>
            
            <!-- Slider Navigation -->
            <button class="kpy-news-slider-prev" aria-label="Previous slide">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M15 18l-6-6 6-6"></path>
                </svg>
            </button>
            <button class="kpy-news-slider-next" aria-label="Next slide">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M9 18l6-6-6-6"></path>
                </svg>
            </button>
        </div>
    </div>
        
       

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const slider = document.querySelector('.kpy-news-slider');
        const prevBtn = document.querySelector('.kpy-news-slider-prev');
        const nextBtn = document.querySelector('.kpy-news-slider-next');
        const slides = document.querySelectorAll('.kpy-news-slide');
        let currentIndex = 0;
        const slideWidth = slides[0]?.offsetWidth + 30; // 30px gap
        
        // Manual navigation
        prevBtn.addEventListener('click', () => {
            currentIndex = Math.max(currentIndex - 1, 0);
            slider.scrollTo({
                left: currentIndex * slideWidth,
                behavior: 'smooth'
            });
        });
        
        nextBtn.addEventListener('click', () => {
            currentIndex = Math.min(currentIndex + 1, slides.length - 1);
            slider.scrollTo({
                left: currentIndex * slideWidth,
                behavior: 'smooth'
            });
        });
        
        // Auto-scroll
        let autoScrollInterval;
        let isHovered = false;
        
        function startAutoScroll() {
            autoScrollInterval = setInterval(() => {
                if (!isHovered) {
                    currentIndex = (currentIndex + 1) % slides.length;
                    slider.scrollTo({
                        left: currentIndex * slideWidth,
                        behavior: 'smooth'
                    });
                }
            }, 5000);
        }
        
        // Pause on hover
        slider.addEventListener('mouseenter', () => isHovered = true);
        slider.addEventListener('mouseleave', () => isHovered = false);
        
        // Initialize
        startAutoScroll();
        
        // Cleanup on slider destruction
        return () => clearInterval(autoScrollInterval);
    });
    </script>

    <?php
    return ob_get_clean();
}
add_shortcode('news_slider', 'news_slider_shortcode');
/**
 *******************************
 *  gallery
 *******************************
**/
/**
 *******************************
 *  gallery shortcode with pagination
 *******************************
**/
function gallery_cards_shortcode($atts) {
    ob_start();

    // Shortcode attributes
    $atts = shortcode_atts(array(
        'posts_per_page' => 9,
        'category' => 'photo-gallery'
    ), $atts);

    // Detect current page number properly (for shortcode on pages)
    if (get_query_var('paged')) {
        $paged = get_query_var('paged');
    } elseif (get_query_var('page')) {
        $paged = get_query_var('page');
    } else {
        $paged = 1;
    }

    // Query arguments
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $atts['posts_per_page'],
        'category_name' => $atts['category'],
        'paged' => $paged,
    );

    $gallery_query = new WP_Query($args);

    if ($gallery_query->have_posts()) : ?>
        <div class="gallery-cards-container">
            <div class="gallery-grid">
                <?php while ($gallery_query->have_posts()) : $gallery_query->the_post(); ?>
                    <div class="gallery-card">
                        <a href="<?php the_permalink(); ?>" class="gallery-card-link" data-fancybox="gallery" data-caption="<?php the_title(); ?>">
                            <div class="gallery-thumbnail-wrapper">
                                <?php if (has_post_thumbnail()) : ?>
                                    <?php the_post_thumbnail('large', array('class' => 'gallery-thumbnail')); ?>
                                <?php else : ?>
                                    <img src="<?php echo esc_url(get_template_directory_uri() . '/assets/images/photo-placeholder.jpg'); ?>" 
                                         alt="<?php esc_attr(the_title()); ?>" 
                                         class="gallery-thumbnail">
                                <?php endif; ?>
                                <div class="gallery-title-overlay">
                                    <h3 class="gallery-title"><?php the_title(); ?></h3>
                                </div>
                            </div>
                        </a>
                    </div>
                <?php endwhile; ?>
            </div>

            <!-- Pagination -->
            <div class="gallery-pagination">
                <?php
                echo paginate_links(array(
                    'total' => $gallery_query->max_num_pages,
                    'current' => max(1, $paged),
                    'format' => '?paged=%#%',
                    'prev_text' => __('<span class="pagination-arrow">&larr;</span> Previous'),
                    'next_text' => __('Next <span class="pagination-arrow">&rarr;</span>'),
                    'type' => 'list',
                    'mid_size' => 2
                ));
                ?>
            </div>
        </div>

    <?php else : ?>
        <p class="no-galleries">No photo galleries found.</p>
    <?php endif;

    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('gallery', 'gallery_cards_shortcode');


// Enhanced Fancybox initialization
function enqueue_lightbox_assets() {
    wp_enqueue_style('fancybox-css', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css');
    wp_enqueue_script('fancybox-js', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js', array('jquery'), null, true);
    wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css');
    
    wp_add_inline_script('fancybox-js', '
        jQuery(document).ready(function($) {
            $("[data-fancybox]").fancybox({
                buttons: ["zoom", "slideShow", "thumbs", "close"],
                animationEffect: "fade",
                transitionEffect: "slide",
                loop: true,
                infobar: true,
                toolbar: true,
                protect: false,
                modal: false,
                touch: {
                    vertical: true,
                    momentum: true
                },
                thumbs: {
                    autoStart: false,
                    hideOnClose: true,
                    parentEl: ".fancybox-container",
                    axis: "y"
                },
                caption: function(instance, item) {
                    var caption = $(item.opts.$orig).data("caption");
                    return caption && caption.trim() ? 
                        "<div class=\"fancybox-caption-custom\">" + caption + "</div>" : 
                        "";
                },
                beforeShow: function(instance, current) {
                    // Enhanced caption styling
                    if (!$("#fancybox-caption-styles").length) {
                        $("head").append(`
                            <style id="fancybox-caption-styles">
                                .fancybox-caption-custom {
                                    color: #fff !important;
                                    font-size: 16px;
                                    line-height: 1.4;
                                    padding: 12px 20px;
                                    background: rgba(0,0,0,0.8);
                                    border-radius: 6px;
                                    text-align: center;
                                    margin: 10px auto 0;
                                    max-width: 80%;
                                    backdrop-filter: blur(10px);
                                }
                                .fancybox-caption {
                                    color: #fff !important;
                                    text-align: center !important;
                                }
                                .fancybox-toolbar {
                                    background: rgba(0,0,0,0.5) !important;
                                }
                                @media (max-width: 768px) {
                                    .fancybox-caption-custom {
                                        font-size: 14px;
                                        padding: 10px 15px;
                                        max-width: 90%;
                                    }
                                }
                            </style>
                        `);
                    }
                }
            });
        });
    ');
}
add_action('wp_enqueue_scripts', 'enqueue_lightbox_assets');


// AJAX handler for image data
add_action('wp_ajax_get_image_data', 'get_image_data_callback');
add_action('wp_ajax_nopriv_get_image_data', 'get_image_data_callback');

function get_image_data_callback() {
    $image_id = intval($_GET['id']);
    $image_url = wp_get_attachment_image_url($image_id, 'full');
    $image_caption = get_the_title($image_id);
    
    wp_send_json(array(
        'url' => $image_url,
        'caption' => $image_caption
    ));
}

?>