/**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="row">
    <div class="yolo-player-adbox" style="display:flex;flex-direction:row;align-items:stretch;justify-content:center;width:100%;">
        <div class="ad-160x600" style="width:160px;min-width:160px;max-width:160px;display:flex;align-items:center;justify-content:center;">
            <div class="ad-desktop">
                <script type="text/javascript" data-cfasync="false" async src="https://poweredby.jads.co/js/jads.js"></script>
                <ins id="1048282" data-width="160" data-height="612"></ins>
                <script type="text/javascript" data-cfasync="false" async>
                    (adsbyjuicy = window.adsbyjuicy || []).push({'adzone':1048282});
                </script>
                </div>
        </div>

        <div class="content detail" style="flex:1 1 0%;max-width:1000px;margin:0 10px;">
            <div class="top-newest">
                <h1 class="main-title"><?php the_title();?></h1>
            </div>
			<CENTER><!-- JuicyAds v3.0 -->
<script type="text/javascript" data-cfasync="false" async src="https://poweredby.jads.co/js/jads.js"></script>
<ins id="932344" data-width="300" data-height="262"></ins>
<script type="text/javascript" data-cfasync="false" async>(adsbyjuicy = window.adsbyjuicy || []).push({'adzone':932344});</script>
<!--JuicyAds END--></CENTER>
            <article class="post-content">
                <div class="videohere">
                    <?php
                        // --- LẤY SERVER TỪ META BOX ---
                        $dood_url         = get_post_meta(get_the_ID(), 'doodstream_url', true);
                        $hydrax_slug      = get_post_meta(get_the_ID(), 'hydrax_slug', true);
                        $hydrax_api_key   = get_post_meta(get_the_ID(), 'hydrax_api_key', true);
                        $voe_url          = get_post_meta(get_the_ID(), 'voe_url', true);
                        $streamtape_url   = get_post_meta(get_the_ID(), 'streamtape_url', true);
                        $viloza_url       = get_post_meta(get_the_ID(), 'viloza_url', true);
                        $dsio_url         = get_post_meta(get_the_ID(), 'dsio_url', true);
                        $netu_vid         = get_post_meta(get_the_ID(), 'netu_vid', true);
                        $video_code       = get_post_meta(get_the_ID(), 'video_code', true);

                        $servers = [];
                        $is_hydrax_only = false;

                        // Hydrax ưu tiên đầu
                        if (!empty($hydrax_slug)) {
                            $hydrax_url = 'https://gaybb.net/?v=' . $hydrax_slug;
                            if (!empty($hydrax_api_key)) {
                                $hydrax_url = add_query_arg('api_key', urlencode($hydrax_api_key), $hydrax_url);
                            }
                            $servers['Hydrax'] = $hydrax_url;
                        }
                        if (!empty($dood_url))       $servers['DoodStream']   = 'https://dood.la/e/' . end(explode('/', rtrim($dood_url, '/')));
                        if (!empty($voe_url))        $servers['Voe.sx']       = 'https://voe.sx/e/' . end(explode('/', rtrim($voe_url, '/')));
                        if (!empty($streamtape_url)) $servers['StreamTape']   = 'https://streamtape.com/e/' . end(explode('/', rtrim($streamtape_url, '/')));
                        if (!empty($viloza_url))     $servers['Viloza']       = 'https://viloza.com/e/' . end(explode('/', rtrim($viloza_url, '/')));
                        if (!empty($dsio_url))       $servers['D-S.io']       = 'https://d-s.io/e/' . end(explode('/', rtrim($dsio_url, '/')));
                        if (!empty($netu_vid))       $servers['Netu.tv']      = 'https://hqq.tv/player/embed_player.php?vid=' . $netu_vid;

                        // --- LẤY THÊM CÁC IFRAME TRONG NỘI DUNG BÀI VIẾT VÀ VIDEO_CODE ---
                        $post_content_full = get_post_field('post_content', get_the_ID()) . $video_code;
                        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 (stripos($host, 'mixdrop') !== false) $name = 'Mixdrop';

                                if (!in_array($iframe_src, $servers) && !array_key_exists($name, $servers)) {
                                    $servers[$name] = $iframe_src;
                                }
                            }
                        }

                        // Check chỉ có Hydrax
                        if (count($servers) === 1 && array_key_exists('Hydrax', $servers)) {
                            $is_hydrax_only = true;
                        }

                        // --- HIỆN 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';
                    ?>
                        <style>
                            .yolo-player-container { position: relative; padding-bottom: 56.25%; height: 0; background: #000; }
                            .yolo-player-container iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0; }
                            .yolo-server-list { padding: 10px 0; text-align: center; border-top: 1px solid #333; margin-top: 10px; }
                            .yolo-server-button { padding: 10px 20px; margin: 5px; border: 1px solid #555; background: #222; color: #fff; cursor: pointer; border-radius: 4px; font-size: 16px; font-weight: bold; text-transform: uppercase; transition: all 0.2s ease; }
                            .yolo-server-button.active, .yolo-server-button:hover { border-color: var(--main-color, #e73737); background: var(--main-color, #e73737); color: #fff; transform: scale(1.05); }
                            .download-buttons { margin-top: 18px; margin-bottom: 8px; text-align: center; }
                            .btn-download { display: inline-block; margin: 0 12px 10px 0; padding: 8px 20px; background: var(--main-color, #e73737); color: #fff !important; border-radius: 4px; text-decoration: none; font-weight: bold; box-shadow: 0 2px 6px rgba(0,0,0,0.10); transition: background 0.2s; }
                            .btn-download:hover { background: #88c900; }
                            
                            /* --- CSS CHO QUẢNG CÁO & NÚT TẮT --- */
                            #yolo-player-ad-banner { margin-top: 15px; text-align: center; position: relative; background: #000; padding: 10px 0; }
                            #yolo-close-ad-btn {
                                position: absolute;
                                bottom: 5px;
                                right: 5px;
                                background-color: rgba(0, 0, 0, 0.7);
                                color: #fff;
                                border: 1px solid #555;
                                border-radius: 50%;
                                cursor: pointer;
                                font-size: 24px;
                                font-weight: bold;
                                line-height: 38px;
                                width: 40px;
                                height: 40px;
                                text-align: center;
                                transition: all 0.2s ease;
                                z-index: 10;
                            }
                            #yolo-close-ad-btn:hover { background-color: #e73737; border-color: #e73737; transform: scale(1.1); }
                            /* --- KẾT THÚC CSS QUẢNG CÁO --- */

                            @media (max-width:991px) {
                                .ad-160x600 { display:none !important;}
                                .content.detail { max-width:100% !important; margin:0 !important; }
                                .yolo-player-adbox { flex-direction: column; }
                            }
                        </style>
                        <div class="yolo-player-container">
                            <iframe id="yolo-main-player" src="<?php echo esc_url(https://japangaysex.com/wp-content/themes/yolotube-mod-v2/$default_embed_url_autoplay); ?>" frameborder="0" allow="autoplay; fullscreen"></iframe>
                        </div>

                        <div id="yolo-player-ad-banner">
                            <script type="text/javascript" data-cfasync="false" async src="https://poweredby.jads.co/js/jads.js"></script>
                            <ins id="1090022" data-width="300" data-height="112"></ins>
                            <script type="text/javascript" data-cfasync="false" async>(adsbyjuicy = window.adsbyjuicy || []).push({'adzone':1090022});</script>
                            
                            <button id="yolo-close-ad-btn" title="Close Ad">&times;</button>
                        </div>
                        <?php if (count($servers) > 1 && !$is_hydrax_only): ?>
                        <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://japangaysex.com/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'; // Link quảng cáo của bạn

                                foreach ($servers as $name => $embed_url) {

                                    // QUY TẮC 1: NGOẠI LỆ - Các server này sẽ có link tải trực tiếp
                                    if ($name === 'Voe.sx' || $name === 'DoodStream' || stripos($name, 'Mixdrop') !== false) {
                                        $download_link = $embed_url; // Mặc định
                                        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];
                                        }
                                        // In ra nút download trực tiếp
                                        echo '<a href="' . esc_url(https://japangaysex.com/wp-content/themes/yolotube-mod-v2/$download_link) . '" target="_blank" class="btn-download">DOWNLOAD ' . $num . '</a>';
                                    }
                                    // QUY TẮC 2: MẶC ĐỊNH - Tất cả các server còn lại sẽ mở popup quảng cáo
                                    else {
                                        $popup_script = 'window.open(\'' . esc_url(https://japangaysex.com/wp-content/themes/yolotube-mod-v2/$popup_ad_url) . '\', \'_blank\', \'width=900,height=600\');return false;';
                                        // In ra nút chỉ mở popup quảng cáo
                                        echo '<a href="javascript:void(0);" onclick="' . $popup_script . '" class="btn-download">DOWNLOAD ' . $num . '</a>';
                                    }

                                    $num++;
                                }
                            ?>
                        </div>
                        <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');
                                    });
                                });
                            }

                            // --- JAVASCRIPT ĐỂ TẮT QUẢNG CÁO ---
                            const adBanner = document.getElementById('yolo-player-ad-banner');
                            const closeAdBtn = document.getElementById('yolo-close-ad-btn');
                            if (adBanner && closeAdBtn) {
                                closeAdBtn.addEventListener('click', function() {
                                    adBanner.style.display = 'none';
                                });
                            }
                            // --- KẾT THÚC JAVASCRIPT ---
                        });
                        </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
                // Ẩn iframe trong nội dung nếu đã có server
                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();
                }
                ?>
                <div class="description">
                    <p>Added: <span><?php if (function_exists('time_ago')) { echo time_ago(); } ?> by <?php the_author(); ?></span><br>
                    <?php $duration = get_post_meta(get_the_ID(), 'duration', true); if ($duration!=""){?>Runtime: <span><?php echo esc_html($duration);?></span><br><?php } ?>
                    </p>
                    <div class="categories clear">
                        <p>Categories: <?php the_category(', ') ?></p>
                    </div>
                </div>
                <p class="tags"> <?php the_tags( 'Tags: ', ', ', '' ); ?></p>
            </article>
        </div>
        <div class="ad-160x600" style="width:160px;min-width:160px;max-width:160px;display:flex;align-items:center;justify-content:center;">
            <div class="ad-desktop">
                <script type="text/javascript" data-cfasync="false" async src="https://poweredby.jads.co/js/jads.js"></script>
                <ins id="1048282" data-width="160" data-height="612"></ins>
                <script type="text/javascript" data-cfasync="false" async>
                    (adsbyjuicy = window.adsbyjuicy || []).push({'adzone':1048282});
                </script>
                </div>
        </div>
    </div>
	<CENTER><!-- JuicyAds v3.0 -->
<script type="text/javascript" data-cfasync="false" async src="https://poweredby.jads.co/js/jads.js"></script>
<ins id="932344" data-width="300" data-height="262"></ins>
<script type="text/javascript" data-cfasync="false" async>(adsbyjuicy = window.adsbyjuicy || []).push({'adzone':932344});</script>
<!--JuicyAds END--></CENTER>
    <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(); ?>