<?php
/**
 * Blog Helper Functions
 *
 * @package Pawfect
 */

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

/**
 * Get blog content ordering
 */
function pawfect_get_blog_content_ordering() {
    // Default configuration with visibility states
    $default_config = array(
        'meta-one' => array('order' => 0, 'visible' => true),
        'title'    => array('order' => 1, 'visible' => true),
        'meta-two' => array('order' => 2, 'visible' => true),
        'image'    => array('order' => 3, 'visible' => true),
        'content'  => array('order' => 4, 'visible' => true),
    );

    // Get the current configuration from theme mod
    $raw_config = get_theme_mod('pawfect_blog_content_ordering', $default_config);

    // Handle JSON string decoding if needed
    if (is_string($raw_config)) {
        $current_config = json_decode($raw_config, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            // If JSON decode fails, use default
            $current_config = $default_config;
        }
    } else {
        $current_config = $raw_config;
    }



    // Handle backward compatibility - convert old format to new format
    if (is_array($current_config) && !empty($current_config)) {
        // Check if it's the old format (simple array of element IDs)
        $first_value = reset($current_config);
        if (!is_array($first_value)) {
            // Convert old format to new format
            $new_config = array();
            foreach ($current_config as $index => $element_id) {
                $new_config[$element_id] = array('order' => $index, 'visible' => true);
            }
            $current_config = $new_config;
        }
    } else {
        $current_config = $default_config;
    }

    // Filter out invisible elements and sort by order
    $visible_elements = array();
    foreach ($current_config as $element_id => $config) {
        if (isset($config['visible']) && $config['visible']) {
            $visible_elements[$element_id] = $config;
        }
    }

    // Sort by order
    uasort($visible_elements, function($a, $b) {
        return $a['order'] - $b['order'];
    });

    // Return just the element IDs in the correct order
    $final_order = array_keys($visible_elements);

    // Fallback: If no visible elements, return default order to prevent empty blog posts
    if (empty($final_order)) {
        $final_order = array('meta-one', 'title', 'meta-two', 'image', 'content');
    }

    return $final_order;
}



/**
 * Get blog layout for archive pages
 */
function pawfect_get_archive_blog_layout() {
    return get_theme_mod('pawfect_archive_blog_pages_layout', 'pawfect_right_sidebar');
}

/**
 * Get blog layout for single pages
 */
function pawfect_get_single_blog_layout() {
    return get_theme_mod('pawfect_single_blog_pages_layout', 'pawfect_right_sidebar');
}

/**
 * Check if current page should have sidebar
 */
function pawfect_has_sidebar() {
    if (is_single()) {
        $layout = pawfect_get_single_blog_layout();
    } else {
        $layout = pawfect_get_archive_blog_layout();
    }
    
    return ($layout !== 'pawfect_no_sidebar');
}

/**
 * Get sidebar position
 */
function pawfect_get_sidebar_position() {
    if (is_single()) {
        $layout = pawfect_get_single_blog_layout();
    } else {
        $layout = pawfect_get_archive_blog_layout();
    }
    
    if ($layout === 'pawfect_left_sidebar') {
        return 'left';
    } elseif ($layout === 'pawfect_right_sidebar') {
        return 'right';
    }
    
    return 'none';
}

/**
 * Get main content classes based on layout
 */
function pawfect_get_main_content_classes() {
    $classes = array('pawfect-main-content');
    
    if (pawfect_has_sidebar()) {
        $position = pawfect_get_sidebar_position();
        if ($position === 'left') {
            $classes[] = 'pawfect-has-left-sidebar';
        } else {
            $classes[] = 'pawfect-has-right-sidebar';
        }
    } else {
        $classes[] = 'pawfect-no-sidebar';
    }
    
    return implode(' ', $classes);
}

/**
 * Render blog post element based on content ordering
 */
function pawfect_render_blog_post_element($element, $post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    switch ($element) {
        case 'meta-one':
            pawfect_render_post_meta_one($post_id);
            break;
            
        case 'title':
            pawfect_render_post_title($post_id);
            break;
            
        case 'meta-two':
            pawfect_render_post_meta_two($post_id);
            break;
            
        case 'image':
            pawfect_render_post_image($post_id);
            break;
            
        case 'content':
            pawfect_render_post_content($post_id);
            break;
    }
}

/**
 * Render post meta one (date, author)
 */
function pawfect_render_post_meta_one($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }

    // Skip meta display on single posts if page header is enabled (to avoid duplication)
    if (is_single() && !get_theme_mod('pawfect_page_header_disabled', false)) {
        return; // Meta is shown in page header instead
    }

    if (is_single()) {
        ?>
        <div class="pawfect-post-meta-one pawfect-flex pawfect-flex-wrap pawfect-items-center pawfect-gap-4 pawfect-text-sm pawfect-text-gray-500 pawfect-mb-4">
            <span class="pawfect-post-date pawfect-flex pawfect-items-center pawfect-gap-2">
                <svg class="pawfect-w-4 pawfect-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                </svg>
                <?php echo esc_html( get_the_date('', $post_id) ); ?>
            </span>

            <span class="pawfect-post-author pawfect-flex pawfect-items-center pawfect-gap-2">
                <svg class="pawfect-w-4 pawfect-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                </svg>
                <?php echo esc_html( get_the_author_meta('display_name', get_post_field('post_author', $post_id)) ); ?>
            </span>
        </div>
        <?php
    } else {
        ?>
       
            <div class="pawfect-post-meta-one pawfect-flex pawfect-flex-wrap pawfect-items-center pawfect-gap-4 pawfect-text-sm pawfect-text-gray-500 pawfect-mb-4">
                <span class="pawfect-post-date pawfect-flex pawfect-items-center pawfect-gap-2">
                    <svg class="pawfect-w-4 pawfect-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                    </svg>
                    <?php echo esc_html( get_the_date('', $post_id) ); ?>
                </span>

                <span class="pawfect-post-author pawfect-flex pawfect-items-center pawfect-gap-2">
                    <svg class="pawfect-w-4 pawfect-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                    </svg>
                    <?php echo esc_html( get_the_author_meta('display_name', get_post_field('post_author', $post_id)) ); ?>
                </span>
            </div>
        
        <?php
    }
}

/**
 * Render post title
 */
function pawfect_render_post_title($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }

    // Skip title display on single posts if page header is enabled (to avoid duplication)
    if (is_single() && !get_theme_mod('pawfect_page_header_disabled', false)) {
        return; // Title is shown in page header instead
    }

    if (is_single()) {
        ?>
        <h1 class="pawfect-post-title pawfect-text-3xl md:pawfect-text-4xl pawfect-font-bold pawfect-text-gray-900 pawfect-leading-tight pawfect-mb-6">
            <?php echo esc_html( get_the_title($post_id) ); ?>
        </h1>
        <?php
    } else {
        ?>
      
            <h2 class="pawfect-post-title pawfect-text-xl md:pawfect-text-2xl pawfect-font-bold pawfect-text-gray-900 pawfect-leading-tight pawfect-mb-4">
                <a href="<?php echo esc_url( get_permalink($post_id) ); ?>" class="pawfect-text-gray-900 hover:pawfect-text-pawfect-primary pawfect-transition-colors pawfect-duration-300">
                    <?php echo esc_html( get_the_title($post_id) ); ?>
                </a>
            </h2>
       
        <?php
    }
}

/**
 * Render post meta two (categories, tags)
 */
function pawfect_render_post_meta_two($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }

    $categories = get_the_category($post_id);
    $comments_count = get_comments_number($post_id);

    if ($categories || $comments_count):
        $wrapper_class = is_single() ? '' : 'pawfect-px-6';
        ?>
        <div class="">
            <div class="pawfect-post-meta-two pawfect-flex pawfect-flex-wrap pawfect-items-center pawfect-gap-4 pawfect-text-sm pawfect-text-gray-500 pawfect-mb-4">
                <?php if ($categories): ?>
                    <span class="pawfect-post-categories pawfect-flex pawfect-items-center pawfect-gap-2">
                        <svg class="pawfect-w-4 pawfect-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                        </svg>
                        <?php
                        $category_links = array();
                        foreach ($categories as $category) {
                            $category_links[] = '<a href="' . esc_url( get_category_link($category->term_id) ) . '" class="hover:pawfect-text-pawfect-primary pawfect-transition-colors">' . esc_html($category->name) . '</a>';
                        }
                        echo wp_kses_post( implode(', ', $category_links) );
                        ?>
                    </span>
                <?php endif; ?>

                <?php if ($comments_count): ?>
                    <span class="pawfect-post-comments pawfect-flex pawfect-items-center pawfect-gap-2">
                        <svg class="pawfect-w-4 pawfect-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                        </svg>
                        <a href="<?php echo esc_url( get_comments_link($post_id) ); ?>" class="hover:pawfect-text-pawfect-primary pawfect-transition-colors">
                            <?php
                            if ($comments_count == 1) {
                                echo '1 ' . esc_html__('Comment', 'pawfect');
                            } else {
                                echo absint( $comments_count ) . ' ' . esc_html__('Comments', 'pawfect');
                            }
                            ?>
                        </a>
                    </span>
                <?php endif; ?>
            </div>
        </div>
    <?php endif;
}

/**
 * Render post featured image
 */
function pawfect_render_post_image($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }

    if (has_post_thumbnail($post_id)):
        $categories = get_the_category($post_id);
        $cat_label = !empty($categories) ? $categories[0]->name : '';
        ?>
        <div class="pawfect-post-featured-image pawfect-relative pawfect-mb-6 pawfect-overflow-hidden pawfect-aspect-[4/3] pawfect-rounded-xl">
            <?php if (is_single()): ?>
                <?php echo wp_kses_post( get_the_post_thumbnail($post_id, 'large', array('class' => 'pawfect-w-full pawfect-h-full pawfect-object-cover')) ); ?>
            <?php else: ?>
                <a href="<?php echo esc_url( get_permalink($post_id) ); ?>" class=" pawfect-relative">
                    <?php echo wp_kses_post( get_the_post_thumbnail($post_id, 'medium_large', array('class' => 'pawfect-w-full pawfect-h-full pawfect-object-cover pawfect-transition-all pawfect-duration-700 group-hover:pawfect-scale-110')) ); ?>

                  


                    <!-- Read More Icon -->
                    <div class="pawfect-absolute pawfect-bottom-4 pawfect-right-4 pawfect-opacity-0 pawfect-transform pawfect-scale-75 pawfect-transition-all pawfect-duration-300 group-hover:pawfect-opacity-100 group-hover:pawfect-scale-100 pawfect-z-20">
                        <div class="pawfect-w-10 pawfect-h-10 pawfect-bg-white pawfect-bg-opacity-90 pawfect-backdrop-blur-sm pawfect-rounded-full pawfect-flex pawfect-items-center pawfect-justify-center pawfect-shadow-lg">
                            <svg class="pawfect-w-5 pawfect-h-5 pawfect-text-pawfect-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"></path>
                            </svg>
                        </div>
                    </div>
                </a>
            <?php endif; ?>
        </div>
    <?php endif;
}

/**
 * Render post content/excerpt
 */
function pawfect_render_post_content($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }

    if (is_single()): ?>
        <div class="pawfect-post-content pawfect-prose pawfect-prose-lg pawfect-max-w-none pawfect-mb-8">
            <?php echo apply_filters('the_content', get_post_field('post_content', $post_id)); ?>
        </div>
    <?php else: ?>
        
            <div class="pawfect-post-excerpt pawfect-text-gray-600 pawfect-leading-relaxed pawfect-mb-6">
                <?php
                $excerpt = get_the_excerpt($post_id);
                if ($excerpt) {
                    echo wp_kses_post( $excerpt );
                } else {
                    echo esc_html( wp_trim_words(get_post_field('post_content', $post_id), 25, '...') );
                }
                ?>
            </div>
            <div class="pawfect-read-more">
                <a href="<?php echo esc_url( get_permalink($post_id) ); ?>" class="pawfect-inline-flex pawfect-items-center pawfect-gap-2 pawfect-text-pawfect-primary  pawfect-font-medium pawfect-transition-colors pawfect-duration-300">
                    <?php esc_html_e('Read More', 'pawfect'); ?>
                    <svg class="pawfect-w-4 pawfect-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                    </svg>
                </a>
            </div>
       
    <?php endif;
}
