<?php
/**
 * RG Testimonial Slider Block
 *
 * Registers the rg/testimonial-slider Gutenberg block.
 * Displays testimonials from ACF custom post type in a slider format.
 * Based on The Regent Grand design system.
 */

add_action('init', function() {
    $registry = WP_Block_Type_Registry::get_instance();
    if ($registry->is_registered('rg/testimonial-slider')) {
        return;
    }

    wp_register_script(
        'rg-testimonial-slider-editor',
        get_stylesheet_directory_uri() . '/blocks/rg-testimonial-slider/editor.js',
        array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render'),
        filemtime(get_stylesheet_directory() . '/blocks/rg-testimonial-slider/editor.js')
    );

    register_block_type('rg/testimonial-slider', array(
        'editor_script'   => 'rg-testimonial-slider-editor',
        'render_callback' => 'rg_render_testimonial_slider_block',
        'attributes'      => array(
            'category' => array(
                'type'    => 'string',
                'default' => '',
            ),
            'limit' => array(
                'type'    => 'number',
                'default' => 5,
            ),
            'autoplay' => array(
                'type'    => 'boolean',
                'default' => true,
            ),
            'autoplaySpeed' => array(
                'type'    => 'number',
                'default' => 5000,
            ),
            'background' => array(
                'type'    => 'string',
                'default' => 'white',
            ),
        ),
    ));
});

/**
 * Enqueue frontend styles and scripts for the testimonial slider block.
 */
add_action('wp_enqueue_scripts', function() {
    wp_register_style('rg-testimonial-slider-style', false);
    wp_enqueue_style('rg-testimonial-slider-style');

    $css = '
        .rg-testimonial-slider {
            max-width: 660px;
            margin: 0 auto;
            text-align: center;
            padding: 48px 52px;
            border-radius: 2px;
            position: relative;
            overflow: hidden;
        }
        .rg-testimonial-slider--white {
            background: #FFFFFF;
        }
        .rg-testimonial-slider--cream {
            background: #FAFAF7;
        }
        .rg-testimonial-slider--transparent {
            background: transparent;
        }
        .rg-testimonial-slider::before {
            content: "\201C";
            font-family: "Cormorant Garamond", Georgia, serif;
            font-size: 130px;
            line-height: 0.45;
            color: #C4A35A;
            opacity: 0.22;
            position: absolute;
            top: 34px;
            left: 30px;
            pointer-events: none;
        }
        .rg-testimonial-slider__slides {
            position: relative;
            min-height: 180px;
        }
        .rg-testimonial-slider__slide {
            opacity: 0;
            visibility: hidden;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            transition: opacity 0.5s ease, visibility 0.5s ease;
        }
        .rg-testimonial-slider__slide.active {
            opacity: 1;
            visibility: visible;
            position: relative;
        }
        .rg-testimonial-slider__content {
            font-family: "Cormorant Garamond", Georgia, serif;
            font-size: 24px;
            font-weight: 300;
            font-style: italic;
            line-height: 1.5;
            color: #1B2A4A;
            margin-bottom: 18px;
            position: relative;
            z-index: 1;
        }
        .rg-testimonial-slider__author {
            font-family: "Inter", sans-serif;
            font-size: 11px;
            font-weight: 500;
            letter-spacing: 0.12em;
            text-transform: uppercase;
            color: #888888;
            font-style: normal;
        }
        .rg-testimonial-slider__author a {
            color: #888888;
            text-decoration: none;
            transition: color 0.2s ease;
        }
        .rg-testimonial-slider__author a:hover {
            color: #C4A35A;
        }
        .rg-testimonial-slider__nav {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-top: 24px;
            position: relative;
            z-index: 2;
        }
        .rg-testimonial-slider__dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #C4A35A;
            opacity: 0.3;
            border: none;
            padding: 0;
            cursor: pointer;
            transition: opacity 0.2s ease, transform 0.2s ease;
        }
        .rg-testimonial-slider__dot:hover {
            opacity: 0.6;
        }
        .rg-testimonial-slider__dot.active {
            opacity: 1;
            transform: scale(1.25);
        }

        @media (max-width: 768px) {
            .rg-testimonial-slider {
                padding: 40px 28px;
            }
            .rg-testimonial-slider__content {
                font-size: 20px;
            }
            .rg-testimonial-slider::before {
                font-size: 80px;
                top: 20px;
                left: 15px;
            }
        }
    ';

    wp_add_inline_style('rg-testimonial-slider-style', $css);
});

/**
 * Server-side render callback for rg/testimonial-slider block.
 */
function rg_render_testimonial_slider_block($attributes) {
    $category = isset($attributes['category']) ? sanitize_text_field($attributes['category']) : '';
    $limit = isset($attributes['limit']) ? intval($attributes['limit']) : 5;
    $autoplay = isset($attributes['autoplay']) ? (bool)$attributes['autoplay'] : true;
    $autoplay_speed = isset($attributes['autoplaySpeed']) ? intval($attributes['autoplaySpeed']) : 5000;
    $background = isset($attributes['background']) ? sanitize_text_field($attributes['background']) : 'white';

    // Validate background
    if (!in_array($background, array('white', 'cream', 'transparent'))) {
        $background = 'white';
    }

    // Build query args
    $args = array(
        'post_type'      => 'testimonial',
        'posts_per_page' => $limit,
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC',
    );

    // Filter by category if specified
    if (!empty($category)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'testimonial-category',
                'field'    => 'slug',
                'terms'    => $category,
            ),
        );
    }

    $testimonials = new WP_Query($args);

    if (!$testimonials->have_posts()) {
        return '<p class="rg-testimonial-slider__empty">No testimonials found.</p>';
    }

    $unique_id = 'rg-testimonial-slider-' . uniqid();
    $slides_html = '';
    $dots_html = '';
    $index = 0;

    while ($testimonials->have_posts()) {
        $testimonials->the_post();
        $post_id = get_the_ID();

        // Get ACF fields
        $content = get_field('testimonial_content', $post_id);
        $author_link = get_field('author_link', $post_id);
        $author_line = get_field('author_line', $post_id);

        // Fallback to post content if ACF field is empty
        if (empty($content)) {
            $content = get_the_content();
        }

        // Fallback to post title for author if empty
        if (empty($author_line)) {
            $author_line = get_the_title();
        }

        $active_class = $index === 0 ? ' active' : '';

        // Build author HTML
        $author_html = '';
        if (!empty($author_line)) {
            if (!empty($author_link)) {
                $author_html = sprintf(
                    '<a href="%s" target="_blank" rel="noopener noreferrer">— %s</a>',
                    esc_url($author_link),
                    esc_html($author_line)
                );
            } else {
                $author_html = '— ' . esc_html($author_line);
            }
        }

        $slides_html .= sprintf(
            '<div class="rg-testimonial-slider__slide%s" data-index="%d">' .
                '<div class="rg-testimonial-slider__content">"%s"</div>' .
                '<div class="rg-testimonial-slider__author">%s</div>' .
            '</div>',
            $active_class,
            $index,
            esc_html(wp_strip_all_tags($content)),
            $author_html
        );

        $dots_html .= sprintf(
            '<button class="rg-testimonial-slider__dot%s" data-index="%d" aria-label="Go to slide %d"></button>',
            $active_class,
            $index,
            $index + 1
        );

        $index++;
    }

    wp_reset_postdata();

    // Only show navigation if more than one testimonial
    $nav_html = '';
    if ($index > 1) {
        $nav_html = '<div class="rg-testimonial-slider__nav">' . $dots_html . '</div>';
    }

    $output = sprintf(
        '<div class="rg-testimonial-slider rg-testimonial-slider--%s" id="%s" data-autoplay="%s" data-speed="%d">' .
            '<div class="rg-testimonial-slider__slides">%s</div>' .
            '%s' .
        '</div>',
        esc_attr($background),
        esc_attr($unique_id),
        $autoplay ? 'true' : 'false',
        $autoplay_speed,
        $slides_html,
        $nav_html
    );

    // Add inline script for this slider instance
    $output .= sprintf(
        '<script>
        (function() {
            var slider = document.getElementById("%s");
            if (!slider) return;

            var slides = slider.querySelectorAll(".rg-testimonial-slider__slide");
            var dots = slider.querySelectorAll(".rg-testimonial-slider__dot");
            var currentIndex = 0;
            var autoplay = slider.dataset.autoplay === "true";
            var speed = parseInt(slider.dataset.speed, 10) || 5000;
            var interval = null;

            function goToSlide(index) {
                slides.forEach(function(slide, i) {
                    slide.classList.toggle("active", i === index);
                });
                dots.forEach(function(dot, i) {
                    dot.classList.toggle("active", i === index);
                });
                currentIndex = index;
            }

            function nextSlide() {
                var next = (currentIndex + 1) %% slides.length;
                goToSlide(next);
            }

            function startAutoplay() {
                if (autoplay && slides.length > 1) {
                    interval = setInterval(nextSlide, speed);
                }
            }

            function stopAutoplay() {
                if (interval) {
                    clearInterval(interval);
                    interval = null;
                }
            }

            dots.forEach(function(dot, index) {
                dot.addEventListener("click", function() {
                    stopAutoplay();
                    goToSlide(index);
                    startAutoplay();
                });
            });

            slider.addEventListener("mouseenter", stopAutoplay);
            slider.addEventListener("mouseleave", startAutoplay);

            startAutoplay();
        })();
        </script>',
        esc_js($unique_id)
    );

    return $output;
}

/**
 * REST API endpoint to get testimonial categories for the editor.
 */
add_action('rest_api_init', function() {
    register_rest_route('rg/v1', '/testimonial-categories', array(
        'methods'  => 'GET',
        'callback' => function() {
            $terms = get_terms(array(
                'taxonomy'   => 'testimonial-category',
                'hide_empty' => false,
            ));

            if (is_wp_error($terms)) {
                return array();
            }

            $categories = array(
                array('value' => '', 'label' => 'All Categories')
            );

            foreach ($terms as $term) {
                $categories[] = array(
                    'value' => $term->slug,
                    'label' => $term->name,
                );
            }

            return $categories;
        },
        'permission_callback' => '__return_true',
    ));
});
