<?php
defined('ABSPATH') || exit;

function ripro_get_post_corner_badges($post_id, $show_vip = true) {
    $post_id = absint($post_id);
    $html = '';

    if (is_sticky($post_id)) {
        $html .= '<span class="ri-corner-badge ri-corner-sticky">' . esc_html__('置顶', 'ripro') . '</span>';
    }

    $prices = get_post_price_data($post_id);
    $default_price = isset($prices['default']) ? (float) $prices['default'] : 0;
    $raw_price = get_post_meta($post_id, 'cao_price', true);
    $is_free_post = (is_numeric($raw_price) && (float) $raw_price <= 0) || (post_is_pay($post_id) && $default_price <= 0) || ripro_post_in_free_category($post_id);

    if ($show_vip && is_site_shop() && post_is_pay($post_id) && post_is_vip_pay($post_id)) {
        $html .= '<span class="ri-corner-badge ri-corner-vip">' . esc_html__('VIP', 'ripro') . '</span>';
    } elseif ($is_free_post) {
        $html .= '<span class="ri-corner-badge ri-corner-free">' . esc_html__('免费', 'ripro') . '</span>';
    }

    return $html;
}

function ripro_post_in_free_category($post_id) {
    $terms = get_the_terms($post_id, 'category');
    $check_terms = array();

    if (!empty($terms) && !is_wp_error($terms)) {
        foreach ($terms as $term) {
            $check_terms[$term->term_id] = $term;
            $ancestor_ids = get_ancestors($term->term_id, 'category');
            foreach ($ancestor_ids as $ancestor_id) {
                $ancestor = get_term($ancestor_id, 'category');
                if (!is_wp_error($ancestor) && !empty($ancestor)) {
                    $check_terms[$ancestor->term_id] = $ancestor;
                }
            }
        }
    }

    if (is_category()) {
        $queried = get_queried_object();
        if (!empty($queried->term_id)) {
            $check_terms[$queried->term_id] = $queried;
            $ancestor_ids = get_ancestors($queried->term_id, 'category');
            foreach ($ancestor_ids as $ancestor_id) {
                $ancestor = get_term($ancestor_id, 'category');
                if (!is_wp_error($ancestor) && !empty($ancestor)) {
                    $check_terms[$ancestor->term_id] = $ancestor;
                }
            }
        }
    }

    foreach ($check_terms as $term) {
        $slug = strtolower((string) $term->slug);
        $name = (string) $term->name;
        if (strpos($slug, 'free') !== false || strpos($name, '免费') !== false || strpos($slug, '%e5%85%8d%e8%b4%b9') !== false) {
            return true;
        }
    }

    return false;
}

function ripro_archive_post_can_add_cart($post_id) {
    $post_id = absint($post_id);

    if (!is_site_shop() || !post_is_pay($post_id)) {
        return false;
    }

    $user_id = get_current_user_id();
    if (get_user_pay_post_status($user_id, $post_id)) {
        return false;
    }

    $price = get_user_pay_post_price($user_id, $post_id);
    if ($price === false || (float) $price <= 0) {
        return false;
    }

    return true;
}

function ripro_archive_action_buttons($post_id, $meta_options = array()) {
    $post_id = absint($post_id);
    $meta_options = is_array($meta_options) ? $meta_options : array();
    $html = '';

    if (in_array('cart_action', $meta_options, true) && ripro_archive_post_can_add_cart($post_id)) {
        $normal_html = '<img class="ri-cart-img" src="' . esc_url(get_template_directory_uri() . '/assets/img/shopcar.svg') . '" alt="" aria-hidden="true">';
        $added_html = '<img class="ri-cart-img" src="' . esc_url(get_template_directory_uri() . '/assets/img/cart_in_on.svg') . '" alt="" aria-hidden="true">';
        $html .= sprintf(
            '<button type="button" class="ri-archive-action ri-archive-cart-action ri-add-cart" data-id="%1$d" data-normal-html="%2$s" data-added-html="%3$s" title="%4$s">%5$s</button>',
            $post_id,
            esc_attr($normal_html),
            esc_attr($added_html),
            esc_attr__('加入购物车', 'ripro'),
            $normal_html
        );
    }

    if (in_array('fav_action', $meta_options, true)) {
        $user_id = get_current_user_id();
        $is_fav = $user_id ? zb_is_post_fav($user_id, $post_id) : false;
        $html .= sprintf(
            '<button type="button" class="ri-archive-action ri-archive-fav-btn%6$s" data-id="%1$d" data-is="%2$d" title="%3$s"%7$s><i class="%4$s"></i><em>%5$s</em></button>',
            $post_id,
            $is_fav ? 0 : 1,
            $is_fav ? esc_attr__('已收藏', 'ripro') : esc_attr__('加入收藏', 'ripro'),
            $is_fav ? 'fas fa-star' : 'far fa-star',
            $is_fav ? esc_html__('已收藏', 'ripro') : esc_html__('收藏', 'ripro'),
            $is_fav ? ' is-added disabled' : '',
            $is_fav ? ' disabled aria-disabled="true"' : ''
        );
    }

    return empty($html) ? '' : '<span class="ri-archive-actions">' . $html . '</span>';
}

function ripro_ap_get_adjacent_question($question_id, $direction = 'prev') {
    $question_id = absint($question_id);
    $question = get_post($question_id);

    if (!$question || 'question' !== $question->post_type) {
        return null;
    }

    $is_next = 'next' === $direction;
    $date_rule = array('inclusive' => false);
    $date_rule[$is_next ? 'after' : 'before'] = $question->post_date;

    $query = new WP_Query(array(
        'post_type'           => 'question',
        'post_status'         => 'publish',
        'posts_per_page'      => 1,
        'ignore_sticky_posts' => true,
        'no_found_rows'       => true,
        'post__not_in'        => array($question_id),
        'orderby'             => 'date',
        'order'               => $is_next ? 'ASC' : 'DESC',
        'date_query'          => array($date_rule),
    ));

    if (!$query->have_posts()) {
        wp_reset_postdata();
        return null;
    }

    $post = $query->posts[0];
    wp_reset_postdata();
    return $post;
}

function ripro_ap_question_navigation($question_id = 0) {
    $question_id = absint($question_id ? $question_id : get_the_ID());
    $prev = ripro_ap_get_adjacent_question($question_id, 'prev');
    $next = ripro_ap_get_adjacent_question($question_id, 'next');

    if (!$prev && !$next) {
        return;
    }
    ?>
    <nav class="ap-modown-question-nav" aria-label="<?php esc_attr_e('问题导航', 'ripro'); ?>">
        <div class="ap-modown-question-nav-edge">
            <?php if ($prev) : ?>
                <a href="<?php echo esc_url(get_permalink($prev)); ?>" aria-label="<?php esc_attr_e('上一个问题', 'ripro'); ?>"><i class="fas fa-arrow-left"></i></a>
            <?php endif; ?>
        </div>
        <div class="ap-modown-question-nav-links">
            <?php if ($prev) : ?>
                <a class="ap-modown-question-nav-item" href="<?php echo esc_url(get_permalink($prev)); ?>">
                    <span><?php esc_html_e('上一篇', 'ripro'); ?></span>
                    <strong><?php echo esc_html(get_the_title($prev)); ?></strong>
                </a>
            <?php endif; ?>
            <?php if ($next) : ?>
                <a class="ap-modown-question-nav-item" href="<?php echo esc_url(get_permalink($next)); ?>">
                    <span><?php esc_html_e('下一篇', 'ripro'); ?></span>
                    <strong><?php echo esc_html(get_the_title($next)); ?></strong>
                </a>
            <?php endif; ?>
        </div>
        <div class="ap-modown-question-nav-edge">
            <?php if ($next) : ?>
                <a href="<?php echo esc_url(get_permalink($next)); ?>" aria-label="<?php esc_attr_e('下一个问题', 'ripro'); ?>"><i class="fas fa-arrow-right"></i></a>
            <?php endif; ?>
        </div>
    </nav>
    <?php
}

function ripro_ap_questions_jump_pagination() {
    if (!function_exists('anspress') || empty(anspress()->questions->max_num_pages)) {
        return;
    }

    $total = absint(anspress()->questions->max_num_pages);
    if ($total <= 1) {
        return;
    }

    if (is_front_page()) {
        $current = absint(get_query_var('page'));
    } elseif (get_query_var('ap_paged')) {
        $current = absint(get_query_var('ap_paged'));
    } else {
        $current = absint(get_query_var('paged'));
    }

    $current = max(1, min($total, $current ? $current : 1));
    $first_url = get_pagenum_link(1);
    $prev_url = get_pagenum_link(max(1, $current - 1));
    $next_url = get_pagenum_link(min($total, $current + 1));
    $last_url = get_pagenum_link($total);
    ?>
    <nav class="ap-modown-pagination" data-total="<?php echo esc_attr($total); ?>" aria-label="<?php esc_attr_e('问题分页', 'ripro'); ?>">
        <a class="ap-page-btn<?php echo 1 === $current ? ' disabled' : ''; ?>" href="<?php echo esc_url($first_url); ?>"><?php esc_html_e('首页', 'ripro'); ?></a>
        <a class="ap-page-btn<?php echo 1 === $current ? ' disabled' : ''; ?>" href="<?php echo esc_url($prev_url); ?>"><?php esc_html_e('上一篇', 'ripro'); ?></a>
        <select class="ap-page-select" aria-label="<?php esc_attr_e('选择页码', 'ripro'); ?>">
            <?php for ($page = 1; $page <= $total; $page++) : ?>
                <option value="<?php echo esc_url(get_pagenum_link($page)); ?>"<?php selected($page, $current); ?>><?php echo esc_html(sprintf(__('第 %d 页', 'ripro'), $page)); ?></option>
            <?php endfor; ?>
        </select>
        <span class="ap-page-jump">
            <input type="number" min="1" max="<?php echo esc_attr($total); ?>" value="<?php echo esc_attr($current); ?>" aria-label="<?php esc_attr_e('输入页码', 'ripro'); ?>">
            <button type="button"><?php esc_html_e('跳转', 'ripro'); ?></button>
        </span>
        <a class="ap-page-btn<?php echo $current === $total ? ' disabled' : ''; ?>" href="<?php echo esc_url($next_url); ?>"><?php esc_html_e('下一篇', 'ripro'); ?></a>
        <a class="ap-page-btn<?php echo $current === $total ? ' disabled' : ''; ?>" href="<?php echo esc_url($last_url); ?>"><?php esc_html_e('末页', 'ripro'); ?></a>
    </nav>
    <script>
    jQuery(function($){
        $('.ap-modown-pagination').each(function(){
            var $pager = $(this);
            var total = parseInt($pager.data('total'), 10) || 1;
            var currentUrl = $pager.find('.ap-page-select option:selected').val() || window.location.href;
            var pageUrl = function(page) {
                var selected = $pager.find('.ap-page-select option').filter(function(){
                    return parseInt($(this).text().replace(/\D/g, ''), 10) === page;
                }).val();
                return selected || currentUrl;
            };

            $pager.on('change', '.ap-page-select', function(){
                if (this.value) window.location.href = this.value;
            });

            $pager.on('click', '.ap-page-jump button', function(){
                var page = parseInt($pager.find('.ap-page-jump input').val(), 10);
                if (!page) return;
                page = Math.max(1, Math.min(total, page));
                window.location.href = pageUrl(page);
            });

            $pager.on('keydown', '.ap-page-jump input', function(e){
                if (e.key === 'Enter') {
                    e.preventDefault();
                    $pager.find('.ap-page-jump button').trigger('click');
                }
            });
        });
    });
    </script>
    <?php
}

function ripro_get_comment_purchased_badge($comment) {
    if (empty($comment->user_id) || empty($comment->comment_post_ID) || !class_exists('ZB_Shop')) {
        return '';
    }

    $post_id = absint($comment->comment_post_ID);
    if (!is_site_shop() || !post_is_pay($post_id)) {
        return '';
    }

    $status = ZB_Shop::get_pay_post_status(absint($comment->user_id), $post_id);
    if (!$status) {
        return '';
    }

    return ' <span class="ri-comment-bought">' . esc_html__('已购买', 'ripro') . '</span>';
}

function ripro_archive_actions_footer_script() {
    if (is_admin()) {
        return;
    }
    ?>
    <script>
    jQuery(function($){
        var archiveFavLogin = <?php echo is_user_logged_in() ? 'false' : 'true'; ?>;
        var archiveFavLoginHtml = '<div class="ri-fav-login-popup"><h5><?php echo esc_js(__('请先登录', 'ripro')); ?></h5><p><?php echo esc_js(__('登录或注册后才能收藏资源。', 'ripro')); ?></p><div class="ri-fav-login-actions"><a rel="nofollow noopener noreferrer" class="login-btn btn btn-danger" href="<?php echo esc_url(wp_login_url(get_current_url())); ?>"><?php echo esc_js(__('登录', 'ripro')); ?></a><?php if (is_site_user_register()) : ?><a rel="nofollow noopener noreferrer" class="login-btn btn btn-light" href="<?php echo esc_url(wp_registration_url()); ?>"><?php echo esc_js(__('注册', 'ripro')); ?></a><?php endif; ?></div></div>';

        $('body').on('click', '.ri-archive-fav-btn:not(.disabled)', function(e){
            e.preventDefault();
            var $btn = $(this);
            var id = parseInt($btn.data('id'), 10);
            if (!id) return;

            if (archiveFavLogin) {
                if (window.ri && ri.popup) {
                    ri.popup(archiveFavLoginHtml, 320, true);
                } else {
                    window.location.href = '<?php echo esc_url(wp_login_url(get_current_url())); ?>';
                }
                return;
            }

            $.post(zb.ajax_url, {
                action: 'zb_add_fav_post',
                nonce: zb.ajax_nonce,
                post_id: id,
                is_add: 1
            }, function(res){
                if (res && res.status == 1) {
                    $btn.addClass('is-added disabled')
                        .prop('disabled', true)
                        .attr('aria-disabled', 'true')
                        .attr('title', '<?php echo esc_js(__('已收藏', 'ripro')); ?>')
                        .data('is', 0)
                        .html('<i class="fas fa-star"></i><em><?php echo esc_js(__('已收藏', 'ripro')); ?></em>');
                }

                if (window.ri && ri.notice) {
                    ri.notice(res && res.msg ? res.msg : '<?php echo esc_js(__('操作完成', 'ripro')); ?>');
                }
            }, 'json').fail(function(xhr){
                if (window.ri && ri.notice) {
                    ri.notice(xhr.responseText || '<?php echo esc_js(__('收藏失败，请稍后重试', 'ripro')); ?>');
                }
            });
        });
    });
    </script>
    <?php
}
add_action('wp_footer', 'ripro_archive_actions_footer_script', 35);
