<?php

$assets_settings = trailingslashit(dirname(plugin_dir_url(__FILE__))) . 'assets/';

// Enqueue Vue.js and custom script
function bongdako6in1_enqueue_scripts()
{
    $assets_settings = trailingslashit(dirname(plugin_dir_url(__FILE__))) . 'assets/';
    wp_register_style('bongdako-style', $assets_settings . 'css/style.css', array(), ASSETS_VERSION, 'all');
}

add_action('wp_enqueue_scripts', 'bongdako6in1_enqueue_scripts', 1);

function my_customizer_controls_css()
{
    echo '<style>
       .options-title-divider {
    background-color: #3d4c5a;
    border-top: 2px solid #23282d;
    color: #fff;
    text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
}

.options-subtitle-divider, .options-title-divider {
    font-size: 120%;
    font-weight: bolder;
    margin-bottom: -12px;
    margin-left: -12px;
    margin-right: -12px;
    padding: 8px 12px;
}
    </style>';
}

add_action('customize_controls_print_styles', 'my_customizer_controls_css');
function unicode_to_utf8($str)
{
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($matches) {
        return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UTF-16');
    }, $str);
}

function add_custom_fonts()
{ ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">

    <meta name="fetch_domain_url" content="<?php echo esc_url(get_option('url_data_sp', 'https://db.winfast.dev')) ?>">
    <meta name="fetch_url_qc" content="<?php echo esc_url(get_option('url_ads_sp', '')) ?>">
    <meta name="fetch_url_image"
          content="<?php echo esc_url(get_option('url_image_sp', 'https://img.winfast.dev')) ?>">
    <meta name="disable_fl" content="<?php echo (int)(true == get_option('Checkbox_unindex_sp', true)); ?>">
    <meta name="Checkbox_hide_action"
          content="<?php echo (int)(true == get_option('Checkbox_hide_action_sp', false)); ?>">
    <meta name="_6in1_max_leagues" content="<?php echo get_option('max_leagues_sixinone', 5) ?>">
    <meta name="_rate_max_leagues" content="<?php echo get_option('max_leagues_rate', 10) ?>">
    <meta name="_result_max_leagues" content="<?php echo get_option('max_leagues_result', 10) ?>">
    <meta name="_fixture_max_leagues" content="<?php echo get_option('max_leagues_fixture', 10) ?>">
    <?php

    // Danh sách ngôn ngữ được hỗ trợ
    $supported_langs = ['en', 'th', 'id'];
    $locale = get_locale(); // Ví dụ: 'en_US'
    $lang_code = substr($locale, 0, 2); // 'en', 'th', 'id', etc.
    $dt = "select_detail_" . $lang_code . "_sp";
    $analysis = "select_analysis_" . $lang_code . "_sp";

    if (!in_array($lang_code, $supported_langs)) {
        $dt = 'select_detail_sp'; // Mặc định
        $analysis = 'select_analysis_sp'; // Mặc định
    }

    // Lấy slug từ option
    $slug = get_option($dt, 'chi-tiet');
    $slugAnalysis = get_option($analysis, 'phan-tich');

    // Tạo URL đầy đủ, có prefix ngôn ngữ
    $detail_url = home_url("/$slug");
    $analysis_url = home_url("/$slugAnalysis");
    ?>

    <meta name="_detail_url" content="<?php echo esc_url($detail_url); ?>">
    <meta name="_analysis_url" content="<?php echo esc_url($analysis_url); ?>">

    <script>
        window.match_detail_url = "<?php echo esc_url($detail_url); ?>"
        window.match_analysis_url = "<?php echo esc_url($analysis_url); ?>"
    </script>
    <?php $match_id = get_query_var('match_id'); ?>
    <?php if ($match_id):
    $server_time = date('Y,n,j,G,i,s');
    $js_content = <<<JS
        window.selectedMatchId = {$match_id}
        var _serverTime =  '{$server_time}' 
    JS;
    bongdako_save_js_data($js_content, 'match-detail-' . $match_id . '.js');
    ?>
    <script data-skip-wpfc="true"
            src="<?= home_url() . '/wp-content/uploads/sport-plugin/match-detail-' . $match_id . '.js?v=' . time() ?>"
            defer></script>

<?php endif; ?>
    <?php
}

function bongdako_save_js_data($js_content, $fileName)
{
    if (empty($js_content)) {
        error_log('Nội dung rỗng hoặc không hợp lệ từ URL.');
        return;
    }

    // Tạo đường dẫn đến thư mục uploads và thư mục bongdako
    $upload_dir = wp_upload_dir();
    $json_file_path = $upload_dir['basedir'] . '/sport-plugin/' . $fileName;
    // Nếu thư mục bongdako không tồn tại, tạo nó
    if (!file_exists(dirname($json_file_path))) {
        mkdir(dirname($json_file_path), 0755, true);
    }
    // Kiểm tra thư mục có thể ghi được không
    if (is_writable(dirname($json_file_path))) {
        // Xóa file cũ nếu có
        if (file_exists($json_file_path)) {
            unlink($json_file_path);
        }

        // Ghi nội dung JS vào file mới
        file_put_contents($json_file_path, $js_content);
        error_log("Dữ liệu đã được lưu tại: $json_file_path");

        return $js_content;
    } else {
        error_log("Không thể ghi vào thư mục: " . dirname($json_file_path));
    }
}

add_action('customize_save_after', function ($wp_customize) {
    // Flush rewrite rules để cập nhật lại permalink sau khi lưu tùy chỉnh
    flush_rewrite_rules();
});

function bongdako_loading_livescore()
{
    ?>
    <div class="bdk_loading-wrap">
        <?php for ($i = 0; $i < 6; $i++) : ?>
            <div class="bdk_loading-item bdk_loading-head">
                <div class="bdk_loading-background"></div>
            </div>
            <div class="bdk_loading-item">
                <div class="bdk_loading-background"></div>
            </div>
        <?php endfor; ?>
    </div>
    <?php
}


add_action('wp_head', 'add_custom_fonts', 1);
function bongdako_banner_assets()
{
    // Lấy thông tin theme hiện tại
    $current_theme = wp_get_theme();
    $theme = $current_theme->get('Name');
    if ($current_theme->parent()) {
        $theme = $current_theme->parent()->get('Name');
    }

    $jsonData = [];
    foreach (bongdako_get_customizer_banners_data() as $key => $itemPanel) {
        $jsonData[$key] = [];

        $toggle_setting = get_option('toggle_setting_1' . "_" . $itemPanel['name']);
        if ($toggle_setting == 1) {
            continue;
        }
        foreach ($itemPanel['banners'] as $bannerFieldKey => $bannerField) {
            if (isset($bannerField['type']) && $bannerField['type'] === "image") {

                $desktop_color = get_option($bannerFieldKey . "_" . $itemPanel['name'], '');
                $mobile_color = get_option('mb_' . $bannerFieldKey . "_" . $itemPanel['name'], '');
                $text = get_option('text_' . $bannerFieldKey . "_" . $itemPanel['name'], '');
                $mobile_text = get_option('mb_text_' . $bannerFieldKey . "_" . $itemPanel['name'], '');

                if ($text || $mobile_text) {
                    $jsonData[$key][] = [
                        'pos' => $bannerField['pos'] ?? '',
                        'text' => $text,
                        'text_mobile' => $mobile_text,
                        'tracking' => get_option("tracking_" . $bannerFieldKey . "_" . $itemPanel['name'], ''),
                        'tracking_mobile' => get_option("mb_tracking_" . $bannerFieldKey . "_" . $itemPanel['name'], ''),
                    ];
                } else {
                    $jsonData[$key][] = [
                        'pos' => $bannerField['pos'] ?? '',
                        'imgUrl' => $desktop_color,
                        'imgUrl_tablet' => $desktop_color,
                        'imgUrl_mobile' => $mobile_color,
                        'tracking' => get_option("tracking_" . $bannerFieldKey . "_" . $itemPanel['name'], ''),
                        'tracking_mobile' => get_option("mb_tracking_" . $bannerFieldKey . "_" . $itemPanel['name'], ''),
                    ];
                }

            }
            if (isset($bannerField['type']) && $bannerField['type'] === "text") {
                $jsonData[$key][] = [
                    'pos' => $bannerField['pos'] ?? '',
                    "text" => get_option($bannerFieldKey . "_" . $key, ''),
                    "text_mobile" => get_option('mb_' . $bannerFieldKey . "_" . $key, ''),
                    'tracking' => get_option("tracking_" . $bannerFieldKey . "_" . $key, ''),
                    'tracking_mobile' => get_option("mb_tracking_" . $bannerFieldKey . "_" . $key, ''),
                ];
            }


            if ($bannerFieldKey === 'matchlist') {
                $matchlist = [];
                $settings = get_option('match_list' . "_" . $itemPanel['name'], []);
                foreach ($settings as $k => $setting) {
                    $textList = $setting['match_text' . "_" . $itemPanel['name']] ?? '';
                    $textListMobile = $setting['match_text_mobile' . "_" . $itemPanel['name']] ?? '';
                    if ($textList || $textListMobile) {
                        $matchlist[] = [
                            'pos' => '1220x52-matchlist-' . str_pad($k + 1, 2, 0, STR_PAD_LEFT),
                            'text' => $setting['match_text' . "_" . $itemPanel['name']] ?? '',
                            'text_mobile' => $setting['match_text_mobile' . "_" . $itemPanel['name']] ?? '',
                            'tracking' => $setting['tracking_url' . "_" . $itemPanel['name']] ?? '',
                            'tracking_mobile' => $setting['tracking_url_mobile' . "_" . $itemPanel['name']] ?? '',
                        ];
                    } else {
                        $matchlist[] = [
                            'pos' => '1220x52-matchlist-' . str_pad($k + 1, 2, 0, STR_PAD_LEFT),
                            'imgUrl' => $setting['match_image_desktop' . "_" . $itemPanel['name']] && !(strpos($setting['match_image_desktop' . "_" . $itemPanel['name']], 'http') !== false) ? wp_get_attachment_url($setting['match_image_desktop' . "_" . $itemPanel['name']]) : $setting['match_image_desktop' . "_" . $itemPanel['name']],
                            'imgUrl_tablet' => $setting['match_image_desktop' . "_" . $itemPanel['name']] && !(strpos($setting['match_image_desktop' . "_" . $itemPanel['name']], 'http') !== false) ? wp_get_attachment_url($setting['match_image_desktop' . "_" . $itemPanel['name']]) : $setting['match_image_desktop' . "_" . $itemPanel['name']],
                            'imgUrl_mobile' => $setting['match_image_mobile' . "_" . $itemPanel['name']] && !(strpos($setting['match_image_mobile' . "_" . $itemPanel['name']], 'http') !== false) ? wp_get_attachment_url($setting['match_image_mobile' . "_" . $itemPanel['name']]) : $setting['match_image_mobile' . "_" . $itemPanel['name']],
                            'tracking' => $setting['tracking_url' . "_" . $itemPanel['name']] ?? '',
                            'tracking_mobile' => $setting['tracking_url_mobile' . "_" . $itemPanel['name']] ?? '',
                        ];
                    }


                }
                $jsonData[$key][] = [
                    "pos" => "match-list",
                    "banner" => $matchlist
                ];
            }
        }
    }

    $upload_dir = wp_upload_dir(); // Lấy đường dẫn thư mục uploads
    $json_file = $upload_dir['basedir'] . '/sport-plugin/banner-data.js';

    // Kiểm tra quyền ghi vào thư mục uploads
    if (is_writable(dirname($json_file))) {
        // Xóa tệp cũ nếu có
        if (file_exists($json_file)) {
            unlink($json_file);
        }

        // Tạo và ghi dữ liệu JSON vào tệp
        $json_data = 'window.banner_data = ' . json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ';';

        file_put_contents($json_file, $json_data);
    } else {
        // Nếu không có quyền ghi, hiển thị thông báo
        error_log("Không thể ghi vào thư mục uploads để tạo tệp banner-data.js.");
    }
}

function priority_custom_scripts()
{
    wp_enqueue_script('banner_data', home_url() . '/wp-content/uploads/sport-plugin/banner-data.js?v=' . date('His'), array(), null, false);
    wp_enqueue_script('priority_custom_scripts', trailingslashit(dirname(plugin_dir_url(__FILE__))) . 'assets/' . 'js/global-configs.js?v=' . ASSETS_VERSION, array(), null, false);
}

add_action('wp_enqueue_scripts', 'priority_custom_scripts', 1);

/**
 * Loại trừ nhiều script khỏi minify/combine của WP Fastest Cache (free)
 * dựa trên danh sách pattern (regex hoặc chuỗi).
 */
add_filter('script_loader_tag', function ($tag, $handle, $src) {

    // Danh sách pattern bạn muốn loại trừ
    $my_excluded_scripts = [
        '/wp-includes/js/jquery/',                    // mọi file trong thư mục jquery
        '/wp-content/plugins/sport-plugin/',           // tất cả JS của plugin sport-plugin
        '/wp-content/uploads/sport-result-data-(.*)\.js',
        '/wp-content/uploads/sport-season-data-(.*)\.js',
        '/wp-content/uploads/sport-plugin/.*\.js',
    ];

    foreach ($my_excluded_scripts as $pattern) {
        // Dùng preg_match cho phép regex
        if (preg_match('#' . $pattern . '#i', $src)) {
            // Gắn data-skip-wpfc="true", giữ nguyên defer/async nếu có
            // Thay thế cách này để tránh mất các thuộc tính khác
            if (strpos($tag, 'data-skip-wpfc') === false) {
                $tag = str_replace(
                    '<script ',
                    '<script data-skip-wpfc="true" ',
                    $tag
                );
            }
            break;
        }
    }
    return $tag;

}, 10, 3);


function bongdako_layout_assets()
{
    $assets_settings = trailingslashit(dirname(plugin_dir_url(__FILE__))) . 'assets/';
    ?>
    <link href="<?= $assets_settings ?>css/google-font.css?v=<?= ASSETS_VERSION ?>" rel="stylesheet">
    <style>
        #scrollIframe .league-info-link {
            pointer-events: none;
        }

        #scrollIframe {
            container-type: inline-size;
            container-name: iframe-table;
        }

        #scrollIframe a.ads-block {
            display: block;
            text-align: center;
        }

        body #scrollIframe {
            min-width: initial;
        }

        #scrollIframe .yellowcard {
            background-color: #ffe600 !important;
            color: black !important;
        }

        body #scrollIframe #main {
            position: initial;
        }

        #scrollIframe {
            padding: 10px;
        }

        #scrollIframe #min .tools {
            line-height: initial;
            height: auto;
        }

        #scrollIframe #min .tools ul li {
            margin-bottom: 0;
        }

        #scrollIframe #min .tools ul li button {
            margin-bottom: 0;
        }

        @container iframe-table (max-width: 870px) {

            #scrollIframe #table_live .change-colname.hpd-td,
            #scrollIframe #table_live .change-colname.tx-td {
                min-width: auto;
            }

            body #scrollIframe #table_live .action-table-pc {
                display: table-cell !important;
            }

            body #scrollIframe #table_live .action-table-pc span {
                margin: auto;
            }

            #scrollIframe table .team-box > a {
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            #scrollIframe #min .tools ul li {
                margin-left: 0;
            }

            body #scrollIframe #min .tools li .dropdown-toggle {
                border: 0;
                margin-right: 0;
            }
        }

        @keyframes placeHolderShimmer {
            0% {
                background-position: -468px 0
            }

            100% {
                background-position: 468px 0
            }
        }


        .bdk_loading-item {
            background: #fff;
            border: 1px solid;
            border-color: #e5e6e9 #dfe0e4 #d0d1d5;
            border-radius: 3px;
            padding: 10px;
            margin-bottom: 10px;
        }

        .bdk_loading-head {
            margin-top: 11px;
        }

        .bdk_loading-item .bdk_loading-background {
            animation-duration: 1s;
            animation-fill-mode: forwards;
            animation-iteration-count: infinite;
            animation-name: placeHolderShimmer;
            animation-timing-function: linear;
            background: #f6f7f8;
            background: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
            background-size: 800px 104px;
            height: 75px;
            position: relative;
        }

        .bdk_loading-head .bdk_loading-background {
            height: 15px;
        }

        #scrollIframe.wrap-iframe {
            color: #070f03;
            overflow: visible;
            max-width: 100%;
        }

        #scrollIframe.wrap-iframe::-webkit-scrollbar {
            height: 0px;
            /* Hide the horizontal scrollbar */
        }

        #scrollIframe .mcontent {
            min-height: 1030px;
            position: relative;
            padding: 0;
            box-sizing: border-box;
        }

        #scrollIframe .fake_iframe {
            position: absolute;
            left: 0px !important;
            top: 0px !important;
            width: 100%;
            background-color: #e6e6e6;
        }


        body #scrollIframe .mcontent > #main #min,
        #scrollIframe #appHome,
        #scrollIframe #homepage.mcontent {
            width: 100% !important;
        }

        .corner-icon.dark {
            display: none;
        }

        #scrollIframe #homepage #main {
            width: 100% !important;
        }

        #scrollIframe p {
            font-family: "Inter", sans-serif;
            margin: 0;
        }

        #scrollIframe .popup-corner__flag-icon-right {
            background-image: url("<?= BONGDAKO_URL ?>/assets/images/flag-blue.svg");
            background-repeat: no-repeat;
            background-position: left;
            height: 16px;
        }

        #scrollIframe .popup-corner__flag-icon-left {
            background-image: url("<?= BONGDAKO_URL ?>/assets/images/flag-red.svg");
            background-repeat: no-repeat;
            background-position: right;
            height: 16px;
        }

        td.gray-bg2.popup-corner__title-core {
            width: 100px;
        }

        #scrollIframe .swt {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDown.svg");
        }

        body.dark #scrollIframe .swt {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDownWhite.svg");
        }

        body.dark #scrollIframe .swt:hover {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDownWhite.svg");
        }

        #scrollIframe td#oddsHead .select-company {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDown.svg");
        }

        #scrollIframe .second-version .info_title_left .selectbox select {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDown.svg");
        }

        #scrollIframe .data-sync .techlist select {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDown.svg");
        }

        #scrollIframe #main .idx-homepage .icon-matchdata-mobile,
        #scrollIframe #main .idx-favorite .icon-matchdata-mobile {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDown.svg");
        }

        #scrollIframe #main .idx-homepage .icon-matchdata-mobile.on,
        #scrollIframe #main .idx-favorite .icon-matchdata-mobile.on {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDown.svg");
        }

        #scrollIframe #info.matchDetail #SelectLi.custom-select-02::after {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDown.svg");
        }

        @font-face {
            font-family: "iconfont";
            src: url("<?= $assets_settings ?>site/assets/fonts/iconfont.woff2") format("woff2"),
            url("<?= $assets_settings ?>site/assets/fonts/iconfont.woff") format("woff"),
            url("<?= $assets_settings ?>site/assets/fonts/iconfont.ttf") format("truetype");
        }

        #scrollIframe .allno {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-trash.svg") !important;
        }

        .dark #scrollIframe .allno {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-trash-dark.svg") !important;
        }

        #scrollIframe #table_live .odds1.resultColor::after,
        #scrollIframe #table_live .odds2.resultColor::after,
        #scrollIframe .odds-bg.odds-normal > span.down::after,
        #scrollIframe #table_live .new-home-tr .odds1.odds-down::after,
        #scrollIframe #table_live .new_oddsChangePopup .popup-odds-change .odds-down:after,
        #scrollIframe .odds2 > span.down::after,
        #scrollIframe #homepage .game-rate #game-rate .container-sp .table-core-odds-value .odds-number.odds-down::after,
        #scrollIframe .oddschanges .oddschanges-bg1 .down::before,
        #scrollIframe .oddschanges .oddschanges-bg1 .down_green::before {
            content: "";
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-arrow-down-light-v2.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        body #scrollIframe #table_live .odds3.resultColor::after,
        body #scrollIframe .odds-bg.odds-normal > span.up::after,
        body #scrollIframe .odds2 > span.up::after,
        body #scrollIframe #table_live .new-home-tr .odds1.odds-up::after,
        body #scrollIframe #homepage .game-rate #game-rate .container-sp .table-core-odds-value .odds-number.odds-up::after,
        body #scrollIframe #table_live .new_oddsChangePopup .popup-odds-change .odds-up::after,
        body #scrollIframe .oddschanges .oddschanges-bg1 .up::before,
        body #scrollIframe .oddschanges .oddschanges-bg1 .up_red::before {
            content: "";
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-arrow-up-light-v2.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        body #scrollIframe .custom-select-02::after {
            content: "";
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/ar-down.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        body #scrollIframe #table_live .Detail-icon::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-lineup.svg");
        }

        body.dark #scrollIframe #table_live .Detail-icon::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-lineup-dark.svg");
        }

        body #scrollIframe #table_live .analyze-icon::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-analytics.svg");
        }

        body #scrollIframe #showoptional2 .bts:nth-of-type(6) .select-all input::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/uncheck-square.svg");
        }

        body #scrollIframe #showoptional2 .bts:nth-of-type(6) .select-all input:checked::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
        }

        #scrollIframe #showFilterBox {
            top: 36px;
        }

        #scrollIframe #showFilterBox .bts .select-all input::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/uncheck-square.svg");
        }

        #scrollIframe #goalTable input[type="checkbox"]::before {
            content: "";
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/uncheck-square.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe #showFilterBox .bts .select-all input:checked::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
        }

        .dark #showoptional2 .bts:nth-of-type(6) .select-all input::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/uncheck-square.svg");
        }

        .dark #showoptional2 .bts:nth-of-type(6) .select-all input:checked::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
        }

        .dark #showFilterBox .bts .select-all input::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/uncheck-square.svg");
        }

        .dark #showFilterBox .bts .select-all input:checked::before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
        }

        #scrollIframe .filterLi2.xz .dropdown-toggle::after {
            content: "";
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/icon_arrow_down.svg");
            background-size: contain;
            background-repeat: no-repeat;
            border: none;
            margin-left: 0;
            vertical-align: middle;
        }

        #scrollIframe #oddsChange .oddsChange_head .oddsChange_head_title,
        #scrollIframe [id^="oddsChange_"] .oddsChange_head .oddsChange_head_title {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/Union-bg.svg");
        }

        body.dark #scrollIframe #oddsChange .oddsChange_head .oddsChange_head_title,
        body.dark #scrollIframe [id^="oddsChange_"] .oddsChange_head .oddsChange_head_title {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/Union-bg-dark.svg");
        }

        #scrollIframe #showoptional2 #myleague2 input::before {
            content: "";
            background: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/uncheck-square.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe #showoptional2 #myleague2 input[type="checkbox"]:checked::before {
            content: "";
            background: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe #OddsFilter table tr td input[type="checkbox"]:checked::before {
            content: "";
            background: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe .icon-matchdata:before {
            content: '';
            background-image: url('<?= IMGS3_PLUGINS ?>/assets/football-vn/images/icon_flash.svg');
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe .Leaguestitle .rankicon,
        body .team_leaguetitle .rankicon {
            background-image: url('<?= IMGS3_PLUGINS ?>/assets/football-vn/images/rank.svg');
        }

        #scrollIframe .closebtn.v2 {
            background-image: url('<?= IMGS3_PLUGINS ?>/assets/football-vn/images/close-outline.svg');
        }

        #scrollIframe #goalTable input[type="checkbox"]:checked::before {
            content: '';
            background: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe .icon-font-collect-off:before {
            content: '' !important;
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/rating-14px.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe .upper-live-icon-football {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/icons-home-ui/football.svg");
        }

        .dark #scrollIframe .upper-live-icon-football {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/icons-home-ui/football-dark.svg");
        }

        #scrollIframe .Leaguestitle .rankicon,
        body .team_leaguetitle .rankicon {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/rank.svg");
        }

        #scrollIframe .Leaguestitle .league-title-rank-icon,
        body .team_leaguetitle .league-title-rank-icon {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/rank.svg");
        }


        #scrollIframe .odds-table-bg .in-gif {
            background: url("<?= IMGS3_PLUGINS ?>/assets/images/in.gif");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe #tableCoreSP [id^="time_"][id^="time_"] span:after,
        #scrollIframe #table_live [id^="time_"][id^="time_"] span:after {
            content: '';
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/in.gif");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe .live-w-content .live-w-content-time .status-time-match span:after {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/in.gif");
        }

        #scrollIframe .filter-search-name input {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/search-1.svg");
        }

        #scrollIframe .odds.up:after,
        #scrollIframe .odds.down:after {
            content: "";
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-arrow-up-light-v2.svg");
            background-size: 7px 7px;
            background-repeat: no-repeat;
        }

        #scrollIframe .filter-box .custom-select-02:after {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/ar_down.svg");
            right: 10px;
            top: 50%;
            width: 14px;
            height: 14px;
        }

        #scrollIframe .odds.down:after {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/icon-arrow-down-light-v2.svg");
        }

        #scrollIframe .sixmix-container #sixinoneFilterLeague .bts-bottom .select-all input:before {
            content: "";
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/uncheck-square.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe .sixmix-container #sixinoneFilterLeague .bts-bottom .select-all input:checked:before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
        }

        #scrollIframe .sixmix-container #sixinoneFilterLeague #myleague2 ul li input[type="checkbox"]:checked:before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/check-square.svg");
        }

        #scrollIframe .sixmix-container #sixinoneFilterLeague #myleague2 ul li input[type="checkbox"]:before {
            content: "";
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/uncheck-square.svg");
            background-size: contain;
        }

        #scrollIframe .icon-font-collect-on:before {
            content: '' !important;
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/rating-14.svg");
            background-size: contain;
            background-repeat: no-repeat;
        }

        #scrollIframe .icon-matchdata.on:before {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/icon_flash_on.svg");
        }

        #scrollIframe .swt:hover {
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/football-vn/images/CaretDownBlack.svg");
        }

        body #scrollIframe .wrap-loadmore .load-more-btn {
            font-family: Inter;
            font-size: 12px;
            font-style: normal;
            font-weight: 500;
            line-height: 14px;
            color: #fff;
            padding: 8px 41px 8px 21px;
            border-radius: 30px;
            border: 0;
            background: #337359;
            background-image: url("<?= IMGS3_PLUGINS ?>/assets/images/double-alt-arrow-down.svg");
            background-repeat: no-repeat;
            background-position: right 20px top 6px;
        }

        #scrollIframe {

        label {
            margin-bottom: 0;
        }

        }


    </style>
    <?php
}

function bongdako_assets_js()
{
    $locale = get_locale();        // Ví dụ 'en_US'
    $lang_code = substr($locale, 0, 2);  // Lấy 2 ký tự đầu tiên: 'en';
    $assets_settings = BONGDAKO_PLUGIN_DIR_URL . '/assets/';
    if (!in_array($lang_code, ['en', 'th', 'id'])) {
        $lang_code = 'vn';
    }

    if (!defined('SPORT_JS_EXISTED')) {
        define('SPORT_JS_EXISTED', true);
        ?>
        <script src="<?= $assets_settings ?>site/assets/js/lang/route_<?php echo $lang_code ?>.js?v=<?= ASSETS_VERSION ?>"
                defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/app_vn.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/abbLeague.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/head.js?v=<?= ASSETS_VERSION ?>" defer></script>
        </script>
        <?php if (!wp_script_is('jquery', 'enqueued')) : ?>
            <script src="<?= $assets_settings ?>site/assets/js/jq.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <?php else: ?>
            <script src="<?= $assets_settings ?>js/inline-script.min.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <?php endif; ?>

        <script src="<?= $assets_settings ?>site/assets/js/soccerSetting.js?v=<?= ASSETS_VERSION ?>" defer></script>

        <script src="<?= $assets_settings ?>site/assets/js/common.min.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/diff.js?v=<?= ASSETS_VERSION ?>" defer></script>

        <script src="<?= $assets_settings ?>site/assets/js/jq-lazy.js?v=<?= ASSETS_VERSION ?>" defer></script>

        <script src="<?= $assets_settings ?>site/assets/js/rs_index_vn.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/left-data_vn.js?v=<?= ASSETS_VERSION ?>" defer></script>

        <script src="<?= $assets_settings ?>site/assets/js/jquery.form.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/loginUtil.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/header.js?v=<?= ASSETS_VERSION ?>" defer></script>

        <script src="<?= $assets_settings ?>site/assets/js/helper.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/global.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/vn-helper.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <script src="<?= $assets_settings ?>site/assets/js/layer.js?v=<?= ASSETS_VERSION ?>" defer></script>
        <?php
    }
}

function getRandomColorClass()
{

    $colors = array_merge(
        array_fill(0, 8, ''),
        array_fill(0, 1, 'odds-down'),
        array_fill(0, 1, 'odds-up')
    );

    return $colors[array_rand($colors)];
}

function add_nofollow_to_content_links($content)
{
    // Kiểm tra xem có tồn tại div id="box1"
    if (strpos($content, 'id="scrollIframe"') === false) {
        return $content; // Không có thì trả lại nguyên vẹn
    }

    // Dùng DOMDocument để xử lý HTML
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));

    $xpath = new DOMXPath($dom);
    $box1 = $xpath->query('//div[@id="scrollIframe"]');

    if ($box1->length > 0) {
        foreach ($box1 as $div) {
            $links = $div->getElementsByTagName('a');
            foreach ($links as $link) {
                $rel = $link->getAttribute('rel');
                $livestream = $link->getAttribute('data-livestream');
                $relParts = preg_split('/\s+/', $rel, -1, PREG_SPLIT_NO_EMPTY);
                if(!$livestream) {
                    // Đảm bảo 'nofollow' và 'noindex' có trong mảng $relParts
                    if (!in_array('nofollow', $relParts, true)) {
                        $relParts[] = 'nofollow';
                    }
                    if (!in_array('noopener', $relParts, true)) {
                        $relParts[] = 'noopener';
                    }
                    if (!in_array('noreferrer', $relParts, true)) {
                        $relParts[] = 'noreferrer';
                    }
    
                    // Gán lại thuộc tính rel
                    $link->setAttribute('rel', implode(' ', $relParts));
                }
            }

            $links2 = $div->getElementsByTagName('img');

            foreach ($links2 as $link2) {
                $rel = $link2->getAttribute('rel');
                $relParts = preg_split('/\s+/', $rel, -1, PREG_SPLIT_NO_EMPTY);

                // Đảm bảo 'nofollow' và 'noindex' có trong mảng $relParts
                if (!in_array('nofollow', $relParts, true)) {
                    $relParts[] = 'nofollow';
                }
                if (!in_array('noindex', $relParts, true)) {
                    $relParts[] = 'noindex';
                }

                // Gán lại thuộc tính rel
                $link2->setAttribute('rel', implode(' ', $relParts));
            }
        }
    }

    return preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
}

function add_nofollow_to_content_links_ranking_board($content)
{
    // Kiểm tra xem có tồn tại div id="box1"
    if (strpos($content, 'id="ranking_board"') === false) {
        return $content; // Không có thì trả lại nguyên vẹn
    }

    // Dùng DOMDocument để xử lý HTML
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));

    $xpath = new DOMXPath($dom);
    $box1 = $xpath->query('//div[@id="ranking_board"]');

    if ($box1->length > 0) {
        foreach ($box1 as $div) {
            $links = $div->getElementsByTagName('a');
            foreach ($links as $link) {
                $rel = $link->getAttribute('rel');
                if (stripos($rel, 'nofollow') === false) {
                    $rel = trim($rel . ' nofollow');
                    $link->setAttribute('rel', $rel);
                }
            }
        }
    }

    return preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
}

if (true == get_option('Checkbox_unindex_sp', true)) {
    add_filter('the_content', 'add_nofollow_to_content_links');
    add_filter('the_content', 'add_nofollow_to_content_links_ranking_board');
}

function custom_match_rewrite_rule()
{
    $slugs = [
        'vi' => get_option('select_detail_sp', 'chi-tiet'),
        'vn' => get_option('select_detail_sp', 'chi-tiet'),
        'en' => get_option('select_detail_en_sp', 'detail'),
        'id' => get_option('select_detail_id_sp', 'detail'),
    ];

    $analysis_slugs = [
        'vi' => get_option('select_analysis_sp', 'phan-tich'),
        'vn' => get_option('select_analysis_sp', 'phan-tich'),
        'en' => get_option('select_analysis_en_sp', 'analysis'),
        'id' => get_option('select_analysis_id_sp', 'analysis'),
    ];

    foreach ($slugs as $lang => $slug) {
        // Rule có prefix ngôn ngữ và slug + dynamic match slug với ID ở cuối
        add_rewrite_rule(
            "^$lang/$slug/.+-([0-9]+)/?$",
            'index.php?pagename=' . $slug . '&match_id=$matches[1]&lang=' . $lang,
            'top'
        );

        add_rewrite_rule(
            "^$lang/$slug/([0-9]+)/?$",
            'index.php?pagename=' . $slug . '&match_id=$matches[1]&lang=' . $lang,
            'top'
        );

        // Rule không có prefix ngôn ngữ
        add_rewrite_rule(
            "^$slug/.+-([0-9]+)/?$",
            'index.php?pagename=' . $slug . '&match_id=$matches[1]',
            'top'
        );
        add_rewrite_rule(
            "^$slug/([0-9]+)/?$",
            'index.php?pagename=' . $slug . '&match_id=$matches[1]',
            'top'
        );

    }

    foreach ($analysis_slugs as $lang => $slug) {
        // Rule có prefix ngôn ngữ và slug + dynamic match slug với ID ở cuối
        add_rewrite_rule(
            "^$lang/$slug/.+-([0-9]+)/?$",
            'index.php?pagename=' . $slug . '&match_id=$matches[1]&lang=' . $lang,
            'top'
        );

        add_rewrite_rule(
            "^$lang/$slug/([0-9]+)/?$",
            'index.php?pagename=' . $slug . '&match_id=$matches[1]&lang=' . $lang,
            'top'
        );

        // Rule không có prefix ngôn ngữ
        add_rewrite_rule(
            "^$slug/.+-([0-9]+)/?$",
            'index.php?pagename=' . $slug . '&match_id=$matches[1]',
            'top'
        );

        add_rewrite_rule(
            "^$slug/([0-9]+)/?$",
            'index.php?pagename=' . $slug . '&match_id=$matches[1]',
            'top'
        );
    }

    // Đừng quên đăng ký tag match_id
    add_rewrite_tag('%match_id%', '([0-9]+)');
    add_rewrite_tag('%lang%', '([a-z]+)');
}


add_action('init', 'custom_match_rewrite_rule');

function add_query_vars_filter($vars)
{
    $vars[] = 'match_id';
    return $vars;
}

add_filter('query_vars', 'add_query_vars_filter');


function myplugin_register_page_template($templates)
{
    $templates['page-template-chi-tiet-tran-dau.php'] = 'Trực Tiếp (Plugin Template)';
    return $templates;
}

function add_image_head()
{
    ?>

    <img fetchpriority="high" style="width: 100%;height: 300px;position: absolute;top: 0;left: 0;z-index: -1"
         loading="eager" src="<?= BONGDAKO_PLUGIN_DIR_URL ?>/assets/images/trans.png" alt="">
    <?php
}

add_action('wp_body_open', 'add_image_head', 5);

add_action('wp_ajax_bongdako_list_match', 'bongdako_list_match');
add_action('wp_ajax_nopriv_bongdako_list_match', 'bongdako_list_match');
function bongdako_list_match()
{

    $cache_key = 'bongdako_list_match';
    // $transient_data = get_transient($cache_key);

    // if ($transient_data !== false) {
    //     wp_send_json_success($transient_data);
    // }


    $response = wp_remote_get(DB_DOMAIN . '/ajax/get-hot-matches?lang=vn', [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode('db:1'),
            'Referer' => home_url(),
        ],
        'timeout' => 60,
        'sslverify' => false,
        'curl' => [
            CURLOPT_SSL_VERIFYPEER => 0,
        ],
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error('Lỗi kết nối API DB_DOMAIN: ' . DB_DOMAIN . ' ' . $response->get_error_message());
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (empty($data)) {
        wp_send_json_error('Dữ liệu không hợp lệ hoặc rỗng');
    }

    $cache_time = 3 * 60 * 60;
    set_transient($cache_key, $data, $cache_time);
    wp_send_json_success($data);
}

function bongdako_timestamp()
{
    return round(microtime(true) * 1000);
}


function genDefaultFilterValue($leagues, $nations)
{

    $srciptReturn = '<script>';
    if ($leagues && !empty($leagues)) $srciptReturn .= 'window.league_ids = [' . $leagues . '];';
    if ($nations && !empty($nations)) $srciptReturn .= 'window.nation_ids = [' . $nations . '];';

    $srciptReturn .= '</script>';
    return $srciptReturn;
}

function bongdako_get_leagues($clear_cache = false)
{
    $cache_key = 'bdk_league_data';
    $expired = 86400;

    if ($clear_cache) {
        delete_transient($cache_key);
        wp_cache_delete($cache_key, 'league_data');
    }

    $cached_data = wp_cache_get($cache_key, 'league_data');
    if ($cached_data !== false) {
        return $cached_data;
    }

    $transient_data = get_transient($cache_key);
    if ($transient_data !== false) {
        wp_cache_set($cache_key, $transient_data, 'league_data', $expired);
        return $transient_data;
    }

    delete_transient($cache_key);
    wp_cache_delete($cache_key, 'league_data');

    $url = DB_DOMAIN . '/ajax/get-league-admin?lang=vn&perPage=9999';
    $username = 'db';
    $password = '1';

    $response = wp_remote_get($url, [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode($username . ':' . $password),
            'Referer' => home_url(),
        ],
        'timeout' => 60,
        'sslverify' => false,
        'curl' => [
            CURLOPT_SSL_VERIFYPEER => 0,
        ],
    ]);

    if (is_wp_error($response)) {
        return [];
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (empty($data['data'])) {
        return [];
    }

    $league_data = [];
    foreach ($data['data'] as $item) {
        $kind = $item['Kind'] == 1 ? 'league' : 'cupmatch';
        $league_data[$item['sclassID']] = [
            'type' => $kind,
            'id' => $item['sclassID'],
            'name' => $item['display_name'],
            'slug' => sanitize_title_with_dashes($item['display_name']),
            'logo' => $item['Sclass_pic'],
            'nation' => $item['Name_ES'],
            'subSclassID' => $item['subSclassID'] ?? 0
        ];
    }


    set_transient($cache_key, $league_data, $expired);
    wp_cache_set($cache_key, $league_data, 'league_data', $expired);

    return $league_data;
}

function bongdako_get_league_choices_for_select()
{
    $leagues = bongdako_get_leagues(); // lấy dữ liệu từ API đã cache

    if (empty($leagues) || !is_array($leagues)) {
        return [];
    }

    $choices = [];

    foreach ($leagues as $id => $league) {
        $choices[$id] = $league['name'] ?? 'Giải #' . $id;
    }

    return $choices;
}