<?php
/**
 * Blog List Block - Server-Side Render
 * 
 * Hybrid Layout: Dynamic Posts Loop + InnerBlocks Sidebar
 * 
 * @package Author_Website_Templates
 * @since 1.0.9
 */

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

// Extract attributes
$posts_to_show   = isset( $attributes['postsToShow'] ) ? absint( $attributes['postsToShow'] ) : 6;
$show_image      = isset( $attributes['showImage'] ) ? (bool) $attributes['showImage'] : true;
$show_excerpt    = isset( $attributes['showExcerpt'] ) ? (bool) $attributes['showExcerpt'] : true;
$read_more_text  = isset( $attributes['readMoreText'] ) ? sanitize_text_field( $attributes['readMoreText'] ) : __( 'Read More', 'author-website-templates' );

// Extract color attributes
$section_bg_color         = isset( $attributes['sectionBgColor'] ) ? sanitize_hex_color( $attributes['sectionBgColor'] ) : '';
$category_color           = isset( $attributes['categoryColor'] ) ? sanitize_hex_color( $attributes['categoryColor'] ) : '#f97316';
$title_hover_color        = isset( $attributes['titleHoverColor'] ) ? sanitize_hex_color( $attributes['titleHoverColor'] ) : '#0ea5e9';
$read_more_color          = isset( $attributes['readMoreColor'] ) ? sanitize_hex_color( $attributes['readMoreColor'] ) : '#0ea5e9';
$pagination_bg_color      = isset( $attributes['paginationBgColor'] ) ? sanitize_hex_color( $attributes['paginationBgColor'] ) : '#ffffff';
$pagination_text_color    = isset( $attributes['paginationTextColor'] ) ? sanitize_hex_color( $attributes['paginationTextColor'] ) : '#1e293b';
$pagination_hover_bg      = isset( $attributes['paginationHoverBgColor'] ) ? sanitize_hex_color( $attributes['paginationHoverBgColor'] ) : '#0ea5e9';
$pagination_hover_text    = isset( $attributes['paginationHoverTextColor'] ) ? sanitize_hex_color( $attributes['paginationHoverTextColor'] ) : '#ffffff';

// Generate unique ID for scoped CSS
$block_id = 'awt-blog-list-' . uniqid();

global $wp_query;
$use_global_query = ( is_home() || is_search() || is_category() || is_tag() || is_author() || is_date() || is_archive() );

if ( $use_global_query && $wp_query->have_posts() ) {
    $query = $wp_query;
} else {
    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => $posts_to_show,
        'post_status'    => 'publish',
        'paged'          => get_query_var('paged') ? get_query_var('paged') : 1,
    );
    $query = new WP_Query( $args );
}

?>

<!-- Dynamic Color Styles -->
<style>
    #<?php echo esc_attr( $block_id ); ?> .awt-category-link {
        color: <?php echo esc_attr( $category_color ); ?>;
    }
    
    #<?php echo esc_attr( $block_id ); ?> .awt-post-title:hover {
        color: <?php echo esc_attr( $title_hover_color ); ?> !important;
    }
    
    #<?php echo esc_attr( $block_id ); ?> .awt-read-more {
        color: <?php echo esc_attr( $read_more_color ); ?>;
    }
    
    #<?php echo esc_attr( $block_id ); ?> .awt-pagination-item {
        background-color: <?php echo esc_attr( $pagination_bg_color ); ?>;
        color: <?php echo esc_attr( $pagination_text_color ); ?>;
    }
    
    #<?php echo esc_attr( $block_id ); ?> .awt-pagination-item:hover {
        background-color: <?php echo esc_attr( $pagination_hover_bg ); ?> !important;
        color: <?php echo esc_attr( $pagination_hover_text ); ?> !important;
    }
    
    #<?php echo esc_attr( $block_id ); ?> .awt-pagination-active {
        background-color: <?php echo esc_attr( $pagination_hover_bg ); ?>;
        color: <?php echo esc_attr( $pagination_hover_text ); ?>;
    }
</style>

<section id="<?php echo esc_attr( $block_id ); ?>" class="py-24" <?php if ( $section_bg_color ) echo 'style="background-color: ' . esc_attr( $section_bg_color ) . ';"'; ?>>
    <div class="awt-container mx-auto px-6 grid grid-cols-1 lg:grid-cols-3 gap-12">
        
        <!-- Main Content - Posts Loop -->
        <div class="lg:col-span-2 space-y-12">
            <?php
            if ( $query->have_posts() ) :
                while ( $query->have_posts() ) : $query->the_post();
            ?>
                <article class="bg-white rounded-xl shadow-lg overflow-hidden transition-all duration-300 hover:shadow-2xl md:flex">
                    
                    <!-- Image -->
                    <?php if ( $show_image && has_post_thumbnail() ) : ?>
                        <a href="<?php the_permalink(); ?>" class="block md:w-2/5">
                            <?php the_post_thumbnail( 'medium_large', array(
                                'class' => 'w-full h-64 md:h-full object-cover'
                            ) ); ?>
                        </a>
                    <?php endif; ?>

                    <div class="p-6 md:p-8 <?php echo ( $show_image && has_post_thumbnail() ) ? 'md:w-3/5' : 'w-full'; ?>">

                        <!-- Category Link -->
                        <?php
                        $categories = get_the_category();
                        if ( ! empty( $categories ) ) :
                            $cat_link = get_category_link( $categories[0]->term_id );
                        ?>
                            <a href="<?php echo esc_url( $cat_link ); ?>" 
                                class="awt-category-link block font-bold uppercase text-sm mb-2 hover:underline">
                                <?php echo esc_html( $categories[0]->name ); ?>
                            </a>
                        <?php endif; ?>

                        <!-- Title Link -->
                        <a href="<?php the_permalink(); ?>">
                            <h3 class="awt-post-title text-2xl md:text-3xl font-black text-navy mb-4">
                                <?php the_title(); ?>
                            </h3>
                        </a>

                        <!-- Excerpt -->
                        <?php if ( $show_excerpt ) : ?>
                            <p class="text-navy/80 mb-6">
                                <?php echo esc_html( get_the_excerpt() ); ?>
                            </p>
                        <?php endif; ?>

                        <!-- Read More Button -->
                        <a href="<?php the_permalink(); ?>" class="awt-read-more font-bold hover:underline">
                            <?php echo esc_html( $read_more_text ); ?> &rarr;
                        </a>

                    </div>
                </article>

            <?php
                endwhile;

                // Pagination
                if ( $query->max_num_pages > 1 ) :
            ?>
                <div class="mt-12 flex justify-center">
                    <?php
                    $big = 999999999;

                    $pagination = paginate_links( array(
                        'base'        => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
                        'format'      => '?paged=%#%',
                        'total'       => $query->max_num_pages,
                        'current'     => max( 1, get_query_var( 'paged' ) ),
                        'prev_text'   => '&larr; Prev',
                        'next_text'   => 'Next &rarr;',
                        'type'        => 'array',
                    ) );

                    if ( ! empty( $pagination ) ) :
                    ?>
                        <nav class="flex gap-2">
                            <?php foreach ( $pagination as $page ) : 
                                $is_active = strpos( $page, 'current' ) !== false;

                                if ( $is_active ) {
                                    echo '<span class="awt-pagination-active px-4 py-2 rounded-lg font-bold shadow-md">'
                                        . wp_kses_post( wp_strip_all_tags( $page ) ) .
                                    '</span>';
                                } else {
                                    preg_match('/href=["\']([^"\']+)["\']/', $page, $match);
                                    $url = $match[1] ?? '#';

                                    echo '<a href="' . esc_url( $url ) . '" 
                                            class="awt-pagination-item px-4 py-2 rounded-lg border border-gray-200 shadow-sm transition-all duration-200">
                                            ' . wp_kses_post( wp_strip_all_tags( $page ) ) . '
                                        </a>';
                                }
                            endforeach; ?>
                        </nav>
                    <?php endif; ?>
                </div>

            <?php
                endif;

            else :
            ?>
                <p class="text-center text-gray-600 py-12">
                    <?php _e( 'No posts found.', 'author-website-templates' ); ?>
                </p>
            <?php
            endif;

            if ( ! $use_global_query ) {
                wp_reset_postdata();
            }
            ?>
        </div>

        <!-- Sidebar - InnerBlocks Content -->
        <aside class="lg:col-span-1 lg:sticky lg:top-32 h-fit space-y-8">
            <?php echo $content; ?>
        </aside>

    </div>
</section>