<?php
/**
 * Template part for displaying the Hero Section.
 * 
 * Unified design based on Slide Count:
 * - 1 = Large single slider
 * - 2 = Two equal column sliders
 * - 3 = Grid layout (1 large + 2 small)
 *
 * @package Blog_Over
 */

$enable_hero = get_theme_mod('blog_over_enable_hero', false);

if (!$enable_hero) {
    return;
}

// Get Slide Count setting (1, 2, or 3)
$slide_count = get_theme_mod('blog_over_hero_slide_count', '3');

// Meta display settings - sortable array
$meta_elements = get_theme_mod('blog_over_hero_meta_elements', array('author', 'date'));

// Get all slider widgets (always 3, visibility controlled by slide_count)
$slider_widgets = get_theme_mod('blog_over_hero_slider_widgets', array());

// Default widgets if none set
if (empty($slider_widgets)) {
    $slider_widgets = array(
        array('widget_title' => 'Slider 1', 'slider_height' => 500, 'category' => '', 'posts_count' => 5, 'autoplay' => true, 'autoplay_speed' => 5, 'loop' => true, 'show_arrows' => false, 'show_dots' => true, 'order' => 'latest'),
        array('widget_title' => 'Slider 2', 'slider_height' => 250, 'category' => '', 'posts_count' => 5, 'autoplay' => true, 'autoplay_speed' => 5, 'loop' => true, 'show_arrows' => false, 'show_dots' => true, 'order' => 'latest'),
        array('widget_title' => 'Slider 3', 'slider_height' => 250, 'category' => '', 'posts_count' => 5, 'autoplay' => true, 'autoplay_speed' => 5, 'loop' => true, 'show_arrows' => false, 'show_dots' => true, 'order' => 'latest'),
    );
}

// Get only the active widgets based on slide count
$active_widgets = array_slice($slider_widgets, 0, intval($slide_count));

/**
 * Helper function to render a single hero item
 */
if (!function_exists('blog_over_render_hero_item')):
function blog_over_render_hero_item($meta_elements, $is_large = true, $is_active = false, $slide_index = null)
{
    $thumb_size = $is_large ? 'blog-over-slider' : 'blog-over-medium';
    $active_class = $is_active ? ' active' : '';
    $data_index = $slide_index !== null ? ' data-index="' . esc_attr($slide_index) . '"' : '';

    // Check which elements are enabled
    $post_elements = get_theme_mod('blog_over_hero_elements', array('category', 'title', 'meta'));
    $meta_elements = get_theme_mod('blog_over_hero_meta_elements', array('author', 'date'));

    ?>
    <div class="blog-over-hero-item<?php echo esc_attr($active_class); ?>" <?php echo $data_index; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped during construction ?>>
        <?php
        // Use the_post_thumbnail() for proper ALT from media library and srcset/sizes
        the_post_thumbnail($thumb_size, array('class' => 'blog-over-hero-image'));
        
        if (!empty($post_elements) && is_array($post_elements)) :
        ?>
        <div class="blog-over-hero-content">
            <?php
            foreach ($post_elements as $element):
                if ($element === 'category'):
                    ?>
                    <span class="blog-over-category-badge">
                        <?php blog_over_first_category(); ?>
                    </span>
                    <?php
                elseif ($element === 'title'):
                    ?>
                    <h<?php echo $is_large ? '2' : '3'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded values ?> class="blog-over-hero-title">
                        <a href="<?php the_permalink(); ?>">
                            <?php the_title(); ?>
                        </a>
                    </h<?php echo $is_large ? '2' : '3'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded values ?>>
                    <?php
                elseif ($element === 'meta' && !empty($meta_elements) && is_array($meta_elements)):
                    ?>
                    <div class="blog-over-hero-meta">
                        <?php foreach ($meta_elements as $meta): ?>
                            <?php if ($meta === 'date'): ?>
                                <a href="<?php the_permalink(); ?>" class="blog-over-date">
                                    <i class="far fa-calendar-alt"></i>
                                    <?php echo esc_html(get_the_date()); ?>
                                </a>
                            <?php elseif ($meta === 'author'): ?>
                                <a href="<?php echo esc_url(get_author_posts_url(get_the_author_meta('ID'))); ?>" class="blog-over-author">
                                    <i class="far fa-user"></i>
                                    <?php echo esc_html(get_the_author()); ?>
                                </a>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                    <?php
                endif;
            endforeach;
            ?>
        </div>
        <?php endif; ?>
        <a href="<?php the_permalink(); ?>" class="blog-over-hero-link-overlay"></a>
    </div>
    <?php
}
endif;

/**
 * Helper function to render slider navigation arrows
 */
if (!function_exists('blog_over_render_slider_arrows')):
function blog_over_render_slider_arrows()
{
    ?>
    <button class="blog-over-slider-arrow blog-over-slider-prev" aria-label="<?php esc_attr_e('Previous', 'blog-over'); ?>">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="28" height="28">
            <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" fill="currentColor" />
        </svg>
    </button>
    <button class="blog-over-slider-arrow blog-over-slider-next" aria-label="<?php esc_attr_e('Next', 'blog-over'); ?>">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="28" height="28">
            <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" fill="currentColor" />
        </svg>
    </button>
    <?php
}
endif;

/**
 * Helper function to render slider dots
 */
if (!function_exists('blog_over_render_slider_dots')):
function blog_over_render_slider_dots($count)
{
    ?>
    <div class="blog-over-slider-dots">
        <?php for ($i = 0; $i < $count; $i++): ?>
            <button class="blog-over-slider-dot <?php echo esc_attr($i === 0 ? 'active' : ''); ?>"
                data-index="<?php echo (int) $i; ?>"
                aria-label="<?php printf(esc_attr__('Slide %d', 'blog-over'), $i + 1); ?>"></button>
        <?php endfor; ?>
    </div>
    <?php
}
endif;

/**
 * Helper function to render slider thumbnails (Pro)
 */
if (!function_exists('blog_over_render_slider_thumbnails')):
function blog_over_render_slider_thumbnails($widget_query)
{
    ?>
    <div class="blog-over-slider-thumbnails">
        <?php 
        $slide_index = 0;
        while ($widget_query->have_posts()):
            $widget_query->the_post();
            ?>
            <button class="blog-over-slider-thumb <?php echo esc_attr($slide_index === 0 ? 'active' : ''); ?>" data-index="<?php echo (int) $slide_index; ?>">
                <?php the_post_thumbnail('thumbnail'); ?>
                <span class="blog-over-thumb-title"><?php echo wp_trim_words(get_the_title(), 4); ?></span>
            </button>
            <?php
            $slide_index++;
        endwhile;
        wp_reset_postdata();
        ?>
    </div>
    <?php
}
endif;

/**
 * Helper function to render a single slider widget
 */
if (!function_exists('blog_over_render_slider_widget')):
function blog_over_render_slider_widget($widget, $widget_index, $is_large, $meta_elements, $slide_effect = 'slide')
{
    // Get widget settings with defaults
    $w_category = isset($widget['category']) ? $widget['category'] : '';
    $w_posts_count = isset($widget['posts_count']) ? intval($widget['posts_count']) : 5;
    $w_autoplay = isset($widget['autoplay']) ? $widget['autoplay'] : true;
    $w_autoplay_speed = isset($widget['autoplay_speed']) ? intval($widget['autoplay_speed']) : 5;
    $w_loop = isset($widget['loop']) ? $widget['loop'] : true;
    $w_show_arrows = isset($widget['show_arrows']) ? $widget['show_arrows'] : false;
    $w_show_dots = isset($widget['show_dots']) ? $widget['show_dots'] : true;
    $w_order = isset($widget['order']) ? $widget['order'] : 'latest';
    $w_effect = $slide_effect;
    $w_show_progressbar = isset($widget['show_progressbar']) ? $widget['show_progressbar'] : false;

    // Build query args
    $query_args = array(
        'post_type' => 'post',
        'posts_per_page' => $w_posts_count,
        'ignore_sticky_posts' => true,
    );

    if (!empty($w_category)) {
        if (is_numeric($w_category)) {
            // Backward compatibility: old installs may still store a numeric ID.
            $query_args['cat'] = intval($w_category);
        } else {
            // Slug-based query (preferred).
            $query_args['category_name'] = sanitize_title($w_category);
        }
    }

    if ($w_order === 'random') {
        $query_args['orderby'] = 'rand';
    }

    $widget_query = new WP_Query($query_args);

    if ($widget_query->have_posts()):
        $pro_class = '';
        if (defined('BLOG_OVER_PRO_VERSION')) {
            if ($is_large) {
                $pagination_style = get_theme_mod('blog_over_hero_pagination_style', 'dots');
                if ($w_show_dots && $pagination_style === 'thumbnails') {
                    $pro_class .= ' has-thumbnails';
                } elseif ($w_show_dots && $pagination_style === 'fraction') {
                    $pro_class .= ' has-fraction';
                }
            }

            // Navigation arrow style — applies to ALL sliders
            $nav_style = get_theme_mod('blog_over_hero_nav_style', 'default');
            if ($nav_style !== 'default') {
                $pro_class .= ' nav-style-' . sanitize_html_class($nav_style);
            }

            // Progressbar — per slider
            if ($w_show_progressbar) {
                $pro_class .= ' has-progressbar';
            }
        }
        $slot_class = ($is_large ? 'blog-over-hero-large' : 'blog-over-hero-small') . $pro_class;
        ?>
        <div class="blog-over-hero-slot blog-over-hero-slot-<?php echo (int) $widget_index; ?> <?php echo esc_attr($slot_class); ?>"
            data-slot-number="<?php echo (int) $widget_index; ?>">
            <div class="blog-over-hero-slider blog-over-slot-slider <?php echo esc_attr(!$is_large ? 'blog-over-mini-slider' : ''); ?>"
                data-slot="<?php echo (int) $widget_index; ?>"
                data-autoplay="<?php echo esc_attr($w_autoplay ? 'true' : 'false'); ?>"
                data-speed="<?php echo esc_attr($w_autoplay_speed * 1000); ?>"
                data-loop="<?php echo esc_attr($w_loop ? 'true' : 'false'); ?>" data-pause-hover="true"
                data-effect="<?php echo esc_attr($w_effect); ?>">
                <div class="blog-over-slider-track">
                    <?php
                    $slide_index = 0;
                    while ($widget_query->have_posts()):
                        $widget_query->the_post();
                        blog_over_render_hero_item($meta_elements, $is_large, $slide_index === 0, $slide_index);
                        $slide_index++;
                    endwhile;
                    wp_reset_postdata();
                    ?>
                </div>

                <?php if ($w_show_arrows && $widget_query->post_count > 1): ?>
                    <?php blog_over_render_slider_arrows(); ?>
                <?php endif; ?>

                <?php if ($w_show_dots && $widget_query->post_count > 1): ?>
                    <?php 
                    $pagination_style = get_theme_mod('blog_over_hero_pagination_style', 'dots');
                    if ($is_large && defined('BLOG_OVER_PRO_VERSION')) {
                        if ($pagination_style === 'thumbnails') {
                            blog_over_render_slider_thumbnails($widget_query);
                        } elseif ($pagination_style === 'fraction') {
                            $total = intval($widget_query->post_count);
                            echo '<div class="blog-over-slider-fraction">';
                            echo '<span class="current">01</span>';
                            echo '<span class="separator"></span>';
                            echo '<span class="total">' . str_pad($total, 2, '0', STR_PAD_LEFT) . '</span>';
                            echo '</div>';
                        } else {
                            blog_over_render_slider_dots($widget_query->post_count);
                        }
                    } else {
                        blog_over_render_slider_dots($widget_query->post_count);
                    }
                    ?>
                <?php endif; ?>

                <?php
                // Progressbar — per slider (works on ALL sliders)
                if (defined('BLOG_OVER_PRO_VERSION') && $w_show_progressbar && $widget_query->post_count > 1) {
                    echo '<div class="blog-over-slider-progressbar"><div class="blog-over-progress-fill"></div></div>';
                }
                ?>
            </div>
        </div>
        <?php
    endif;
}
endif;

// Get container setting
$hero_container = get_theme_mod('blog_over_hero_container', 'container');
$container_class = ($hero_container === 'full-width') ? 'blog-over-container blog-over-container-wide' : 'blog-over-container';

// Get global slide effect setting
$slide_effect = get_theme_mod('blog_over_hero_slide_effect', 'slide');

// Get overlay toggle
$show_overlay = get_theme_mod('blog_over_hero_overlay', true);
$overlay_class = $show_overlay ? '' : ' hero-no-overlay';
?>

<div class="blog-over-hero-wrapper hero-slide-count-<?php echo esc_attr($slide_count); echo esc_attr($overlay_class); ?>">
    <div class="<?php echo esc_attr($container_class); ?>">
        <?php if ($slide_count === '1'): ?>
            <!-- SLIDE COUNT 1: Large Single Slider -->
            <?php
            $widget = $active_widgets[0];
            blog_over_render_slider_widget($widget, 1, true, $meta_elements, $slide_effect);
            ?>

        <?php elseif ($slide_count === '2'): ?>
            <!-- SLIDE COUNT 2: Two Equal Sliders -->
            <div class="blog-over-hero-grid">
                <?php
                $widget_index = 0;
                foreach ($active_widgets as $widget):
                    $widget_index++;
                    blog_over_render_slider_widget($widget, $widget_index, true, $meta_elements, $slide_effect);
                endforeach;
                ?>
            </div>

        <?php elseif ($slide_count === '3'): ?>
            <!-- SLIDE COUNT 3: Grid Layout (1 Large + 2 Small) -->
            <div class="blog-over-hero-grid">
                <?php
                $widget_index = 0;
                foreach ($active_widgets as $widget):
                    $widget_index++;
                    $is_large = ($widget_index === 1);
                    blog_over_render_slider_widget($widget, $widget_index, $is_large, $meta_elements, $slide_effect);
                endforeach;
                ?>
            </div>

        <?php elseif ($slide_count === '4'): ?>
            <!-- SLIDE COUNT 4: 1 Large + 3 Small (4-column magazine grid) -->
            <div class="blog-over-hero-grid">
                <?php
                $widget_index = 0;
                foreach ($active_widgets as $widget):
                    $widget_index++;
                    $is_large = ($widget_index === 1);
                    blog_over_render_slider_widget($widget, $widget_index, $is_large, $meta_elements, $slide_effect);
                endforeach;
                ?>
            </div>

        <?php elseif ($slide_count === '5'): ?>
            <!-- SLIDE COUNT 5: 1 Featured + 4 Equal Column Layout -->
            <div class="blog-over-hero-grid">
                <?php
                $widget_index = 0;
                foreach ($active_widgets as $widget):
                    $widget_index++;
                    $is_large = ($widget_index === 1);
                    blog_over_render_slider_widget($widget, $widget_index, $is_large, $meta_elements, $slide_effect);
                endforeach;
                ?>
            </div>

        <?php endif; ?>
    </div>
</div>
