/**handles:kenit-style**/
<?php get_header(); ?>

<?php if (have_posts()) : while (have_posts()) : the_post();
    if (function_exists('_set_views')) {
        _set_views(get_the_ID());
    }
?>

<div class="newest-videos row">
    <div class="yolo-player-adbox">
        <div class="ad-160x600 ad-desktop">
            <script type="text/javascript" data-cfasync="false" async src="https://poweredby.jads.co/js/jads.js"></script>
            <ins id="1099689" data-width="160" data-height="612"></ins>
            <script type="text/javascript" data-cfasync="false" async>(adsbyjuicy = window.adsbyjuicy || []).push({'adzone':1099689});</script>
        </div>

        <div class="content detail">
            <div class="post-info-bar">
                <?php
                    // Display Categories
                    $categories = get_the_category($post->ID);
                    if ($categories) {
                        foreach($categories as $individual_category) {
                            echo '<a href="' . esc_url(https://asiangay.tv/wp-content/themes/yolotube-mod-v2/get_category_link($individual_category->term_id)) . '">' . esc_html($individual_category->cat_name) . '</a><span class="separator">|</span>';
                        }
                    }

                    // Display Tags
                    $tags = get_the_tags($post->ID);
                    if ($tags) {
                        foreach($tags as $individual_tag) {
                            echo '<a href="' . esc_url(https://asiangay.tv/wp-content/themes/yolotube-mod-v2/get_tag_link($individual_tag->term_id)) . '">' . esc_html($individual_tag->name) . '</a><span class="separator">|</span>';
                        }
                    }
                ?>
                <a href="<?php the_permalink(); ?>" class="post-title-link"><?php the_title(); ?></a>
            </div>
            <article class="post-content">
                <div class="videohere">
                    <?php
                        // LẤY SERVER TỪ META BOX THEO THỨ TỰ ƯU TIÊN
                        $servers = [];
                        
                        // Thứ tự ưu tiên: Hydrax -> Voe -> Doodstream
                        $hydrax_slug = get_post_meta(get_the_ID(), 'hydrax_slug', true);
                        if (!empty($hydrax_slug)) {
                            $servers['Hydrax'] = 'https://gaybb.net/?v=' . $hydrax_slug;
                        }

                        $voe_url = get_post_meta(get_the_ID(), 'voe_url', true);
                        if (!empty($voe_url)) {
                            $servers['Voe.sx'] = 'https://voe.sx/e/' . end(explode('/', rtrim($voe_url, '/')));
                        }

                        $dood_url = get_post_meta(get_the_ID(), 'doodstream_url', true);
                        if (!empty($dood_url)) {
                            $servers['DoodStream'] = 'https://dood.la/e/' . end(explode('/', rtrim($dood_url, '/')));
                        }
                        
                        // LẤY THÊM CÁC IFRAME TỪ NỘI DUNG BÀI VIẾT
                        $post_content_full = get_post_field('post_content', get_the_ID());
                        if (preg_match_all('/<iframe.*?src=["\'](.*?)["\']/i', $post_content_full, $matches)) {
                            foreach ($matches[1] as $iframe_src) {
                                $host = parse_url($iframe_src, PHP_URL_HOST);
                                $name = ucfirst(str_replace('www.', '', $host));
                                if (!in_array($iframe_src, $servers) && !array_key_exists($name, $servers)) {
                                    $servers[$name] = $iframe_src;
                                }
                            }
                        }

                        // HIỂN THỊ PLAYER VÀ DANH SÁCH SERVER
                        if (!empty($servers)) :
                            $default_embed_url = reset($servers);
                            $default_embed_url_autoplay = $default_embed_url . (strpos($default_embed_url, '?') === false ? '?' : '&') . 'autoplay=1';
                    ?>
                        <div class="yolo-player-container">
                            <iframe id="yolo-main-player" src="<?php echo esc_url(https://asiangay.tv/wp-content/themes/yolotube-mod-v2/$default_embed_url_autoplay); ?>" frameborder="0" allow="autoplay; fullscreen"></iframe>
                        </div>
                        <?php if (count($servers) > 1): ?>
                        <div class="yolo-server-list">
                            <?php $is_first = true; foreach ($servers as $name => $embed_url) { ?>
                                <button class="yolo-server-button <?php if ($is_first) { echo 'active'; $is_first = false; } ?>" data-src="<?php echo esc_url(https://asiangay.tv/wp-content/themes/yolotube-mod-v2/$embed_url); ?>">
                                    <?php echo esc_html($name); ?>
                                </button>
                            <?php } ?>
                        </div>
                        <?php endif; ?>
                        <div class="download-buttons">
                            <?php
                                $num = 1;
                                $popup_ad_url = 'https://adorablenet.com/vhM5I1';
                                foreach ($servers as $name => $embed_url) {
                                    if ($name === 'Voe.sx' || $name === 'DoodStream' || stripos($name, 'Mixdrop') !== false) {
                                        $download_link = $embed_url;
                                        if ($name === 'Voe.sx' && preg_match('#^https://voe\.sx/e/([^/]+)$#', $embed_url, $m)) {
                                            $download_link = "https://voe.sx/" . $m[1];
                                        } else if ($name === 'DoodStream' && preg_match('#/e/([^/]+)#', $embed_url, $m)) {
                                            $download_link = "https://dood.ws/d/" . $m[1];
                                        }
                                        echo '<a href="' . esc_url(https://asiangay.tv/wp-content/themes/yolotube-mod-v2/$download_link) . '" target="_blank" class="btn-download">DOWNLOAD ' . $num . '</a>';
                                    } else {
                                        $popup_script = 'window.open(\'' . esc_url(https://asiangay.tv/wp-content/themes/yolotube-mod-v2/$popup_ad_url) . '\', \'_blank\', \'width=900,height=600\');return false;';
                                        echo '<a href="javascript:void(0);" onclick="' . $popup_script . '" class="btn-download">DOWNLOAD ' . $num . '</a>';
                                    }
                                    $num++;
                                }
                            ?>
                        </div>
                        <center>
                            <script type="text/javascript" data-cfasync="false" async src="https://poweredby.jads.co/js/jads.js"></script>
                            <ins id="1099691" data-width="300" data-height="262"></ins>
                            <script type="text/javascript" data-cfasync="false" async>(adsbyjuicy = window.adsbyjuicy || []).push({'adzone':1099691});</script>
                        </center>
                        <script type="text/javascript">
                        document.addEventListener('DOMContentLoaded', function() {
                            const mainPlayer = document.getElementById('yolo-main-player');
                            if (mainPlayer) {
                                const serverButtons = document.querySelectorAll('.yolo-server-button');
                                serverButtons.forEach(button => {
                                    button.addEventListener('click', function(e) {
                                        e.preventDefault();
                                        const baseSrc = this.getAttribute('data-src');
                                        const newSrcWithAutoplay = baseSrc + (baseSrc.includes('?') ? '&' : '?') + 'autoplay=1';
                                        if (mainPlayer.src !== newSrcWithAutoplay) {
                                            mainPlayer.src = newSrcWithAutoplay;
                                        }
                                        serverButtons.forEach(btn => btn.classList.remove('active'));
                                        this.classList.add('active');
                                    });
                                });
                            }
                        });
                        </script>
                    <?php
                        else:
                            echo '<p style="text-align:center; padding: 20px; background: #222; color: #fff;">Không tìm thấy video cho bài đăng này.</p>';
                        endif;
                    ?>
                </div>
                <?php
                if (!empty($servers)) {
                    $content_no_iframe = preg_replace('/<iframe.*?<\/iframe>/is', '', get_the_content());
                    echo apply_filters('the_content', $content_no_iframe);
                } else {
                    the_content();
                }
                ?>
            </article>
        </div>
        <div class="ad-160x600 ad-desktop">
            <script type="text/javascript" data-cfasync="false" async src="https://poweredby.jads.co/js/jads.js"></script>
            <ins id="1099689" data-width="160" data-height="612"></ins>
            <script type="text/javascript" data-cfasync="false" async>(adsbyjuicy = window.adsbyjuicy || []).push({'adzone':1099689});</script>
        </div>
    </div>

    <div class="newest-videos row">
        <div class="top-newest">
            <h2 class="main-title">Relate videos</h2>
        </div>
        <?php
        $categories = get_the_category($post->ID);
        if ($categories) {
            $category_ids = array();
            foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
            $args = array( 'category__in' => $category_ids, 'post__not_in' => array($post->ID), 'posts_per_page' => 12, 'ignore_sticky_posts' => 1 );
            $my_query = new WP_Query($args);
            if( $my_query->have_posts() ) {
                while ($my_query->have_posts()) : $my_query->the_post();
                    get_template_part( 'template-parts/content', 'video' );
                endwhile;
            } else {
                get_template_part( 'template-parts/content', 'none' );
            }
            wp_reset_postdata();
        }
        ?>
    </div>
<?php endwhile; endif; ?>
<?php get_footer(); ?>