<?php
/**
 * Custom hooks for Blog Over
 *
 * @package Blog_Over
 */

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

/**
 * Output dynamic CSS from Kirki customizer settings
 */
function blog_over_customizer_dynamic_css()
{
    // Collect variables
    $primary_color = get_theme_mod('blog_over_primary_color', '#3b82f6');
    $secondary_color = get_theme_mod('blog_over_secondary_color', '#1e40af');
    $text_color = get_theme_mod('blog_over_text_color', '#334155');
    $heading_color = get_theme_mod('blog_over_heading_color', '#1e293b');

    // Top Bar 
    $topbar_bg = get_theme_mod('blog_over_topbar_bg', '#1e293b');
    $topbar_text = get_theme_mod('blog_over_topbar_text_color', '#94a3b8');
    $topbar_height = get_theme_mod('blog_over_topbar_height', 40);

    // Footer
    $footer_bg = get_theme_mod('blog_over_footer_bg_color', '#1e293b');
    $footer_text = get_theme_mod('blog_over_footer_text_color', '#94a3b8');
    $copyright_bg = get_theme_mod('blog_over_copyright_bg', '#000000');
    $copyright_text = get_theme_mod('blog_over_copyright_text_color', '#888888');

    // Start building CSS
    $css = ":root {";

    // Brand Colors
    $css .= "--blog-over-primary: {$primary_color};";
    $css .= "--blog-over-secondary: {$secondary_color};";

    // Text
    $css .= "--blog-over-text-body: {$text_color};";
    $css .= "--blog-over-heading-color: {$heading_color};";

    // Top Bar
    $css .= "--blog-over-topbar-text: {$topbar_text};";

    // Footer
    $css .= "--blog-over-footer-bg: {$footer_bg};";
    $css .= "--blog-over-footer-text: {$footer_text};";
    $css .= "--blog-over-copyright-bg: {$copyright_bg};";
    $css .= "--blog-over-copyright-text: {$copyright_text};";

    $css .= "}"; // End :root

    // Top Bar Height
    $css .= ".blog-over-topbar { min-height: {$topbar_height}px; }";

    // Top Bar Background - handle solid vs gradient
    $topbar_bg_type = get_theme_mod('blog_over_topbar_bg_type', 'solid');
    if ($topbar_bg_type === 'gradient') {
        $start = get_theme_mod('blog_over_topbar_gradient_start', '#1e293b');
        $end = get_theme_mod('blog_over_topbar_gradient_end', '#334155');
        $css .= ".blog-over-topbar { background: linear-gradient(135deg, {$start} 0%, {$end} 100%); }";
    } else {
        // Solid color
        $css .= ".blog-over-topbar { background: {$topbar_bg}; }";
    }

    // Special Case: Topbar Boxed Layout
    $topbar_width = get_theme_mod('blog_over_topbar_width', 'boxed');
    if ($topbar_width === 'boxed') {
        $css .= ".blog-over-topbar.blog-over-topbar-boxed { padding-left: 0; padding-right: 0; }";
        $css .= ".blog-over-topbar.blog-over-topbar-boxed > .blog-over-container { max-width: 1200px; margin: 0 auto; padding: 0 15px; }";
    }

    // Social icons now use primary/secondary colors from CSS variables - no custom handling needed

    // Topbar text color - apply to ALL text elements (free + Pro centered layout)
    $css .= ".blog-over-topbar-date, .blog-over-topbar-text, .blog-over-topbar-custom-text, .blog-over-topbar-centered-message, .blog-over-topbar-mobile-text { color: {$topbar_text}; }";

    // Topbar border color - must use !important to override dark mode CSS variable fallback
    $topbar_border_show = get_theme_mod('blog_over_topbar_border_show', false);
    if ($topbar_border_show) {
        $topbar_border_color = get_theme_mod('blog_over_topbar_border_color', '#334155');
        $css .= ".blog-over-topbar.blog-over-topbar-border { border-bottom-color: {$topbar_border_color} !important; }";
    }

    // Reading Progress Bar
    $enabled_css = get_theme_mod('blog_over_single_reading_progress', true);
    if (($enabled_css !== false && $enabled_css !== '0' && $enabled_css !== 0 && $enabled_css !== 'off') || is_customize_preview()) {
        $progress_color = get_theme_mod('blog_over_single_reading_progress_color', $primary_color);
        $progress_height = absint(get_theme_mod('blog_over_single_reading_progress_height', 4));
        
        $css .= ".blog-over-reading-progress { ";
        $css .= "position: fixed; top: 0; left: 0; width: 0%; z-index: 99999; ";
        $css .= "height: {$progress_height}px; background-color: {$progress_color}; ";
        $css .= "transition: width 0.1s ease-out; }";
        
        $css .= "body.admin-bar .blog-over-reading-progress { top: 32px; }";
        $css .= "@media screen and (max-width: 782px) { body.admin-bar .blog-over-reading-progress { top: 46px; } }";
    }

    // Use wp_add_inline_style for proper CSS output
    wp_add_inline_style('blog-over-style', $css);
}
add_action('wp_enqueue_scripts', 'blog_over_customizer_dynamic_css', 20);

/**
 * Render Reading Progress Bar (Single Posts)
 */
function blog_over_render_reading_progress()
{
    $enabled = get_theme_mod('blog_over_single_reading_progress', true);
    $is_single = is_single();
    $is_customizer = is_customize_preview();

    if (!is_single()) {
        return;
    }
    
    if ($enabled === false || $enabled === '0' || $enabled === 0 || $enabled === 'off' || $enabled === '') {
        return;
    }

    echo '<div class="blog-over-reading-progress" id="blog-over-reading-progress-bar"></div>';
}
add_action('wp_body_open', 'blog_over_render_reading_progress');

/**
 * Footer section hook
 */
function blog_over_footer_section()
{
    do_action('blog_over_footer_section');
}

/**
 * Add header container class based on layout
 */
function blog_over_get_container_class()
{
    $full_width = get_theme_mod('blog_over_menu_full_width', false);
    return $full_width ? 'container-fluid' : 'container';
}

/**
 * Check if sticky header is enabled
 */
function blog_over_is_sticky_header()
{
    return get_theme_mod('blog_over_sticky_enable', false);
}

/**
 * Helper to render announcement templates.
 */
function blog_over_render_announcement_bars()
{
    get_template_part('template-parts/sections/announcement');
}

/**
 * Render announcement bar above header.
 */
function blog_over_render_announcement_above_header()
{
    if (function_exists('blog_over_is_pro_active') && blog_over_is_pro_active()) {
        return; // Pro plugin handles this natively.
    }
    $position = get_theme_mod('blog_over_announcement_position', 'above-header');
    if ($position !== 'above-header' && $position !== 'fixed-top') {
        return;
    }
    blog_over_render_announcement_bars();
}
add_action('wp_body_open', 'blog_over_render_announcement_above_header', 4);

/**
 * Render announcement bar below header.
 */
function blog_over_render_announcement_below_header()
{
    if (function_exists('blog_over_is_pro_active') && blog_over_is_pro_active()) {
        return; // Pro plugin handles this natively.
    }
    if (get_theme_mod('blog_over_announcement_position', 'above-header') !== 'below-header') {
        return;
    }
    blog_over_render_announcement_bars();
}
add_action('blog_over_after_header', 'blog_over_render_announcement_below_header', 5);

/**
 * Render announcement bar in footer (for fixed bottom).
 */
function blog_over_render_announcement_footer()
{
    if (function_exists('blog_over_is_pro_active') && blog_over_is_pro_active()) {
        return; // Pro plugin handles this natively.
    }
    if (get_theme_mod('blog_over_announcement_position', 'above-header') !== 'fixed-bottom') {
        return;
    }
    blog_over_render_announcement_bars();
}
add_action('wp_footer', 'blog_over_render_announcement_footer', 5);

/**
 * Announcement partial render callback for Customizer
 */
function blog_over_render_announcement_partial()
{
    get_template_part('template-parts/sections/announcement');
}

/**
 * Render Custom Header Image
 */
function blog_over_render_custom_header()
{
    if ( ! has_header_image() ) {
        return;
    }
    get_template_part('template-parts/sections/custom-header');
}
add_action('blog_over_after_header', 'blog_over_render_custom_header', 8);

/**
 * Custom Header partial render callback for Customizer
 */
function blog_over_render_custom_header_partial()
{
    get_template_part('template-parts/sections/custom-header');
}

/**
 * Render Ticker News Section
 */
function blog_over_render_ticker()
{
    get_template_part('template-parts/sections/ticker');
}
add_action('blog_over_after_header', 'blog_over_render_ticker', 10);

/**
 * Ticker partial render callback for Customizer
 */
function blog_over_render_ticker_partial()
{
    get_template_part('template-parts/sections/ticker');
}

/**
 * Render Hero Section
 */
function blog_over_render_hero()
{
    // Check if hero is enabled globally
    $enable_hero = get_theme_mod('blog_over_enable_hero', false);
    if (!$enable_hero) {
        return;
    }

    // Get the pages where Hero should be shown
    $enable_on = get_theme_mod('blog_over_hero_enable_on', array('home', 'posts_page'));
    if (empty($enable_on)) {
        return;
    }

    $should_show = false;

    // Check each condition
    if (in_array('home', $enable_on) && is_front_page()) {
        $should_show = true;
    }
    if (in_array('posts_page', $enable_on) && is_home() && !is_front_page()) {
        $should_show = true;
    }
    if (in_array('archive', $enable_on) && (is_archive() || is_category() || is_tag() || is_author() || is_date())) {
        $should_show = true;
    }
    if (in_array('search', $enable_on) && is_search()) {
        $should_show = true;
    }
    if (in_array('post', $enable_on) && is_singular('post')) {
        $should_show = true;
    }

    if (!$should_show) {
        return;
    }

    get_template_part('template-parts/sections/hero');
}
add_action('blog_over_after_header', 'blog_over_render_hero', 20);


/**
 * Hero partial render callback for Customizer
 */
function blog_over_render_hero_partial()
{
    get_template_part('template-parts/sections/hero');
}

/**
 * Render Featured Links Section
 */
function blog_over_render_featured()
{
    // Check if featured links is enabled globally
    $enable_featured = get_theme_mod('blog_over_enable_featured_links', false);
    if (!$enable_featured) {
        return;
    }

    // Get the pages where Featured Links should be shown
    $enable_on = get_theme_mod('blog_over_featured_enable_on', array('home', 'posts_page'));
    if (empty($enable_on) || !is_array($enable_on)) {
        return;
    }

    $should_show = false;

    // Check each condition (same as Hero section)
    if (in_array('home', $enable_on) && is_front_page()) {
        $should_show = true;
    }
    if (in_array('posts_page', $enable_on) && is_home() && !is_front_page()) {
        $should_show = true;
    }
    if (in_array('archive', $enable_on) && (is_archive() || is_category() || is_tag() || is_author() || is_date())) {
        $should_show = true;
    }
    if (in_array('search', $enable_on) && is_search()) {
        $should_show = true;
    }
    if (in_array('post', $enable_on) && is_singular('post')) {
        $should_show = true;
    }

    if (!$should_show) {
        return;
    }

    get_template_part('template-parts/sections/featured');
}
add_action('blog_over_after_header', 'blog_over_render_featured', 30);

/**
 * Featured Links partial render callback for Customizer
 */
function blog_over_render_featured_partial()
{
    get_template_part('template-parts/sections/featured');
}

/**
 * Render Tabbed Magazine Section (Front Page)
 */
function blog_over_render_tabbed_magazine()
{
    if (!get_theme_mod('blog_over_tabbed_magazine_enable', false)) {
        return;
    }
    if (!is_front_page() && !is_home()) {
        return;
    }
    get_template_part('template-parts/sections/tabbed-magazine');
}
add_action('blog_over_before_footer', 'blog_over_render_tabbed_magazine', 5);

/**
 * Render Feature Story Block (Front Page)
 */
function blog_over_render_feature_story()
{
    // Feature story handles its own enable toggle internally, but we should verify the visibility logic.
    if (!get_theme_mod('blog_over_feature_story_enable', false) && !is_customize_preview()) {
        return;
    }
    
    $enable_on = get_theme_mod('blog_over_feature_story_show_on', array('home', 'blog'));
    if (!is_array($enable_on)) {
        $enable_on = array();
    }
    
    $should_show = false;

    if (in_array('home', $enable_on) && is_front_page()) {
        $should_show = true;
    }
    if (in_array('blog', $enable_on) && is_home() && !is_front_page()) {
        $should_show = true;
    }
    if (in_array('archive', $enable_on) && (is_archive() || is_category() || is_tag() || is_author() || is_date())) {
        $should_show = true;
    }
    if (in_array('single', $enable_on) && is_singular('post')) {
        $should_show = true;
    }

    if (!$should_show) {
        return;
    }
    
    echo '<div id="blog-over-feature-story-ajax-wrap">';
    get_template_part('template-parts/sections/feature-story');
    echo '</div>';
}
// Before footer, but above Tabbed Magazine (priority 5)
add_action('blog_over_before_footer', 'blog_over_render_feature_story', 2);

/**
 * Feature Story partial render callback for Customizer
 */
function blog_over_render_feature_story_partial()
{
    get_template_part('template-parts/sections/feature-story');
}

/**
 * Tabbed Magazine partial render callback for selective refresh.
 * No page guard — the Customizer preview always fires on front page context.
 */
function blog_over_render_tabbed_magazine_partial()
{
    get_template_part('template-parts/sections/tabbed-magazine');
}

/**
 * Render You Missed Section
 * Usually this is in the footer in Blogus, but hooks allow placing it anywhere.
 * We'll place it at the bottom of the main content usually, but for modularity, let's hook it before footer.
 */
function blog_over_render_missed()
{
    get_template_part('template-parts/sections/missed');
}
// Using 'wp_footer' might be too low, let's define a new hook 'blog_over_before_footer' or use 'get_footer'
// For now, let's put it at the end of the header stack for visibility, OR strictly speaking, it should be in the footer area.
// Blogus puts it in 'blog_over_footer_missed_section' likely attached to footer.
// Let's hook to 'blog_over_before_footer' if it exists, otherwise define it.
// Assuming we want it part of the front page flow, maybe priority 90 on header hook?
// Or better: Let's assume the user wants it at the bottom.
add_action('blog_over_before_footer', 'blog_over_render_missed', 10);

/**
 * Footer partial render callback for Customizer
 */
function blog_over_render_footer_partial()
{
    get_template_part('template-parts/sections/footer-widgets');
}

// =============================================
// ADVERTISING BANNER
// =============================================

/**
 * Parse a Kirki repeater checkbox value into a reliable boolean.
 *
 * Kirki repeater checkboxes may store values as boolean true/false,
 * string '1'/'0', string 'true'/'false', string 'on'/'off', or
 * integers 1/0. This helper normalises all variants.
 *
 * @param mixed $value Raw checkbox value from repeater data.
 * @return bool
 */
function blog_over_parse_checkbox($value)
{
    if (is_bool($value)) {
        return $value;
    }
    if (is_int($value)) {
        return $value === 1;
    }
    if (is_string($value)) {
        $value = strtolower(trim($value));
        return in_array($value, array('1', 'true', 'on', 'yes'), true);
    }
    return false;
}

/**
 * Check per-ad visibility (hide_homepage / hide_blog / hide_single).
 *
 * Works for both free and Pro repeater items (the free repeater
 * simply never contains these keys, so the defaults keep ads visible).
 *
 * @param array $ad The repeater item data.
 * @return bool True if allowed on the current page.
 */
function blog_over_ad_item_visible($ad)
{
    $hide_home   = isset($ad['hide_homepage']) ? blog_over_parse_checkbox($ad['hide_homepage']) : false;
    $hide_blog   = isset($ad['hide_blog'])     ? blog_over_parse_checkbox($ad['hide_blog'])     : false;
    $hide_single = isset($ad['hide_single'])   ? blog_over_parse_checkbox($ad['hide_single'])   : false;

    // Homepage (static front page or "Your latest posts" as front)
    if ($hide_home && is_front_page()) {
        return false;
    }

    // Blog / archive pages (posts page, archives, categories, tags, search)
    // When front page IS the blog ("Your latest posts"), is_home() is true.
    // Avoid double-hiding: if user only checked "blog" and front page is
    // the blog page, "hide on homepage" takes priority — so skip the blog
    // check when on the front page unless hide_home is also set.
    if ($hide_blog) {
        // Dedicated blog page (not also the front page)
        if (is_home() && !is_front_page()) {
            return false;
        }
        // Archives, search, categories, tags
        if (is_archive() || is_search()) {
            return false;
        }
    }

    // Single posts (any single post type view)
    if ($hide_single && is_single()) {
        return false;
    }

    return true;
}

// Keep backward-compat alias for external code that may call the old name.
if (!function_exists('blog_over_ad_pro_item_visible')) {
    function blog_over_ad_pro_item_visible($ad)
    {
        return blog_over_ad_item_visible($ad);
    }
}

/**
 * Render advertisement banners for a given placement.
 *
 * Free:  reads blog_over_ad_banners repeater (limited to 1 item).
 * Pro:   reads blog_over_ad_banners repeater (unlimited + extra fields).
 *
 * @param string $placement The current placement hook key (e.g. 'below-header').
 */
function blog_over_render_ads($placement)
{
    // Global enable check
    if (!get_theme_mod('blog_over_ad_banner_enable', false)) {
        // In Customizer preview, output empty wrapper for pencil icon
        if (is_customize_preview()) {
            echo '<div class="blog-over-ad-banner-wrapper blog-over-ad-placement-' . esc_attr($placement) . '"></div>';
        }
        return;
    }

    $is_pro = function_exists('blog_over_is_pro_active') && blog_over_is_pro_active();

    // Data is unified under exactly one setting key.
    $ads = get_theme_mod('blog_over_ad_banners', array());

    if (!is_array($ads) || empty($ads)) {
        return;
    }

    // Enforce limit of 1 banner for free theme on the frontend
    if (!$is_pro && count($ads) > 1) {
        $ads = array_slice($ads, 0, 1);
    }

    $has_output = false;

    foreach ($ads as $ad) {
        // Skip if placement doesn't match
        $ad_placement = isset($ad['placement']) ? $ad['placement'] : 'below-header';
        if ($ad_placement !== $placement) {
            continue;
        }

        // Per-ad visibility check (works for both free & Pro)
        if (!blog_over_ad_item_visible($ad)) {
            continue;
        }

        if (!$has_output) {
            $ad_section_width = get_theme_mod('blog_over_ad_banner_section_width', 'boxed');
            $ad_container_class = ($ad_section_width === 'full-width') ? 'blog-over-container blog-over-container-wide' : 'blog-over-container';
            
            echo '<div class="blog-over-ad-banner-wrapper blog-over-ad-placement-' . esc_attr($placement) . '">';
            echo '<div class="' . esc_attr($ad_container_class) . '">';
            $has_output = true;
        }

        get_template_part('template-parts/sections/advertisement', null, $ad);
    }

    if ($has_output) {
        echo '</div></div>';
    }
}

/**
 * Hook: Render ad banners below the header.
 */
function blog_over_render_ads_below_header()
{
    blog_over_render_ads('below-header');
}
add_action('blog_over_after_header', 'blog_over_render_ads_below_header', 5);

/**
 * Hook: Render ad banners above the footer.
 */
function blog_over_render_ads_above_footer()
{
    blog_over_render_ads('above-footer');
}
add_action('blog_over_before_footer', 'blog_over_render_ads_above_footer', 15);

/**
 * Hook: Render ad banners before the hero section.
 */
function blog_over_render_ads_before_hero()
{
    blog_over_render_ads('before-hero');
}
add_action('blog_over_after_header', 'blog_over_render_ads_before_hero', 15);

/**
 * Hook: Render ad banners before the featured section.
 */
function blog_over_render_ads_before_featured()
{
    blog_over_render_ads('before-featured');
}
add_action('blog_over_after_header', 'blog_over_render_ads_before_featured', 25);

/**
 * Hook: Render ad banners before the feature story section.
 */
function blog_over_render_ads_before_feature_story()
{
    blog_over_render_ads('before-feature-story');
}
add_action('blog_over_before_footer', 'blog_over_render_ads_before_feature_story', 1);

/**
 * Hook: Render ad banners before the tabbed magazine section.
 */
function blog_over_render_ads_before_tabbed_magazine()
{
    blog_over_render_ads('before-tabbed-magazine');
}
add_action('blog_over_before_footer', 'blog_over_render_ads_before_tabbed_magazine', 4);

/**
 * Hook: Render ad banners before the you missed section.
 */
function blog_over_render_ads_before_you_missed()
{
    blog_over_render_ads('before-you-missed');
}
add_action('blog_over_before_footer', 'blog_over_render_ads_before_you_missed', 8);

/**
 * Advertisement banner partial render callback for Customizer.
 */
function blog_over_render_ad_banner_partial()
{
    // Re-render all placements — the customizer will swap the matching wrapper
    blog_over_render_ads('below-header');
    blog_over_render_ads('before-hero');
    blog_over_render_ads('before-featured');
    blog_over_render_ads('before-feature-story');
    blog_over_render_ads('before-tabbed-magazine');
    blog_over_render_ads('before-you-missed');
    blog_over_render_ads('above-footer');
}

// =============================================
// TRENDING POSTS SECTION
// =============================================

/**
 * Render the Trending Posts section.
 * Placed after You Missed (priority 12) in the before_footer hook stack.
 */
function blog_over_render_trending()
{
    get_template_part('template-parts/sections/trending');
}
add_action('blog_over_before_footer', 'blog_over_render_trending', 12);

/**
 * Trending Posts partial render callback for Customizer selective refresh.
 */
function blog_over_render_trending_partial()
{
    get_template_part('template-parts/sections/trending');
}

// =============================================
// NEWSLETTER / CTA SECTION
// =============================================

/**
 * Render the Newsletter / CTA section.
 * Placed after Trending (priority 13) in the before_footer hook stack.
 */
function blog_over_render_newsletter()
{
    get_template_part('template-parts/sections/newsletter');
}
add_action('blog_over_before_footer', 'blog_over_render_newsletter', 13);

/**
 * Newsletter CTA partial render callback for Customizer selective refresh.
 */
function blog_over_render_newsletter_partial()
{
    get_template_part('template-parts/sections/newsletter');
}

// =============================================
// CATEGORY SHOWCASE SECTION
// =============================================

/**
 * Render the Category Showcase section.
 * Placed after Newsletter (priority 14) in the before_footer hook stack.
 */
function blog_over_render_catshowcase()
{
    get_template_part('template-parts/sections/category-showcase');
}
add_action('blog_over_before_footer', 'blog_over_render_catshowcase', 14);

/**
 * Category Showcase partial render callback for Customizer selective refresh.
 */
function blog_over_render_catshowcase_partial()
{
    get_template_part('template-parts/sections/category-showcase');
}

