<?php
/**
 * Plugin Name: KPY Testimonials Slider
 * Description: Custom Post Type for Testimonials with a responsive slider shortcode and AOS animations.
 * Version: 2.0.0
 * Author: Your Name
 */

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

/**
 * Register Testimonial Custom Post Type
 */
function kpy_register_testimonial_cpt() {
    $labels = array(
        'name'               => 'Testimonials',
        'singular_name'      => 'Testimonial',
        'menu_name'          => 'Testimonials',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Testimonial',
        'edit_item'          => 'Edit Testimonial',
        'new_item'           => 'New Testimonial',
        'view_item'          => 'View Testimonial',
        'search_items'       => 'Search Testimonials',
        'not_found'          => 'No testimonials found',
        'not_found_in_trash' => 'No testimonials found in trash',
    );

    $args = array(
        'labels'              => $labels,
        'public'              => true,
        'has_archive'         => false,
        'exclude_from_search' => true,
        'publicly_queryable'  => false,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_admin_bar'   => true,
        'supports'            => array( 'title', 'editor', 'thumbnail' ),
        'menu_icon'           => 'dashicons-format-quote',
    );

    register_post_type( 'kpy_testimonial', $args );
}
add_action( 'init', 'kpy_register_testimonial_cpt' );

/**
 * Shortcode to display testimonials slider with AOS effects
 * Usage: [kpy_testimonials_slider]
 * Additional attributes: [kpy_testimonials_slider posts_per_page="6" aos_duration="800" aos_delay="0" aos_offset="100" aos_easing="ease-in-out" aos_once="true"]
 */
function kpy_testimonials_slider_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'posts_per_page' => -1,
        'aos_duration'   => '800',
        'aos_delay'      => '0',
        'aos_offset'     => '100',
        'aos_easing'     => 'ease-in-out',
        'aos_once'       => 'true',
        'aos_mirror'     => 'false',
        'aos_anchor_placement' => 'top-bottom',
        'autoplay_speed' => '5000',
        'slides_per_view' => '2',
    ), $atts );

    $args = array(
        'post_type'      => 'kpy_testimonial',
        'posts_per_page' => $atts['posts_per_page'],
        'post_status'    => 'publish',
    );

    $testimonials = get_posts( $args );

    if ( empty( $testimonials ) ) {
        return '<p>No testimonials found.</p>';
    }

    $slider_id = 'kpy-slider-' . uniqid();
    
    // Enqueue AOS CSS and JS
    wp_enqueue_style( 'aos-css', 'https://unpkg.com/aos@2.3.1/dist/aos.css', array(), '2.3.1' );
    wp_enqueue_script( 'aos-js', 'https://unpkg.com/aos@2.3.1/dist/aos.js', array(), '2.3.1', true );
    
    ob_start();
    ?>
    <div class="kpy-testimonials-wrapper" data-aos="fade-up" 
         data-aos-duration="<?php echo esc_attr( $atts['aos_duration'] ); ?>" 
         data-aos-offset="<?php echo esc_attr( $atts['aos_offset'] ); ?>"
         data-aos-easing="<?php echo esc_attr( $atts['aos_easing'] ); ?>"
         data-aos-once="<?php echo esc_attr( $atts['aos_once'] ); ?>">
        
        <div class="kpy-sg-header">
            <div class="kpy-sg-title-container">
                <div class="kpy-sg-title-bg" aria-hidden="true">
                    Testimonials
                </div>
                <h2 class="kpy-sg-title">
                    <span class="kpy-sg-title-red">What Our</span>
                    <span class="kpy-sg-title-white">Clients Say</span>
                </h2>
            </div>
        </div>
        
        <!-- Navigation above cards -->
        <div class="kpy-slider-nav">
            <button class="testimonial-prev" data-slider="<?php echo esc_attr($slider_id); ?>">‹</button>
            <button class="testimonial-next" data-slider="<?php echo esc_attr($slider_id); ?>">›</button>
        </div>
        
        <div class="kpy-testimonials-slider container" id="<?php echo esc_attr($slider_id); ?>">
            <div class="kpy-slider-track">
                <?php foreach ( $testimonials as $index => $testimonial ) : 
                    $name = get_the_title( $testimonial->ID );
                    $content = get_post_field( 'post_content', $testimonial->ID );
                    $position = get_post_meta( $testimonial->ID, '_kpy_testimonial_position', true );
                    $badge_text = get_post_meta( $testimonial->ID, '_kpy_testimonial_badge', true );
                    $rating = get_post_meta( $testimonial->ID, '_kpy_testimonial_rating', true );
                    $thumbnail_id = get_post_thumbnail_id( $testimonial->ID );
                    $avatar_url = '';
                    $has_avatar = false;

                    if ( $thumbnail_id ) {
                        $avatar_url = wp_get_attachment_image_url( $thumbnail_id, 'medium' );
                        if ( $avatar_url ) {
                            $has_avatar = true;
                        }
                    }

                    $first_letter = ! empty( $name ) ? mb_substr( $name, 0, 1 ) : 'U';
                    $clean_content = wp_strip_all_tags( $content );
                    
                    // Staggered delay for each testimonial
                    $staggered_delay = intval($atts['aos_delay']) + ($index * 100);
                ?>
                    <div class="kpy-slide" 
                         data-aos="fade-up" 
                         data-aos-duration="<?php echo esc_attr( $atts['aos_duration'] ); ?>" 
                         data-aos-delay="<?php echo $staggered_delay; ?>"
                         data-aos-offset="<?php echo esc_attr( $atts['aos_offset'] ); ?>"
                         data-aos-easing="<?php echo esc_attr( $atts['aos_easing'] ); ?>"
                         data-aos-once="<?php echo esc_attr( $atts['aos_once'] ); ?>"
                         data-aos-anchor-placement="<?php echo esc_attr( $atts['aos_anchor_placement'] ); ?>">
                        <div class="single-testimonials-item kpy-testimonial-card">
                            <?php if ( ! empty( $badge_text ) ) : ?>
                                <div class="kpy-testimonial-title-badge">
                                    <i class="fas fa-quote-left"></i> <?php echo esc_html( $badge_text ); ?>
                                </div>
                            <?php endif; ?>
                            
                            <?php if ( ! empty( $rating ) ) : ?>
                                <div class="kpy-testimonial-rating">
                                    <?php for( $i = 1; $i <= 5; $i++ ) : ?>
                                        <i class="fas fa-star <?php echo $i <= intval($rating) ? 'active' : ''; ?>"></i>
                                    <?php endfor; ?>
                                </div>
                            <?php endif; ?>
                            
                            <div class="kpy-testimonial-text">
                                <i class="fas fa-quote-left quote-icon"></i>
                                <?php echo nl2br( esc_html( $clean_content ) ); ?>
                            </div>
                            
                            <div class="kpy-testimonial-author-section">
                                <div class="kpy-testimonial-avatar">
                                    <?php if ( $has_avatar ) : ?>
                                        <img src="<?php echo esc_url( $avatar_url ); ?>" alt="<?php echo esc_attr( $name ); ?>" loading="lazy">
                                    <?php else : ?>
                                        <span class="kpy-testimonial-initial"><?php echo esc_html( $first_letter ); ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="kpy-testimonial-author-info">
                                    <strong><?php echo esc_html( $name ); ?></strong>
                                    <?php if ( ! empty( $position ) ) : ?>
                                        <span><?php echo esc_html( $position ); ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Decorative elements -->
                            <div class="kpy-testimonial-glow"></div>
                            <div class="kpy-testimonial-corner"></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="kpy-slider-pagination" data-slider="<?php echo esc_attr($slider_id); ?>"></div>
    </div>

    
    <script>
    (function() {
        var sliderId = '<?php echo esc_js($slider_id); ?>';
        var container = document.getElementById(sliderId);
        if (!container) return;
        
        var track = container.querySelector('.kpy-slider-track');
        var slides = container.querySelectorAll('.kpy-slide');
        var prevBtn = document.querySelector('.testimonial-prev[data-slider="' + sliderId + '"]');
        var nextBtn = document.querySelector('.testimonial-next[data-slider="' + sliderId + '"]');
        var pagination = document.querySelector('.kpy-slider-pagination[data-slider="' + sliderId + '"]');
        
        var slidesPerView = <?php echo intval($atts['slides_per_view']); ?>;
        var currentIndex = 0;
        var totalSlides = slides.length;
        var autoplayInterval;
        var autoplaySpeed = <?php echo intval($atts['autoplay_speed']); ?>;
        
        // Check screen size for slides per view
        function updateSlidesPerView() {
            if (window.innerWidth < 768) {
                return 1;
            }
            return slidesPerView;
        }
        
        // Update slider position
        function updateSlider() {
            if (!slides.length) return;
            var slideWidth = slides[0].offsetWidth;
            var gap = 30;
            var currentSlidesPerView = updateSlidesPerView();
            var offset = -(currentIndex * (slideWidth + gap));
            track.style.transform = 'translateX(' + offset + 'px)';
            updatePagination();
        }
        
        // Update pagination dots
        function updatePagination() {
            if (!pagination) return;
            var currentSlidesPerView = updateSlidesPerView();
            var totalGroups = Math.ceil(totalSlides / currentSlidesPerView);
            pagination.innerHTML = '';
            
            for (var i = 0; i < totalGroups; i++) {
                var dot = document.createElement('span');
                dot.classList.add('kpy-pagination-dot');
                var activeGroup = Math.floor(currentIndex / currentSlidesPerView);
                if (i === activeGroup) {
                    dot.classList.add('active');
                }
                dot.addEventListener('click', (function(index) {
                    return function() {
                        currentIndex = index * currentSlidesPerView;
                        if (currentIndex >= totalSlides) {
                            currentIndex = totalSlides - currentSlidesPerView;
                        }
                        if (currentIndex < 0) currentIndex = 0;
                        updateSlider();
                        resetAutoplay();
                    };
                })(i));
                pagination.appendChild(dot);
            }
        }
        
        // Next slide
        function nextSlide() {
            var currentSlidesPerView = updateSlidesPerView();
            var maxIndex = totalSlides - currentSlidesPerView;
            if (currentIndex + currentSlidesPerView < totalSlides) {
                currentIndex += currentSlidesPerView;
            } else {
                currentIndex = 0;
            }
            updateSlider();
        }
        
        // Previous slide
        function prevSlide() {
            var currentSlidesPerView = updateSlidesPerView();
            if (currentIndex - currentSlidesPerView >= 0) {
                currentIndex -= currentSlidesPerView;
            } else {
                currentIndex = totalSlides - currentSlidesPerView;
                if (currentIndex < 0) currentIndex = 0;
            }
            updateSlider();
        }
        
        // Reset autoplay timer
        function resetAutoplay() {
            if (autoplayInterval) {
                clearInterval(autoplayInterval);
                autoplayInterval = setInterval(nextSlide, autoplaySpeed);
            }
        }
        
        // Start autoplay
        function startAutoplay() {
            if (autoplayInterval) clearInterval(autoplayInterval);
            autoplayInterval = setInterval(nextSlide, autoplaySpeed);
        }
        
        // Handle window resize
        var resizeTimeout;
        function handleResize() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                var oldSlidesPerView = slidesPerView;
                updateSlidesPerView();
                if (oldSlidesPerView !== slidesPerView) {
                    currentIndex = 0;
                    updateSlider();
                }
                updateSlider();
            }, 100);
        }
        
        // Initialize AOS
        function initAOS() {
            if (typeof AOS !== 'undefined') {
                AOS.init({
                    duration: <?php echo intval($atts['aos_duration']); ?>,
                    offset: <?php echo intval($atts['aos_offset']); ?>,
                    easing: '<?php echo esc_js($atts['aos_easing']); ?>',
                    once: <?php echo $atts['aos_once'] === 'true' ? 'true' : 'false'; ?>,
                    mirror: <?php echo $atts['aos_mirror'] === 'true' ? 'true' : 'false'; ?>,
                    disable: false,
                    startEvent: 'DOMContentLoaded'
                });
            }
        }
        
        // Initialize slider
        function initSlider() {
            if (totalSlides === 0) return;
            
            updateSlidesPerView();
            updateSlider();
            
            // Event listeners
            if (prevBtn) prevBtn.addEventListener('click', function() { prevSlide(); resetAutoplay(); });
            if (nextBtn) nextBtn.addEventListener('click', function() { nextSlide(); resetAutoplay(); });
            window.addEventListener('resize', handleResize);
            
            // Start autoplay
            startAutoplay();
            
            // Pause autoplay on hover
            container.addEventListener('mouseenter', function() {
                if (autoplayInterval) clearInterval(autoplayInterval);
            });
            container.addEventListener('mouseleave', function() {
                startAutoplay();
            });
        }
        
        // Initialize everything
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                initAOS();
                initSlider();
            });
        } else {
            initAOS();
            initSlider();
        }
        
        // Refresh AOS on AJAX complete
        if (typeof jQuery !== 'undefined') {
            jQuery(document).on('ajaxComplete', function() {
                if (typeof AOS !== 'undefined') {
                    AOS.refresh();
                }
            });
        }
    })();
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode( 'kpy_testimonials_slider', 'kpy_testimonials_slider_shortcode' );

/**
 * Add meta box for testimonial position/role, badge, and rating
 */
function kpy_testimonial_add_meta_box() {
    add_meta_box(
        'kpy_testimonial_details',
        'Testimonial Details',
        'kpy_testimonial_meta_box_callback',
        'kpy_testimonial',
        'normal',
        'high'
    );
}
add_action( 'add_meta_boxes', 'kpy_testimonial_add_meta_box' );

function kpy_testimonial_meta_box_callback( $post ) {
    wp_nonce_field( 'kpy_testimonial_save_data', 'kpy_testimonial_nonce' );
    $position = get_post_meta( $post->ID, '_kpy_testimonial_position', true );
    $badge_text = get_post_meta( $post->ID, '_kpy_testimonial_badge', true );
    $rating = get_post_meta( $post->ID, '_kpy_testimonial_rating', true );
    ?>
    <p>
        <label for="kpy_testimonial_position">Position/Role (e.g., CEO at Envato):</label>
        <input type="text" id="kpy_testimonial_position" name="kpy_testimonial_position" value="<?php echo esc_attr( $position ); ?>" style="width: 100%;" />
    </p>
    <p>
        <label for="kpy_testimonial_badge">Title Badge (e.g., "Amazing Service"):</label>
        <input type="text" id="kpy_testimonial_badge" name="kpy_testimonial_badge" value="<?php echo esc_attr( $badge_text ); ?>" style="width: 100%;" placeholder="Enter title badge text" />
        <small>This will appear as a styled title badge at the top of each testimonial card.</small>
    </p>
    <p>
        <label for="kpy_testimonial_rating">Rating (1-5 stars):</label>
        <select id="kpy_testimonial_rating" name="kpy_testimonial_rating" style="width: 100%;">
            <option value="">No Rating</option>
            <?php for( $i = 1; $i <= 5; $i++ ) : ?>
                <option value="<?php echo $i; ?>" <?php selected( $rating, $i ); ?>><?php echo $i; ?> Star<?php echo $i > 1 ? 's' : ''; ?></option>
            <?php endfor; ?>
        </select>
        <small>Select rating to display star rating on the testimonial.</small>
    </p>
    <?php
}

function kpy_testimonial_save_meta_data( $post_id ) {
    if ( ! isset( $_POST['kpy_testimonial_nonce'] ) || ! wp_verify_nonce( $_POST['kpy_testimonial_nonce'], 'kpy_testimonial_save_data' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
    if ( isset( $_POST['kpy_testimonial_position'] ) ) {
        update_post_meta( $post_id, '_kpy_testimonial_position', sanitize_text_field( $_POST['kpy_testimonial_position'] ) );
    }
    if ( isset( $_POST['kpy_testimonial_badge'] ) ) {
        update_post_meta( $post_id, '_kpy_testimonial_badge', sanitize_text_field( $_POST['kpy_testimonial_badge'] ) );
    }
    if ( isset( $_POST['kpy_testimonial_rating'] ) ) {
        update_post_meta( $post_id, '_kpy_testimonial_rating', intval( $_POST['kpy_testimonial_rating'] ) );
    }
}
add_action( 'save_post', 'kpy_testimonial_save_meta_data' );

/**
 * Create JS file (fallback)
 */
function kpy_create_js_file() {
    $js_dir = plugin_dir_path( __FILE__ ) . 'js';
    if ( ! file_exists( $js_dir ) ) {
        wp_mkdir_p( $js_dir );
    }
    $js_file = $js_dir . '/testimonial-slider.js';
    if ( ! file_exists( $js_file ) ) {
        $js_content = "// Main slider initialization is handled inline in the shortcode\nconsole.log('KPY Testimonials Slider - Ready');";
        file_put_contents( $js_file, $js_content );
    }
}
register_activation_hook( __FILE__, 'kpy_create_js_file' );
add_action( 'admin_init', 'kpy_create_js_file' );