<?php
/**
 * Plugin Name: BW Gallery Slider Block
 * Description: Custom gallery slider block that mimics the old theshoreclub theme gallery.
 * Version: 1.0.0
 * Author: Bowden Works
 */

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

// Load debugging tools
include_once __DIR__ . '/debug.php';

/**
 * Register the block
 */
function bw_register_gallery_slider_block() {
    // Register block script
    wp_register_script(
        'bw-gallery-slider-block',
        get_stylesheet_directory_uri() . '/blocks/bw-gallery-slider/block.js',
        array('wp-blocks', 'wp-element', 'wp-editor', 'wp-components'),
        filemtime(get_stylesheet_directory() . '/blocks/bw-gallery-slider/block.js')
    );
    
    // Register block editor style
    wp_register_style(
        'bw-gallery-slider-block-editor',
        get_stylesheet_directory_uri() . '/blocks/bw-gallery-slider/editor.css',
        array(),
        filemtime(get_stylesheet_directory() . '/blocks/bw-gallery-slider/editor.css')
    );
    
    // Register block front-end style
    wp_register_style(
        'bw-gallery-slider-block',
        get_stylesheet_directory_uri() . '/blocks/bw-gallery-slider/style.css',
        array(),
        filemtime(get_stylesheet_directory() . '/blocks/bw-gallery-slider/style.css')
    );
    
    // Register Slick slider scripts and styles
    wp_register_script(
        'bw-slick-js',
        get_stylesheet_directory_uri() . '/blocks/bw-gallery-slider/slick/slick.min.js',
        array('jquery'),
        '1.8.1',
        true
    );
    
    wp_register_style(
        'bw-slick-css',
        get_stylesheet_directory_uri() . '/blocks/bw-gallery-slider/slick/slick.css',
        array(),
        '1.8.1'
    );
    
    wp_register_style(
        'bw-slick-theme-css',
        get_stylesheet_directory_uri() . '/blocks/bw-gallery-slider/slick/slick-theme.css',
        array('bw-slick-css'),
        '1.8.1'
    );
    
    // Register custom gallery slider script
    wp_register_script(
        'bw-gallery-slider-js',
        get_stylesheet_directory_uri() . '/blocks/bw-gallery-slider/gallery-slider.js',
        array('jquery', 'bw-slick-js'),
        filemtime(get_stylesheet_directory() . '/blocks/bw-gallery-slider/gallery-slider.js'),
        true
    );

    // Register the block
    register_block_type('bw/gallery-slider', array(
        'editor_script' => 'bw-gallery-slider-block',
        'editor_style' => 'bw-gallery-slider-block-editor',
        'style' => 'bw-gallery-slider-block',
        'render_callback' => 'bw_gallery_slider_block_render',
        'attributes' => array(
            'images' => array(
                'type' => 'array',
                'default' => array()
            )
        )
    ));
}

// Enqueue necessary frontend assets
function bw_enqueue_gallery_assets() {
    if (!is_admin()) {
        wp_enqueue_script('jquery');
        wp_enqueue_script('bw-slick-js');
        wp_enqueue_script('bw-gallery-slider-js');
        wp_enqueue_style('bw-slick-css');
        wp_enqueue_style('bw-slick-theme-css');
    }
}
add_action('wp_enqueue_scripts', 'bw_enqueue_gallery_assets');
add_action('init', 'bw_register_gallery_slider_block');

/**
 * Render the block
 */
function bw_gallery_slider_block_render($attributes) {
    // We'll rebuild the front-end code based on user instructions
    
    // Debug information for development
    $debug = '';
    if (current_user_can('administrator') && isset($_GET['debug']) && $_GET['debug'] === 'gallery') {
        $debug .= '<div style="background: #f1f1f1; padding: 10px; margin: 10px 0; border: 1px solid #ccc;">';
        $debug .= '<h4>Debug Information</h4>';
        $debug .= '<pre>' . esc_html(print_r($attributes, true)) . '</pre>';
        $debug .= '</div>';
    }
    
    // Get images array from attributes
    $images = isset($attributes['images']) ? $attributes['images'] : array();
    $gallery_count = count($images);
    
    if ($gallery_count < 2) {
        return $debug . '<div class="bw-gallery-slider-empty">Add at least 2 images to display the gallery slider.</div>';
    }
    
    // Create a unique ID for this slider instance
    $slider_id = 'bw-gallery-slider-' . uniqid();
    
    // Start building the output with the main container
    $output = '<div id="' . $slider_id . '" class="bw-gallery-slider">
        <div class="bw-gallery-slider-container">';
    
    // Main slider (80% width)
    $output .= '<div class="bw-gallery-main">';
    
    // Add each slide to the main slider
    foreach ($images as $index => $image) {
        $image_url = '';
        
        if (isset($image['id']) && !empty($image['id'])) {
            $image_url = wp_get_attachment_image_url($image['id'], 'full');
        }
        
        if (empty($image_url) && isset($image['url'])) {
            $image_url = $image['url'];
        }
        
        if (!empty($image_url)) {
            $output .= '<div><div class="slide" style="background-image: url(\'' . esc_url($image_url) . '\');"></div></div>';
        }
    }
    
    $output .= '</div>'; // End main slider
    
    // Side content (20% width) - next slide + indicators
    $output .= '<div class="bw-gallery-side">';
    
    // Next slide preview with fixed arrow overlay
    $output .= '<div class="bw-gallery-next-outer">
        <div class="bw-gallery-next">';
    
    // Add each slide to the next slider (will only show one at a time) - always show next image
    foreach ($images as $index => $image) {
        $image_url = '';
        $next_index = ($index + 1) % count($images); // Get the next image index with wrapping
        $next_image = $images[$next_index];
        
        if (isset($next_image['id']) && !empty($next_image['id'])) {
            $image_url = wp_get_attachment_image_url($next_image['id'], 'full');
        }
        
        if (empty($image_url) && isset($next_image['url'])) {
            $image_url = $next_image['url'];
        }
        
        if (!empty($image_url)) {
            $output .= '<div><div class="slide" style="background-image: url(\'' . esc_url($image_url) . '\');"></div></div>';
        }
    }
    
    $output .= '</div>'; // End next slider
    
    // Add fixed arrow overlay that stays in place
    $output .= '<div class="bw-gallery-next-arrow">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            <path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
        </svg>
    </div>';
    
    $output .= '</div>'; // End next-outer container
    
    // Indicators (numbers)
    $output .= '<div class="bw-gallery-indicators">';
    
    // Max indicators to show individual numbers for
    $max_indicators = 7;
    
    // Show individual numbered indicators up to the max
    for ($i = 0; $i < min(count($images), $max_indicators); $i++) {
        $number = str_pad($i + 1, 2, '0', STR_PAD_LEFT);
        $output .= '<div class="bw-gallery-indicator" data-slide="' . $i . '">' . $number . '</div>';
    }
    
    // If more than max indicators, add "»" at the end
    if (count($images) > $max_indicators) {
        $output .= '<div class="bw-gallery-indicator more-indicator" data-slide="' . $max_indicators . '">&raquo;</div>';
    }
    
    $output .= '</div>'; // End indicators
    
    $output .= '</div>'; // End side content
    
    // Mobile navigation (only visible on small screens)
    $output .= '<div class="bw-gallery-mobile-nav">
        <div class="bw-gallery-mobile-indicators">';
    
    for ($i = 0; $i < count($images); $i++) {
        $output .= '<div class="bw-gallery-mobile-indicator" data-slide="' . $i . '"></div>';
    }
    
    $output .= '</div>
    </div>';
    
    // Close main containers
    $output .= '</div>
    </div>';
    
    // Add initialization script
    $output .= '<script type="text/javascript">
        jQuery(document).ready(function($){
            // Wait a short moment to ensure Kadence rows are fully rendered
            setTimeout(function() {
                // Init main slider
                var $mainSlider = $("#' . $slider_id . ' .bw-gallery-main");
                var $nextSlider = $("#' . $slider_id . ' .bw-gallery-next");
                var $indicators = $("#' . $slider_id . ' .bw-gallery-indicator");
                var $mobileIndicators = $("#' . $slider_id . ' .bw-gallery-mobile-indicator");
                
            // Initialize main slider
            $mainSlider.slick({
                slidesToShow: 1,
                slidesToScroll: 1,
                arrows: false, // No arrows on main slider on desktop
                fade: false, // Changed from true to false to enable slide animation
                cssEase: "ease",
                speed: 700,
                autoplay: true, // Enable autoplay
                autoplaySpeed: 5000, // 5 seconds between slides
                infinite: true, // Enable looping
                rtl: false, // Ensure left to right animation
                asNavFor: "#' . $slider_id . ' .bw-gallery-next",
                responsive: [{
                    breakpoint: 768,
                    settings: {
                        arrows: true, // Show arrows only on mobile
                        prevArrow: "<div class=\'slick-prev\'><svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\'><path d=\'M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z\'/></svg></div>",
                        nextArrow: "<div class=\'slick-next\'><svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\'><path d=\'M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z\'/></svg></div>",
                        adaptiveHeight: true,
                        dots: false, // No dots on mobile
                        autoplay: true, // Keep autoplay on mobile
                        autoplaySpeed: 5000
                    }
                }]
            });
            
            // Initialize next preview slider
            $nextSlider.slick({
                slidesToShow: 1,
                slidesToScroll: 1,
                arrows: false,
                fade: false, // Changed from true to false to match the main slider animation
                cssEase: "ease",
                draggable: false,
                infinite: true, // Enable looping
                rtl: false, // Ensure left to right animation
                speed: 700, // Match main slider speed for synchronization
                asNavFor: "#' . $slider_id . ' .bw-gallery-main"
            });
            
            // Click events for the next preview
            $("#' . $slider_id . ' .bw-gallery-next-arrow").on("click", function(e){
                e.preventDefault();
                e.stopPropagation();
                $mainSlider.slick("slickNext");
                console.log("Next arrow clicked"); // Debug message
            });
            
            // Update indicators
            $mainSlider.on("afterChange", function(event, slick, currentSlide){
                $indicators.removeClass("active");
                
                // Calculate which indicator to activate
                const maxIndicators = 7;
                
                if (currentSlide < maxIndicators) {
                    // Activate the numbered indicator if within range
                    $indicators.eq(currentSlide).addClass("active");
                } else {
                    // Activate the "»" indicator if beyond numbered range
                    $(".bw-gallery-indicator.more-indicator").addClass("active");
                }
                
                $mobileIndicators.removeClass("active");
                $mobileIndicators.eq(currentSlide).addClass("active");
            });
            
            // Make first indicators active
            $indicators.first().addClass("active");
            $mobileIndicators.first().addClass("active");
            
            // Click on indicators
            $indicators.on("click", function(){
                var slideIndex = $(this).data("slide");
                $mainSlider.slick("slickGoTo", slideIndex);
                
                // Handle more-indicator special case
                if ($(this).hasClass("more-indicator")) {
                    console.log("More indicator clicked, going to slide: " + slideIndex);
                }
            });
            
            // Click on mobile indicators
            $mobileIndicators.on("click", function(){
                var slideIndex = $(this).data("slide");
                $mainSlider.slick("slickGoTo", slideIndex);
            });
            }, 100); // End setTimeout - wait 100ms for everything to render properly
        });
    </script>';
    
    return $debug . $output;
}

/**
 * Add block category for Bowden Works
 */
function bw_block_categories($categories, $editor_context) {
    return array_merge(
        $categories,
        array(
            array(
                'slug' => 'bw-blocks',
                'title' => __('Bowden Works Blocks', 'kadence-child'),
            ),
        )
    );
}

// WordPress 5.8+ uses block_categories_all
if (function_exists('wp_get_block_categories')) {
    add_filter('block_categories_all', 'bw_block_categories', 10, 2);
} else {
    // Backwards compatibility
    add_filter('block_categories', 'bw_block_categories', 10, 2);
}