<?php
/**
 * Enqueue child styles.
 */
function child_enqueue_styles() {
    wp_enqueue_style( 'child-theme', get_stylesheet_directory_uri() . '/style.css', array(), 100 );
}

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles' );

// Register a Scroll Down Shortcode
function bw_scroll_down_shortcode() {
    return '<div class="bw-scroll-down">
                <a href="#start">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="40" height="40" fill="currentColor">
                        <path d="M12 16.5l-7-7 1.41-1.41L12 13.67l5.59-5.58L19 9.5l-7 7z"/>
                    </svg>
                </a>
            </div>';
}
add_shortcode('bw_scroll_down', 'bw_scroll_down_shortcode');


function bw_enqueue_scripts() {
    wp_enqueue_script('bw-scroll-down', get_stylesheet_directory_uri() . '/js/scroll-down.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'bw_enqueue_scripts');



/**
 * Force update term counts for gallery-category taxonomy.
 */
function update_gallery_category_counts() {
    $taxonomy = 'gallery-category';
    $terms = get_terms(array('taxonomy' => $taxonomy, 'hide_empty' => false));
    foreach ($terms as $term) {
        wp_update_term_count_now(array($term->term_id), $taxonomy);
    }
}
add_action('admin_init', 'update_gallery_category_counts');

/**
 * Shortcode for Filterable Gallery with Lightbox
 */
function bw_filterable_gallery($atts) {
    $atts = shortcode_atts(array(
        'columns' => 3, 
        'thumb_size' => 350 
    ), $atts, 'bw_gallery');

    // Get all media categories in gallery-category taxonomy
    $categories = get_terms(array(
        'taxonomy' => 'gallery-category',
        'hide_empty' => false, // Set to false to ensure all terms are loaded
    ));

    ob_start();
    ?>

    <div id="gallery-filters">
        <button class="filter-button" data-filter="all">All</button>
        <?php foreach ($categories as $category) : ?>
            <button class="filter-button" data-filter="<?php echo esc_attr($category->slug); ?>">
                <?php echo esc_html($category->name); ?>
            </button>
        <?php endforeach; ?>
    </div>

    <div id="gallery-items" style="grid-template-columns: repeat(<?php echo intval($atts['columns']); ?>, 1fr);">
        <?php
        $media_items = get_posts(array(
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'gallery-category',
                    'field' => 'slug',
                    'terms' => wp_list_pluck($categories, 'slug'),
                ),
            ),
        ));

        foreach ($media_items as $item) :
            $item_categories = wp_get_post_terms($item->ID, 'gallery-category');
            $item_category_slugs = join(' ', wp_list_pluck($item_categories, 'slug'));
            $full_image_url = wp_get_attachment_image_url($item->ID, 'full'); 
            $image_title = get_the_title($item->ID);
            ?>
            <div class="gallery-item" data-category="<?php echo esc_attr($item_category_slugs); ?>">
                <a href="<?php echo esc_url($full_image_url); ?>" class="lightbox-link" data-title="<?php echo esc_attr($image_title); ?>">
                    <?php echo wp_get_attachment_image($item->ID, array($atts['thumb_size'], $atts['thumb_size']), false, array('style' => 'aspect-ratio: 1/1; object-fit: cover; width: 100%;')); ?>
                </a>
            </div>
        <?php endforeach; ?>
    </div>

    <style>
        #gallery-filters { text-align: center; margin-bottom: 20px; }
        .filter-button { cursor: pointer; padding: 10px 20px; margin: 5px; transition: all 0.3s ease; }
        #gallery-items { display: grid; gap: 15px; }
        .gallery-item img { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; transition: transform 0.3s ease; }
        
        .lightbox-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            justify-content: center;
            align-items: center;
            z-index: 9999;
            flex-direction: column;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .lightbox-overlay.show { display: flex; opacity: 1; }
        .lightbox-image { max-width: 90%; max-height: 80%; margin-bottom: 15px; transition: all 0.3s ease; }
        .lightbox-title { color: #fff; text-align: center; font-size: 18px; }
        
        .lightbox-arrow { position: absolute; top: 50%; transform: translateY(-50%); color: #fff; font-size: 30px; cursor: pointer; user-select: none; transition: all 0.3s ease; }
        .lightbox-arrow.left { left: 20px; }
        .lightbox-arrow.right { right: 20px; }
        .lightbox-close { position: absolute; top: 20px; right: 20px; color: #fff; font-size: 30px; cursor: pointer; transition: all 0.3s ease; }
    </style>

    <div class="lightbox-overlay" id="lightbox-overlay">
        <span class="lightbox-arrow left" id="lightbox-prev">&#10094;</span>
        <img src="" alt="Lightbox Image" class="lightbox-image" id="lightbox-image">
        <div class="lightbox-title" id="lightbox-title"></div>
        <span class="lightbox-arrow right" id="lightbox-next">&#10095;</span>
        <span class="lightbox-close" id="lightbox-close">&#10005;</span>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var filterButtons = document.querySelectorAll('.filter-button');
            var galleryItems = document.querySelectorAll('.gallery-item');
            var lightboxOverlay = document.getElementById('lightbox-overlay');
            var lightboxImage = document.getElementById('lightbox-image');
            var lightboxTitle = document.getElementById('lightbox-title');
            var currentIndex = -1;
            var lightboxLinks = Array.from(document.querySelectorAll('.lightbox-link'));

            function disableScroll() { document.body.style.overflow = 'hidden'; }
            function enableScroll() { document.body.style.overflow = ''; }

            filterButtons.forEach(function (button) {
                button.addEventListener('click', function () {
                    var filter = this.getAttribute('data-filter');
                    galleryItems.forEach(function (item) {
                        if (filter === 'all' || item.getAttribute('data-category').includes(filter)) {
                            item.style.display = 'inline-block';
                        } else {
                            item.style.display = 'none';
                        }
                    });
                });
            });

            lightboxLinks.forEach(function (link, index) {
                link.addEventListener('click', function (event) {
                    event.preventDefault();
                    currentIndex = index;
                    openLightbox(link);
                });
            });

            function openLightbox(link) {
                lightboxImage.src = link.href;
                lightboxTitle.textContent = link.getAttribute('data-title');
                lightboxOverlay.classList.add('show');
                disableScroll();
            }

            document.getElementById('lightbox-next').addEventListener('click', function () {
                currentIndex = (currentIndex + 1) % lightboxLinks.length;
                openLightbox(lightboxLinks[currentIndex]);
            });
            document.getElementById('lightbox-prev').addEventListener('click', function () {
                currentIndex = (currentIndex - 1 + lightboxLinks.length) % lightboxLinks.length;
                openLightbox(lightboxLinks[currentIndex]);
            });

            function closeLightbox() {
                lightboxOverlay.classList.remove('show');
                lightboxImage.src = '';
                enableScroll();
            }
            document.getElementById('lightbox-close').addEventListener('click', closeLightbox);
            lightboxOverlay.addEventListener('click', function (e) {
                if (e.target === lightboxOverlay) closeLightbox();
            });
        });
    </script>
    <?php

    return ob_get_clean();
}
add_shortcode('bw_gallery', 'bw_filterable_gallery');

// Dineplan Booking Shortcode
// Usage: [bw_dineplan key="6Rh8r9H2"]
function bw_dineplan_shortcode($atts) {
    // Parse the attributes and set a default key as a fallback
    $atts = shortcode_atts(
        array(
            'key' => '', // Specify the data key for Dineplan
        ),
        $atts
    );

    // Ensure the key is provided
    if (empty($atts['key'])) {
        return '<p style="color: red;">Error: Please provide a valid Dineplan key using the "key" attribute.</p>';
    }

    // HTML for the button and Dineplan script
    $output = '
    <div class="wp-block-kadence-advancedbtn kb-buttons-wrap dineplan"><a href="javascript:void(0)" data-key="' . esc_attr($atts['key']) . '" data-partner="" class="dineplan-widget-link kb-button kt-button button kb-btn5103_40edb3-db kt-btn-size-standard kt-btn-width-type-auto kb-btn-global-inherit kt-btn-has-text-true kt-btn-has-svg-false wp-block-button__link wp-block-kadence-singlebtn">
        <span class="kt-btn-inner-text">Book Now</span>
    </a></div>
    <script src="https://www.dineplan.com/resources/dineplan.widget.min.js"></script>
    <script type="text/javascript">
        Dineplan.key = "' . esc_js($atts['key']) . '";
    </script>
    ';

    // Return the HTML for the frontend
    return $output;
}
add_shortcode('bw_dineplan', 'bw_dineplan_shortcode');

// Optional: Comments to Remember Keys
/*
Key Reference:
- Parallel23: 6Rh8r9H2
- 72west: XvyRfTYs (But maybe wrong because it returns "Si Si")
*/