<?php
function bongdako_shortcode_list_match()
{
    ob_start();

    static $sport_plugin_list_match_existed = false;
    if (!$sport_plugin_list_match_existed) {

        /*        <!-- <link rel="preload" as="style" href="<?= BONGDAKO_PLUGIN_DIR_URL ?>layouts/shortcode/list_match/index.css?v=<?= ASSETS_VERSION ?>" />*/
        /*        <link rel="stylesheet" href="<?= BONGDAKO_PLUGIN_DIR_URL ?>layouts/shortcode/list_match/index.css?v=<?= ASSETS_VERSION ?>" /> -->*/
        ?>
        <style>
            .bdk_m-box {
                cursor: pointer;
            }

            .dbk_matchs table {
                border-collapse: collapse;
                max-width: 100%;
                width: 100%;
                table-layout: fixed;
                margin-bottom: 0;
            }

            .bdk_m-box {
                font-size: 13px;
                font-weight: 400;
                border-top: 1px solid #007691;

            }

            .bdk_m-box:hover {
                background-color: #f2f2f2;
            }

            .dbk_matchs table tr td {
                padding: 10px 5px;
            }

            .dbk_matchs table tr td.bdk_m-team span {
                display: -webkit-box;
                -webkit-line-clamp: 3;
                -webkit-box-orient: vertical;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .bdk_m-box:first-of-type {
                border-top: 0;
            }

            .bdk_m-team {
                text-align: center;
            }

            .bdk_m-team img {
                display: block;
                width: 50px;
                height: 50px;
                margin: auto;
            }

            .bdk_m-info {
                text-align: center;
            }

            .bdk_m-time {
                background: #007691;
                color: #fff;
                padding: 2px 10px;
                font-weight: 700;
                border-radius: 20px;
                display: inline-block;
            }

            <?php if (get_option('primary_color_sp')){?>
            .bdk_m-time {
                background: <?php echo get_option('primary_color_sp')?> !important;
            }

            .bdk_m-box {
                border-bottom: 1px solid <?php echo get_option('primary_color_sp')?> !important;
            }

            <?php }?>
            <?php if (get_option('text_primary_color_sp')){?>
            .dbk_matchs table tr td.bdk_m-team span, .bdk_league-title {
                color: <?php echo get_option('text_primary_color_sp')?> !important;
            }

            <?php }?>

            <?php if (get_option('text_secondary_color_sp')){?>
            .bdk_m-date {
                color: <?php echo get_option('text_secondary_color_sp')?> !important;
            }

            <?php }?>
        </style>
        <?php
        add_action('wp_footer', function () {
            bongdako_assets_js();
            ?>
            <script type="text/javascript">
                var ajaxurl_list_match = "<?php echo admin_url('admin-ajax.php'); ?>";

                function formatDateTime(dateTimeString) {
                    const date = new Date(dateTimeString);

                    const d = String(date.getDate()).padStart(2, "0");
                    const m = String(date.getMonth() + 1).padStart(2, "0"); // months are 0-based
                    const y = date.getFullYear();

                    const hours = date.getHours().toString().padStart(2, '0');
                    const minutes = date.getMinutes().toString().padStart(2, '0');

                    const formattedTime = `${hours}:${minutes}`;
                    const formattedDate = `${d}/${m}/${y}`;

                    return {date: formattedDate, time: formattedTime};
                }

                function renderMatches(matches, targetElement) {
                    if (!matches || matches.length === 0) {
                        targetElement.innerHTML = "Không có kết quả.";
                        return;
                    }

                    let html = '';
                    let count = 0;
                    matches.slice(0, 3).forEach(match => {
                        const matchId = match.ScheduleID;
                        const {date, time} = formatDateTime(match.MatchTime);
                        let slugDt = `${toThaiSlug(match.homeTeamName)}-${toThaiSlug(match.guestTeamName)}-${matchId}`;
                        html += `
                            <tr class="bdk_m-box viewDetail" id="${matchId}" onClick="window.open(window.match_detail_url + '/${slugDt}', '_blank');">
                                <td class="bdk_m-team bdk_mt-home">
                                    <img src="<?= IMGS3?>${match.homeTeamLogo}" onerror="this.src='<?= DB_DOMAIN?>/assets/images/home_1.svg'" alt="${match.homeTeamName}" width="50" height="50">
                                    <span>${match.homeTeamName}</span>
                                </td>
                                <td class="bdk_m-info">
                                    <div class="bdk_league-title"><span>${match.SclassName}</span></div>
                                    <div class="bdk_m-date">${date}</div>
                                    <div class="bdk_m-time">${time}</div>
                                </td>
                                <td class="bdk_m-team bdk_mt-away">
                                    <img src="<?= IMGS3?>${match.guestTeamLogo}" onerror="this.src='<?= DB_DOMAIN?>/assets/images/home_1.svg'" alt="${match.guestTeamName}" width="50" height="50">
                                    <span>${match.guestTeamName}</span>
                                </td>
                            </tr>
                        `;
                    });

                    targetElement.innerHTML = `<div class="dbk_matchs"><table>${html}</table></div>`;
                }

                document.addEventListener("DOMContentLoaded", function () {
                    var matchesContainer = document.querySelector('.dbk_list_match');

                    fetch(ajaxurl_list_match, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: 'action=bongdako_list_match'
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                var matches = data.data;
                                renderMatches(matches, matchesContainer);
                            } else {
                                matchesContainer.innerHTML = 'Error: ' + data.data;
                            }
                        })
                        .catch(error => {
                            console.warn(error);

                            matchesContainer.innerHTML = 'Error loading data';
                        });
                });
            </script>
            <?php
        });

        $sport_plugin_list_match_existed = true;
    }
    ?>
    <div class="dbk_list_match"></div>
    <?php
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}

add_shortcode('bongdako_list_match', 'bongdako_shortcode_list_match');

