<?php
/**
 * Blog Helper Functions
 * 
 * Helper functions for componentizing the Blog Details block rendering.
 *
 * @package Author_Website_Templates
 */

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

/**
 * Get Related Posts based on common categories or tags
 *
 * @param int $post_id Current Post ID.
 * @return WP_Query Query result for related posts.
 */
function rswpthemes_awt_get_related_posts($post_id)
{
    $taxs = array();

    // Get categories
    $categories = get_the_category($post_id);
    if ($categories) {
        foreach ($categories as $category) {
            $taxs[] = array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $category->slug,
            );
        }
    }

    // Get tags
    $tags = get_the_tags($post_id);
    if ($tags) {
        foreach ($tags as $tag) {
            $taxs[] = array(
                'taxonomy' => 'post_tag',
                'field' => 'slug',
                'terms' => $tag->slug,
            );
        }
    }

    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'post__not_in' => array($post_id),
        'orderby' => 'rand',
    );

    if (!empty($taxs)) {
        $args['tax_query'] = array_merge(array('relation' => 'OR'), $taxs);
    }

    return new WP_Query($args);
}

/**
 * Custom Comment List Callback
 *
 * Renders comments to match the specific design in blog-single.html.
 *
 * @param object $comment The comment object.
 * @param array  $args    Arguments.
 * @param int    $depth   Depth.
 */
function rswpthemes_awt_custom_comment_list($comment, $args, $depth)
{
    $GLOBALS['comment'] = $comment;

    // Cycle background colors for avatars to match design
    $bg_colors = ['bg-yellow-sun/20', 'bg-coral-pop/20', 'bg-blue-sky/20'];
    $bg_class = $bg_colors[$comment->comment_ID % 3];

    $tag = ('div' === $args['style']) ? 'div' : 'li';

    // Outer wrapper classes
    $classes = 'comment-body flex space-x-4 mb-6';
    ?>
    <<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class($classes, $comment); ?>>

        <div class="flex-shrink-0">
            <?php
            if (0 != $args['avatar_size']) {
                // Get avatar with base classes
                $avatar_url = get_avatar_url($comment, array('size' => $args['avatar_size']));
                // Render custom image tag to ensure classes are exact
                printf(
                    '<img src="%s" alt="%s" class="w-12 h-12 md:w-16 md:h-16 rounded-full %s flex-shrink-0 object-cover" />',
                    esc_url($avatar_url),
                    esc_attr(get_comment_author($comment)),
                    esc_attr($bg_class)
                );
            }
            ?>
        </div>

        <div class="bg-white p-5 rounded-xl shadow-sm w-full">
            <div class="flex justify-between items-center mb-1">
                <span class="font-black text-navy text-lg">
                    <?php echo get_comment_author_link($comment); ?>
                </span>
                <span class="text-sm text-navy/60">
                    <?php
                    printf(
                        /* translators: 1: date, 2: time */
                        esc_html__('%1$s', 'author-website-templates'),
                        get_comment_date('M j, Y')
                    );
                    ?>
                </span>
            </div>

            <?php if ('0' == $comment->comment_approved): ?>
                <p class="text-sm text-yellow-600 mb-2">
                    <?php esc_html_e('Your comment is awaiting moderation.', 'author-website-templates'); ?>
                </p>
            <?php endif; ?>

            <div class="text-navy/80 prose prose-sm max-w-none">
                <?php comment_text(); ?>
            </div>

            <?php
            comment_reply_link(array_merge($args, array(
                'depth' => $depth,
                'max_depth' => $args['max_depth'],
                'before' => '<div class="mt-2">',
                'after' => '</div>',
                'add_below' => 'comment',
                'reply_text' => __('Reply', 'author-website-templates'),
                // Custom class for the anchor itself is hard to inject via args alone in some WP versions without 'class' arg, 
                // but usually 'login_text' etc. 
                // We'll rely on global CSS or specific selector if plugin allows.
                // However, we can use a filter or `rswpthemes_awt_comment_reply_link` if needed.
                // For now, let's assume the theme CSS targets .comment-reply-link.
            )));
            ?>
        </div>
        <!-- Closing tag handled by Walker -->
        <?php
}

/**
 * Get Comment Form Arguments
 *
 * Returns the arguments array for comment_form() to match the design.
 *
 * @return array Arguments for comment_form().
 */
function rswpthemes_awt_get_comment_form_args()
{
    $commenter = wp_get_current_commenter();
    $req = get_option('require_name_email');
    $aria_req = ($req ? " aria-required='true'" : '');

    $fields = array(
        'author' => '<div class="mb-6"><label for="author" class="block mb-2 font-bold">' . esc_html__('Name', 'author-website-templates') . ($req ? ' <span class="required">*</span>' : '') . '</label>' .
            '<input id="author" name="author" type="text" value="' . esc_attr($commenter['comment_author']) . '" size="30"' . $aria_req . ' class="w-full p-4 rounded-lg bg-cream border-2 border-transparent text-navy placeholder:text-navy/50 focus:outline-none focus:ring-2 focus:ring-blue-sky transition-all" /></div>',

        'email' => '<div class="mb-6"><label for="email" class="block mb-2 font-bold">' . esc_html__('Email', 'author-website-templates') . ($req ? ' <span class="required">*</span>' : '') . '</label>' .
            '<input id="email" name="email" type="text" value="' . esc_attr($commenter['comment_author_email']) . '" size="30"' . $aria_req . ' class="w-full p-4 rounded-lg bg-cream border-2 border-transparent text-navy placeholder:text-navy/50 focus:outline-none focus:ring-2 focus:ring-blue-sky transition-all" /></div>',

        'url' => '<div class="mb-6"><label for="url" class="block mb-2 font-bold">' . esc_html__('Website', 'author-website-templates') . '</label>' .
            '<input id="url" name="url" type="text" value="' . esc_attr($commenter['comment_author_url']) . '" size="30" class="w-full p-4 rounded-lg bg-cream border-2 border-transparent text-navy placeholder:text-navy/50 focus:outline-none focus:ring-2 focus:ring-blue-sky transition-all" /></div>',
    );

    return array(
        'fields' => $fields,
        'comment_field' => '<div class="mb-6"><label for="comment" class="block mb-2 font-bold">' . esc_html__('Your Comment', 'author-website-templates') . '</label><textarea id="comment" name="comment" rows="5" class="w-full p-4 rounded-lg bg-cream border-2 border-transparent text-navy placeholder:text-navy/50 focus:outline-none focus:ring-2 focus:ring-blue-sky transition-all" aria-required="true"></textarea></div>',
        'submit_button' => '<button name="%1$s" type="submit" id="%2$s" class="%3$s">%4$s</button>',
        'class_submit' => 'btn-fun btn-yellow cursor-pointer px-8 py-3 rounded-full font-extrabold uppercase bg-yellow-400 text-navy shadow-lg',
        'label_submit' => __('Post Your Comment', 'author-website-templates'),
        'title_reply' => '', // Title should be handled by the template or passed in args if needed, but usually we output custom title before form
        'title_reply_to' => '',
        'comment_notes_before' => '',
        'class_container' => 'comment-respond font-sans',
    );
}
