<?php
/**
 * Template part for displaying the footer widget areas.
 *
 * Used by both footer.php and the Customizer selective refresh callback.
 *
 * @package Blog_Over
 */

if (!defined('ABSPATH')) {
    exit;
}

$footer_widgets_enable = get_theme_mod('blog_over_footer_widgets_enable', true);

if (!$footer_widgets_enable && !is_customize_preview()) {
    return;
}

$columns = absint(get_theme_mod('blog_over_footer_columns', 3));
$columns = max(1, min(4, $columns));

// Check if any of the visible widget areas have content.
$has_widgets = false;
// In Customizer preview, we always check all 4 to ensure they are available
$check_limit = is_customize_preview() ? 4 : $columns;

for ($i = 1; $i <= $check_limit; $i++) {
    if (is_active_sidebar('footer-' . $i)) {
        $has_widgets = true;
        break;
    }
}

// In Customizer preview, always render so widgets can be added to empty areas
if (!$has_widgets && !is_customize_preview()) {
    return;
}

$footer_section_width = get_theme_mod('blog_over_footer_section_width', 'boxed');
$footer_container_class = ('full-width' === $footer_section_width)
    ? 'blog-over-container blog-over-container-wide'
    : 'blog-over-container';

// Hide wrapper if disabled but in preview
$wrapper_style = (!$footer_widgets_enable) ? 'style="display:none;"' : '';
?>

<div class="footer-widgets" role="complementary" aria-label="<?php esc_attr_e('Footer Widgets', 'blog-over'); ?>" <?php echo $wrapper_style; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded style attribute ?>>
    <div class="<?php echo esc_attr($footer_container_class); ?>">
        <div class="footer-widgets-grid footer-columns-<?php echo esc_attr($columns); ?>">

            <?php
            // Always render 4 slots in customizer to ensure they are detected,
            // but hide the ones that shouldn't be visible based on column setting.
            $render_limit = is_customize_preview() ? 4 : $columns;

            for ($i = 1; $i <= $render_limit; $i++):
                // Verify if this column is active based on settings
                $is_active_column = ($i <= $columns);
                $column_style = (!$is_active_column) ? 'style="display:none;"' : '';

                if (is_active_sidebar('footer-' . $i) || is_customize_preview()):
                    ?>
                    <div class="footer-widget footer-widget-<?php echo esc_attr($i); ?>" <?php echo $column_style; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded style attribute ?>>
                        <?php dynamic_sidebar('footer-' . $i); ?>
                    </div>
                <?php endif; ?>
            <?php endfor; ?>

        </div>
    </div>
</div>