<?php
/**
 * Plugin Name: ThaiGoLive Multi-Sport & Player API Connector
 * Plugin URI: https://lnwthailive.online/docs
 * Description: ปลั๊กอินเชื่อมต่อ API ผลบอลสด มวยไทย วัวชน IPTV และเครื่องเล่นวีดีโอสตรีมมิ่ง (Iframe Player) พร้อมระบบแคช Transient ความเร็วสูง และ Shortcodes สำหรับ WordPress & Elementor
 * Version: 2.3.0
 * Author: LnwthaiLive
 * Author URI: https://lnwthailive.online
 * License: GPL2
 */

if (!defined('ABSPATH')) exit;

// 0. ฟังก์ชันช่วยดึง API Key พร้อม Fallback ป้องกันการเรียก API ล้มเหลว
function thaigolive_get_api_key() {
    $apiKey = get_option('thaigolive_api_key', '');
    if (empty($apiKey)) {
        return 'demo-19326a7919f3b5980741da5aaecfd3df';
    }
    return trim($apiKey);
}

// 1. ลงทะเบียนเมนูตั้งค่าใน WP Admin
add_action('admin_menu', function() {
    add_options_page(
        'ตั้งค่า ThaiGoLive API',
        'ThaiGoLive API',
        'manage_options',
        'thaigolive-settings',
        'thaigolive_render_settings_page'
    );
});

add_action('admin_init', function() {
    register_setting('thaigolive_options_group', 'thaigolive_api_key');
    register_setting('thaigolive_options_group', 'thaigolive_api_base');
    register_setting('thaigolive_options_group', 'thaigolive_cache_ttl');
});

// AJAX Handler สำหรับทดสอบความถูกต้องของ API Key ในหน้า WP Admin
add_action('wp_ajax_thaigolive_test_api', function() {
    check_ajax_referer('thaigolive_test_nonce', 'nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'ไม่มีสิทธิ์ใช้งาน'));
    }

    $apiKey = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
    $apiBase = isset($_POST['api_base']) ? esc_url_raw($_POST['api_base']) : 'https://lnwthailive.online';

    if (empty($apiKey)) {
        wp_send_json_error(array('message' => 'กรุณากรอก API Key ก่อนทำการทดสอบ'));
    }

    $url = rtrim($apiBase, '/') . '/api/verify?api_key=' . urlencode($apiKey);
    $response = wp_remote_get($url, array(
        'timeout' => 10,
        'headers' => array(
            'x-api-key' => $apiKey,
            'Accept'    => 'application/json',
        )
    ));

    if (is_wp_error($response)) {
        wp_send_json_error(array('message' => 'เกิดข้อผิดพลาดในการเชื่อมต่อเซิร์ฟเวอร์: ' . $response->get_error_message()));
    }

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

    if ($code === 200 && !empty($data['ok'])) {
        $owner = isset($data['owner']) ? $data['owner'] : 'Authorized Client';
        $tier = isset($data['tier']) ? strtoupper($data['tier']) : 'PREMIUM';
        wp_send_json_success(array(
            'message' => "🟢 เชื่อมต่อสำเร็จ! สิทธิ์การใช้งาน: {$tier} (เจ้าของ: {$owner})",
            'data'    => $data
        ));
    } else {
        $err = isset($data['error']) ? $data['error'] : 'API Key ไม่ถูกต้อง หรือหมดอายุแล้ว';
        wp_send_json_error(array('message' => '🔴 ' . $err));
    }
});

// Render หน้าตั้งค่าใน WP Admin
function thaigolive_render_settings_page() {
    $apiKey = get_option('thaigolive_api_key', '');
    $apiBase = get_option('thaigolive_api_base', 'https://lnwthailive.online');
    $cacheTtl = get_option('thaigolive_cache_ttl', 30);
    $nonce = wp_create_nonce('thaigolive_test_nonce');
    ?>
    <div class="wrap" style="max-width: 900px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
        <h1 style="display: flex; align-items: center; gap: 10px; margin-bottom: 20px;">
            <span style="background: linear-gradient(135deg, #f97316, #ea580c); color: #fff; padding: 6px 14px; border-radius: 10px; font-size: 16px; font-weight: 800; box-shadow: 0 4px 12px rgba(234,88,12,0.3);">ThaiGoLive</span>
            ตั้งค่าระบบเชื่อมต่อ Multi-Sport & Iframe Player API
        </h1>

        <div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 16px; padding: 28px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); margin-bottom: 24px;">
            <form method="post" action="options.php" id="tgl-settings-form">
                <?php settings_fields('thaigolive_options_group'); ?>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row" style="font-weight: 700; color: #0f172a;">API Key ของคุณ</th>
                        <td>
                            <input type="text" id="tgl_api_key" name="thaigolive_api_key" value="<?php echo esc_attr($apiKey); ?>" class="regular-text" style="width: 100%; max-width: 500px; font-family: monospace; font-size: 14px; padding: 8px 12px; border-radius: 8px; border: 1px solid #cbd5e1;" placeholder="เช่น thl_live_xxxxxxx หรือ key ของท่าน" />
                            <p class="description" style="color: #64748b; margin-top: 6px;">
                                หากยังไม่ได้ตั้งค่า ระบบจะใช้สิทธิ์ Demo อัตโนมัติ | ติดต่อรับ API Key ถาวรได้ทาง Telegram <a href="https://t.me/lnwthaicode" target="_blank" style="color: #0284c7; font-weight: 600;">@lnwthaicode</a> หรือดูข้อมูลใน <a href="https://lnwthailive.online/docs" target="_blank" style="color: #0284c7; font-weight: 600;">API Portal Docs</a>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row" style="font-weight: 700; color: #0f172a;">API Base URL</th>
                        <td>
                            <input type="text" id="tgl_api_base" name="thaigolive_api_base" value="<?php echo esc_attr($apiBase); ?>" class="regular-text" style="width: 100%; max-width: 500px; font-family: monospace; font-size: 14px; padding: 8px 12px; border-radius: 8px; border: 1px solid #cbd5e1;" />
                            <p class="description" style="color: #64748b; margin-top: 6px;">ค่ามาตรฐาน: <code>https://lnwthailive.online</code></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row" style="font-weight: 700; color: #0f172a;">ระยะเวลาแคชผลบอลสด (Cache TTL)</th>
                        <td>
                            <input type="number" name="thaigolive_cache_ttl" value="<?php echo esc_attr($cacheTtl); ?>" min="5" max="300" style="width: 120px; font-size: 14px; padding: 6px 10px; border-radius: 8px; border: 1px solid #cbd5e1;" /> วินาที
                            <p class="description" style="color: #64748b; margin-top: 6px;">
                                แนะนำ 15–30 วินาที เพื่อเพิ่มความเร็วหน้าเว็บ (&lt;10ms) และประหยัดโควต้า API
                            </p>
                        </td>
                    </tr>
                </table>

                <div style="margin-top: 24px; padding-top: 20px; border-top: 1px solid #f1f5f9; display: flex; align-items: center; gap: 12px;">
                    <?php submit_button('บันทึกการตั้งค่า', 'primary', 'submit', false, array('style' => 'padding: 8px 20px; font-weight: 700; border-radius: 8px;')); ?>
                    <button type="button" id="tgl-test-btn" class="button button-secondary" style="padding: 8px 16px; font-weight: 600; border-radius: 8px; background: #f8fafc; border-color: #cbd5e1;">
                        ⚡ ทดสอบการเชื่อมต่อ API Key
                    </button>
                </div>
                <div id="tgl-test-result" style="margin-top: 14px; font-size: 13px; font-weight: 600; display: none; padding: 10px 14px; border-radius: 8px;"></div>
            </form>
        </div>

        <!-- Section: Documentation & Shortcodes -->
        <div style="background: #0f172a; color: #f8fafc; border-radius: 16px; padding: 28px; box-shadow: 0 10px 30px rgba(0,0,0,0.2);">
            <h3 style="margin-top: 0; font-size: 18px; color: #f97316; display: flex; align-items: center; gap: 8px;">
                🚀 ตัวอย่าง Shortcodes พร้อมใช้งานบน WordPress & Elementor
            </h3>

            <div style="display: grid; grid-template-columns: 1fr; gap: 16px; margin-top: 20px;">
                <!-- Shortcode 1: Iframe Player -->
                <div style="background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 16px;">
                    <div style="font-weight: 700; color: #38bdf8; font-size: 14px; margin-bottom: 6px;">
                        1. ฝังเครื่องเล่นวีดีโอสตรีมมิ่งสด (Iframe Player)
                    </div>
                    <code style="background: #090d16; color: #4ade80; padding: 6px 12px; border-radius: 6px; display: block; font-size: 13px; font-family: monospace; margin-bottom: 8px;">
                        [tgl_player match_id="104859" channel="1" responsive="yes"]
                    </code>
                    <p style="margin: 0; font-size: 12px; color: #94a3b8;">
                        * ระบบจะดึง API Key จากหน้าตั้งค่าใส่ให้ในไอเฟรมโดยอัตโนมัติ ทำให้ผู้ใช้รับชมได้ทันทีโดยไม่ติดรหัสผ่าน
                    </p>
                </div>

                <!-- Shortcode 2: Live Matches List -->
                <div style="background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 16px;">
                    <div style="font-weight: 700; color: #38bdf8; font-size: 14px; margin-bottom: 6px;">
                        2. แสดงตารางการแข่งขันพร้อมโลโก้ทีมและปุ่มกดดูสด / ป๊อปอัป
                    </div>
                    <code style="background: #090d16; color: #4ade80; padding: 6px 12px; border-radius: 6px; display: block; font-size: 13px; font-family: monospace; margin-bottom: 8px;">
                        [tgl_live_matches sport="football" count="10"]
                    </code>
                    <p style="margin: 0; font-size: 12px; color: #94a3b8;">
                        มีระบบ Lightbox Popup ในตัว ผู้ชมสามารถคลิกดูสดได้ทันทีบนหน้าเว็บเดิมโดยไม่ต้องสลับแท็บ
                    </p>
                </div>

                <!-- Shortcode 3: Boxing -->
                <div style="background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 16px;">
                    <div style="font-weight: 700; color: #38bdf8; font-size: 14px; margin-bottom: 6px;">
                        3. แสดงรายการมวยไทยสด / มวยพักยก
                    </div>
                    <code style="background: #090d16; color: #4ade80; padding: 6px 12px; border-radius: 6px; display: block; font-size: 13px; font-family: monospace; margin-bottom: 8px;">
                        [tgl_boxing count="5"]
                    </code>
                </div>

                <!-- Shortcode 4: Wuachon -->
                <div style="background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 16px;">
                    <div style="font-weight: 700; color: #38bdf8; font-size: 14px; margin-bottom: 6px;">
                        4. แสดงถ่ายทอดสดวัวชน
                    </div>
                    <code style="background: #090d16; color: #4ade80; padding: 6px 12px; border-radius: 6px; display: block; font-size: 13px; font-family: monospace; margin-bottom: 8px;">
                        [tgl_wuachon count="5"]
                    </code>
                </div>
            </div>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        $('#tgl-test-btn').on('click', function() {
            var apiKey = $('#tgl_api_key').val();
            var apiBase = $('#tgl_api_base').val();
            var $res = $('#tgl-test-result');

            $res.hide().removeClass('notice-success notice-error').css({
                'background': '#f1f5f9',
                'color': '#334155',
                'border': '1px solid #cbd5e1'
            }).text('⏳ กำลังตรวจสอบ API Key...').slideDown();

            $.post(ajaxurl, {
                action: 'thaigolive_test_api',
                nonce: '<?php echo $nonce; ?>',
                api_key: apiKey,
                api_base: apiBase
            }, function(response) {
                if (response.success) {
                    $res.css({
                        'background': '#f0fdf4',
                        'color': '#166534',
                        'border': '1px solid #bbf7d0'
                    }).text(response.data.message);
                } else {
                    $res.css({
                        'background': '#fef2f2',
                        'color': '#991b1b',
                        'border': '1px solid #fecaca'
                    }).text(response.data.message);
                }
            });
        });
    });
    </script>
    <?php
}

// 2. ฟังก์ชันหลักในการเรียก API พร้อมระบบ Caching (Transients API)
function thaigolive_fetch_api($endpoint, $params = array(), $custom_ttl = null) {
    $apiKey = thaigolive_get_api_key();
    $apiBase = rtrim(get_option('thaigolive_api_base', 'https://lnwthailive.online'), '/');
    $ttl = $custom_ttl !== null ? $custom_ttl : intval(get_option('thaigolive_cache_ttl', 30));

    // แนบ api_key ใน query parameters เสมอ เพื่อป้องกัน header โดน Cloudflare/Proxy ตัดทิ้ง
    if (!empty($apiKey) && !isset($params['api_key'])) {
        $params['api_key'] = $apiKey;
    }

    $cache_key = 'tgl_' . md5($endpoint . serialize($params));
    $cached = get_transient($cache_key);
    if (false !== $cached) {
        return $cached;
    }

    $url = $apiBase . $endpoint;
    if (!empty($params)) {
        $url = add_query_arg($params, $url);
    }

    $response = wp_remote_get($url, array(
        'timeout' => 8,
        'headers' => array(
            'x-api-key' => $apiKey,
            'Accept'    => 'application/json',
        ),
    ));

    if (is_wp_error($response)) {
        error_log('[ThaiGoLive API Error]: ' . $response->get_error_message());
        return false;
    }

    $code = wp_remote_retrieve_response_code($response);
    if ($code !== 200) {
        return false;
    }

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

    if (!empty($data)) {
        set_transient($cache_key, $data, $ttl);
    }

    return $data;
}

// 2.5 Lightbox Modal Player Script สำหรับเปิดดูถ่ายทอดสดบนหน้าเว็บ
function thaigolive_render_modal_player() {
    static $rendered = false;
    if ($rendered) return;
    $rendered = true;
    ?>
    <div id="tgl-player-modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;z-index:999999;background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);align-items:center;justify-content:center;padding:16px;box-sizing:border-box;">
        <div style="position:relative;width:100%;max-width:960px;background:#090d16;border:1px solid rgba(255,255,255,0.15);border-radius:16px;overflow:hidden;box-shadow:0 25px 60px rgba(0,0,0,0.8);">
            <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 18px;background:#0f172a;border-bottom:1px solid rgba(255,255,255,0.08);">
                <div id="tgl-modal-title" style="color:#f8fafc;font-weight:700;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">ถ่ายทอดสด LnwthaiLive</div>
                <div style="display:flex;align-items:center;gap:10px;">
                    <a id="tgl-modal-newtab" href="#" target="_blank" style="color:#38bdf8;font-size:12px;text-decoration:none;font-weight:600;display:inline-flex;align-items:center;gap:4px;padding:4px 8px;border-radius:6px;background:rgba(56,189,248,0.1);">↗ เปิดแท็บใหม่</a>
                    <button type="button" onclick="tglClosePlayerModal()" style="background:transparent;border:0;color:#94a3b8;cursor:pointer;font-size:20px;line-height:1;padding:4px 8px;border-radius:6px;" onmouseover="this.style.color='#ef4444'" onmouseout="this.style.color='#94a3b8'">✕</button>
                </div>
            </div>
            <div style="position:relative;padding-bottom:56.25%;height:0;background:#000;">
                <iframe id="tgl-modal-iframe" src="about:blank" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;" allowfullscreen allow="autoplay; encrypted-media; picture-in-picture"></iframe>
            </div>
        </div>
    </div>
    <style>
        @keyframes tglPulse {
            0% { transform: scale(0.95); opacity: 0.8; }
            50% { transform: scale(1.15); opacity: 1; }
            100% { transform: scale(0.95); opacity: 0.8; }
        }
    </style>
    <script>
    function tglOpenPlayerModal(e, url, title) {
        if (e && e.preventDefault) e.preventDefault();
        var modal = document.getElementById('tgl-player-modal');
        var iframe = document.getElementById('tgl-modal-iframe');
        var titleEl = document.getElementById('tgl-modal-title');
        var newtab = document.getElementById('tgl-modal-newtab');
        if (modal && iframe) {
            iframe.src = url;
            if (title && titleEl) titleEl.innerText = title;
            if (newtab) newtab.href = url;
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    }
    function tglClosePlayerModal() {
        var modal = document.getElementById('tgl-player-modal');
        var iframe = document.getElementById('tgl-modal-iframe');
        if (modal && iframe) {
            iframe.src = 'about:blank';
            modal.style.display = 'none';
            document.body.style.overflow = '';
        }
    }
    document.addEventListener('keydown', function(evt) {
        if (evt.key === 'Escape') tglClosePlayerModal();
    });
    </script>
    <?php
}
add_action('wp_footer', 'thaigolive_render_modal_player');

// 3. Shortcode: [tgl_player match_id="104859" channel="1" height="540" responsive="yes"]
add_shortcode('tgl_player', function($atts) {
    $a = shortcode_atts(array(
        'match_id'   => '',
        'matchid'    => '',
        'id'         => '',
        'channel'    => '',
        'sport'      => '',
        'title'      => 'ถ่ายทอดสด',
        'url'        => '',
        'tv_link'    => '',
        'height'     => '540',
        'responsive' => 'yes',
        'api_key'    => '',
    ), $atts);

    $matchId = !empty($a['match_id']) ? $a['match_id'] : (!empty($a['matchid']) ? $a['matchid'] : $a['id']);
    $apiKey = !empty($a['api_key']) ? $a['api_key'] : thaigolive_get_api_key();
    $apiBase = rtrim(get_option('thaigolive_api_base', 'https://lnwthailive.online'), '/');

    if (empty($matchId) && empty($a['url']) && empty($a['tv_link'])) {
        return '<div style="padding:14px;background:#1e1e2d;color:#ef4444;border-radius:10px;text-align:center;font-size:13px;">กรุณาระบุ match_id ใน Shortcode [tgl_player match_id="..."]</div>';
    }

    $queryParams = array();
    if (!empty($matchId)) $queryParams['matchId'] = $matchId;
    if (!empty($a['channel'])) $queryParams['channel'] = $a['channel'];
    if (!empty($a['sport'])) $queryParams['sport'] = $a['sport'];
    if (!empty($a['title'])) $queryParams['title'] = $a['title'];
    if (!empty($a['url'])) $queryParams['url'] = $a['url'];
    if (!empty($a['tv_link'])) $queryParams['tvLink'] = $a['tv_link'];
    if (!empty($apiKey)) $queryParams['api_key'] = $apiKey;

    $iframeSrc = add_query_arg($queryParams, $apiBase . '/player/iframe');

    if ($a['responsive'] === 'yes') {
        return '<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;border-radius:14px;background:#000;box-shadow:0 10px 30px rgba(0,0,0,0.5);">' .
               '<iframe src="' . esc_url($iframeSrc) . '" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;" allowfullscreen allow="autoplay; encrypted-media; picture-in-picture"></iframe>' .
               '</div>';
    }

    return '<div style="width:100%;height:' . intval($a['height']) . 'px;border-radius:14px;overflow:hidden;background:#000;box-shadow:0 10px 30px rgba(0,0,0,0.5);">' .
           '<iframe src="' . esc_url($iframeSrc) . '" width="100%" height="100%" frameborder="0" allowfullscreen allow="autoplay; encrypted-media; picture-in-picture"></iframe>' .
           '</div>';
});

add_shortcode('thaigo_player', 'tgl_player_shortcode_alias');
function tgl_player_shortcode_alias($atts) {
    return do_shortcode('[tgl_player ' . thaigolive_atts_to_string($atts) . ']');
}

// 4. Shortcode: [tgl_live_matches sport="football" count="10"]
add_shortcode('tgl_live_matches', function($atts) {
    $a = shortcode_atts(array(
        'sport' => 'football',
        'count' => 10,
    ), $atts);

    $endpoint = ($a['sport'] === 'football') 
        ? '/api/public/matches?sport=football' 
        : '/api/ge-sports?type=' . urlencode($a['sport']);

    $res = thaigolive_fetch_api($endpoint, array(), 20);

    $matches = array();
    if (!empty($res['data'])) {
        $matches = $res['data'];
    } elseif (!empty($res['matches'])) {
        $matches = $res['matches'];
    }

    if (empty($matches)) {
        return '<div style="padding:16px;background:#0e101f;color:#94a3b8;border-radius:12px;text-align:center;font-size:13px;border:1px solid rgba(255,255,255,0.06);">ยังไม่มีรายการแข่งขันในขณะนี้</div>';
    }

    $apiKey = thaigolive_get_api_key();
    $apiBase = rtrim(get_option('thaigolive_api_base', 'https://lnwthailive.online'), '/');

    // ตรวจสอบให้แน่ใจว่า modal player มีอยู่ในหน้า
    thaigolive_render_modal_player();

    $output = '<div class="tgl-matches-grid" style="display:flex;flex-direction:column;gap:8px;font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',sans-serif;">';
    $shown = 0;
    foreach ($matches as $m) {
        if ($shown++ >= intval($a['count'])) break;

        $mId = esc_attr($m['id'] ?? $m['matchId'] ?? '');
        $home = esc_html($m['teamHome'] ?? $m['home'] ?? '');
        $away = esc_html($m['teamAway'] ?? $m['away'] ?? '');
        $homeLogo = esc_url($m['homeLogo'] ?? $m['home_logo'] ?? $m['logoHome'] ?? '');
        $awayLogo = esc_url($m['awayLogo'] ?? $m['away_logo'] ?? $m['logoAway'] ?? '');
        $score = esc_html($m['score'] ?? 'VS');
        $league = esc_html($m['league'] ?? '');
        $isLive = !empty($m['isLive']);
        $matchTitle = esc_attr($home . ' vs ' . $away . ' (' . $league . ')');

        $playerUrl = $apiBase . '/player/iframe?matchId=' . urlencode($mId) . '&api_key=' . urlencode($apiKey);

        if ($isLive) {
            $statusText = '<a href="' . esc_url($playerUrl) . '" onclick="tglOpenPlayerModal(event, \'' . esc_url($playerUrl) . '\', \'' . $matchTitle . '\')" target="_blank" style="background:linear-gradient(135deg, #ef4444, #dc2626);color:#fff;padding:6px 12px;border-radius:8px;font-weight:700;font-size:11px;text-decoration:none;display:inline-flex;align-items:center;gap:5px;box-shadow:0 2px 8px rgba(239,68,68,0.35);transition:transform 0.2s;" onmouseover="this.style.transform=\'scale(1.05)\'" onmouseout="this.style.transform=\'scale(1)\'"><span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:#fff;animation:tglPulse 1.5s infinite;"></span> ดูสด</a>';
        } else {
            $timeText = esc_html($m['time'] ?? 'รอแข่ง');
            $statusText = '<a href="' . esc_url($playerUrl) . '" onclick="tglOpenPlayerModal(event, \'' . esc_url($playerUrl) . '\', \'' . $matchTitle . '\')" target="_blank" style="background:rgba(255,255,255,0.08);color:#38bdf8;padding:5px 10px;border-radius:8px;font-weight:600;font-size:11px;text-decoration:none;display:inline-flex;align-items:center;gap:4px;border:1px solid rgba(56,189,248,0.2);transition:all 0.2s;" onmouseover="this.style.background=\'rgba(56,189,248,0.15)\'" onmouseout="this.style.background=\'rgba(255,255,255,0.08)\'">🕒 ' . $timeText . ' (เข้าชม)</a>';
        }

        $homeLogoHtml = $homeLogo ? '<img src="' . $homeLogo . '" style="width:22px;height:22px;object-fit:contain;flex-shrink:0;border-radius:4px;" alt="" onerror="this.style.display=\'none\'" />' : '';
        $awayLogoHtml = $awayLogo ? '<img src="' . $awayLogo . '" style="width:22px;height:22px;object-fit:contain;flex-shrink:0;border-radius:4px;" alt="" onerror="this.style.display=\'none\'" />' : '';

        $output .= '<div style="background:#0e101f;border:1px solid rgba(255,255,255,0.08);border-radius:12px;padding:12px 16px;display:flex;align-items:center;justify-content:space-between;gap:12px;color:#fff;">';
        $output .= '  <div style="font-size:12px;color:#f97316;font-weight:bold;min-width:90px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' . $league . '</div>';
        $output .= '  <div style="flex:1;display:flex;align-items:center;justify-content:center;gap:10px;font-size:13px;font-weight:600;">';
        $output .= '    <div style="flex:1;display:flex;align-items:center;justify-content:flex-end;gap:8px;min-width:0;">';
        $output .= '      <span style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' . $home . '</span>';
        $output .= '      ' . $homeLogoHtml;
        $output .= '    </div>';
        $output .= '    <span style="background:rgba(34,197,94,0.15);color:#22c55e;padding:3px 10px;border-radius:8px;font-family:monospace;font-size:12px;font-weight:bold;flex-shrink:0;">' . $score . '</span>';
        $output .= '    <div style="flex:1;display:flex;align-items:center;justify-content:flex-start;gap:8px;min-width:0;">';
        $output .= '      ' . $awayLogoHtml;
        $output .= '      <span style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' . $away . '</span>';
        $output .= '    </div>';
        $output .= '  </div>';
        $output .= '  <div style="min-width:85px;text-align:right;">' . $statusText . '</div>';
        $output .= '</div>';
    }
    $output .= '</div>';
    return $output;
});

// 5. Shortcode: [tgl_boxing count="5"]
add_shortcode('tgl_boxing', function($atts) {
    $a = shortcode_atts(array('count' => 5), $atts);
    $res = thaigolive_fetch_api('/api/public/boxing', array(), 20);
    $fights = !empty($res['data']) ? $res['data'] : array();

    if (empty($fights)) {
        return '<div style="padding:16px;background:#0e101f;color:#94a3b8;border-radius:12px;text-align:center;font-size:13px;border:1px solid rgba(255,255,255,0.06);">ไม่มีคู่มวยสดในขณะนี้</div>';
    }

    $apiKey = thaigolive_get_api_key();
    $apiBase = rtrim(get_option('thaigolive_api_base', 'https://lnwthailive.online'), '/');

    thaigolive_render_modal_player();

    $output = '<div style="display:flex;flex-direction:column;gap:8px;font-family:sans-serif;">';
    $shown = 0;
    foreach ($fights as $f) {
        if ($shown++ >= intval($a['count'])) break;
        $mId = esc_attr($f['id'] ?? '');
        $red = esc_html($f['redCorner'] ?? $f['fighter1'] ?? '');
        $blue = esc_html($f['blueCorner'] ?? $f['fighter2'] ?? '');
        $stadium = esc_html($f['stadium'] ?? 'มวยไทย');
        $matchTitle = esc_attr($red . ' vs ' . $blue . ' [' . $stadium . ']');
        $playerUrl = $apiBase . '/player/iframe?matchId=' . urlencode($mId) . '&sport=boxing&api_key=' . urlencode($apiKey);

        $status = !empty($f['isLive']) 
            ? '<a href="' . esc_url($playerUrl) . '" onclick="tglOpenPlayerModal(event, \'' . esc_url($playerUrl) . '\', \'' . $matchTitle . '\')" target="_blank" style="background:#dc2626;color:#fff;padding:4px 10px;border-radius:6px;font-weight:bold;font-size:11px;text-decoration:none;display:inline-flex;align-items:center;gap:4px;">🔴 ดูสด</a>' 
            : '<a href="' . esc_url($playerUrl) . '" onclick="tglOpenPlayerModal(event, \'' . esc_url($playerUrl) . '\', \'' . $matchTitle . '\')" target="_blank" style="background:rgba(255,255,255,0.08);color:#cbd5e1;padding:4px 10px;border-radius:6px;font-size:11px;text-decoration:none;">🕒 รอชก (เข้าชม)</a>';

        $output .= '<div style="background:#0e101f;border:1px solid rgba(255,255,255,0.08);border-radius:12px;padding:12px 16px;display:flex;align-items:center;justify-content:space-between;color:#fff;">';
        $output .= '  <div style="font-size:12px;color:#eab308;font-weight:bold;">[' . $stadium . ']</div>';
        $output .= '  <div style="font-size:14px;font-weight:bold;display:flex;gap:8px;">';
        $output .= '    <span style="color:#ef4444;">' . $red . '</span> VS <span style="color:#3b82f6;">' . $blue . '</span>';
        $output .= '  </div>';
        $output .= '  <div style="font-size:12px;">' . $status . '</div>';
        $output .= '</div>';
    }
    $output .= '</div>';
    return $output;
});

// 6. Shortcode: [tgl_wuachon count="5"]
add_shortcode('tgl_wuachon', function($atts) {
    $a = shortcode_atts(array('count' => 5), $atts);
    $res = thaigolive_fetch_api('/api/public/wuachon/stream', array(), 20);
    $matches = !empty($res['data']) ? $res['data'] : array();

    if (empty($matches)) {
        return '<div style="padding:16px;background:#0e101f;color:#94a3b8;border-radius:12px;text-align:center;font-size:13px;border:1px solid rgba(255,255,255,0.06);">ไม่มีคู่ชนวัวในขณะนี้</div>';
    }

    $apiKey = thaigolive_get_api_key();
    $apiBase = rtrim(get_option('thaigolive_api_base', 'https://lnwthailive.online'), '/');

    thaigolive_render_modal_player();

    $output = '<div style="display:flex;flex-direction:column;gap:8px;font-family:sans-serif;">';
    $shown = 0;
    foreach ($matches as $m) {
        if ($shown++ >= intval($a['count'])) break;
        $mId = esc_attr($m['id'] ?? '');
        $title = esc_html($m['title'] ?? 'วัวชนสด');
        $stadium = esc_html($m['stadium'] ?? 'สนามวัวชน');
        $matchTitle = esc_attr($title . ' [' . $stadium . ']');
        $playerUrl = $apiBase . '/player/iframe?matchId=' . urlencode($mId) . '&sport=wuachon&api_key=' . urlencode($apiKey);

        $status = !empty($m['isLive']) 
            ? '<a href="' . esc_url($playerUrl) . '" onclick="tglOpenPlayerModal(event, \'' . esc_url($playerUrl) . '\', \'' . $matchTitle . '\')" target="_blank" style="background:#dc2626;color:#fff;padding:4px 10px;border-radius:6px;font-weight:bold;font-size:11px;text-decoration:none;display:inline-flex;align-items:center;gap:4px;">🔴 ดูถ่ายทอดสด</a>' 
            : '<a href="' . esc_url($playerUrl) . '" onclick="tglOpenPlayerModal(event, \'' . esc_url($playerUrl) . '\', \'' . $matchTitle . '\')" target="_blank" style="background:rgba(255,255,255,0.08);color:#cbd5e1;padding:4px 10px;border-radius:6px;font-size:11px;text-decoration:none;">🕒 รอแข่ง (เข้าชม)</a>';

        $output .= '<div style="background:#0e101f;border:1px solid rgba(255,255,255,0.08);border-radius:12px;padding:12px 16px;display:flex;align-items:center;justify-content:space-between;color:#fff;">';
        $output .= '  <div style="font-size:12px;color:#f59e0b;font-weight:bold;">[' . $stadium . ']</div>';
        $output .= '  <div style="font-size:13px;font-weight:bold;">' . $title . '</div>';
        $output .= '  <div>' . $status . '</div>';
        $output .= '</div>';
    }
    $output .= '</div>';
    return $output;
});

// 7. Shortcode: [tgl_standings league="7"] หรือ [tgl_standings league="epl"]
add_shortcode('tgl_standings', function($atts) {
    $a = shortcode_atts(array(
        'league' => '7',
        'count'  => 20,
    ), $atts);

    $leagueId = esc_attr($a['league']);
    $endpoint = is_numeric($leagueId) 
        ? '/api/365scores/standings?competitionId=' . urlencode($leagueId)
        : '/api/standings?league=' . urlencode($leagueId);

    $res = thaigolive_fetch_api($endpoint, array(), 60);

    $rows = array();
    $leagueTitle = 'ตารางคะแนน';

    if (!empty($res['data']['rows'])) {
        $rows = $res['data']['rows'];
        $leagueTitle = esc_html($res['data']['displayName'] ?? $res['data']['leagueName'] ?? 'ตารางคะแนน');
    } elseif (!empty($res['rows'])) {
        $rows = $res['rows'];
        $leagueTitle = esc_html($res['leagueName'] ?? 'ตารางคะแนน');
    }

    if (empty($rows)) {
        return '<div style="padding:16px;background:#0e101f;color:#94a3b8;border-radius:12px;text-align:center;font-size:13px;border:1px solid rgba(255,255,255,0.06);">ไม่พบข้อมูลตารางคะแนนในขณะนี้</div>';
    }

    $output = '<div class="tgl-standings-box" style="background:#0e101f;border:1px solid rgba(255,255,255,0.08);border-radius:14px;padding:16px;color:#fff;font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',sans-serif;overflow-x:auto;">';
    $output .= '<h3 style="margin:0 0 14px 0;font-size:16px;color:#f97316;display:flex;align-items:center;gap:8px;">📊 ' . $leagueTitle . '</h3>';
    $output .= '<table style="width:100%;border-collapse:collapse;font-size:13px;text-align:center;">';
    $output .= '<thead><tr style="border-bottom:1px solid rgba(255,255,255,0.1);color:#94a3b8;font-size:11px;">';
    $output .= '<th style="padding:8px;text-align:left;">อันดับ</th>';
    $output .= '<th style="padding:8px;text-align:left;">ทีม</th>';
    $output .= '<th style="padding:8px;">แข่ง</th>';
    $output .= '<th style="padding:8px;">ชนะ</th>';
    $output .= '<th style="padding:8px;">เสมอ</th>';
    $output .= '<th style="padding:8px;">แพ้</th>';
    $output .= '<th style="padding:8px;">+/-</th>';
    $output .= '<th style="padding:8px;font-weight:bold;color:#22c55e;">แต้ม</th>';
    $output .= '</tr></thead><tbody>';

    $shown = 0;
    foreach ($rows as $r) {
        if ($shown++ >= intval($a['count'])) break;
        $rank = esc_html($r['rank'] ?? $r['position'] ?? $shown);
        $team = esc_html($r['teamName'] ?? $r['team'] ?? 'Team');
        $logo = esc_url($r['teamLogo'] ?? '');
        $mp = esc_html($r['played'] ?? $r['mp'] ?? 0);
        $w = esc_html($r['wins'] ?? $r['w'] ?? 0);
        $d = esc_html($r['draws'] ?? $r['d'] ?? 0);
        $l = esc_html($r['losses'] ?? $r['l'] ?? 0);
        $gd = esc_html($r['gd'] ?? $r['ratio'] ?? 0);
        $pts = esc_html($r['points'] ?? $r['pts'] ?? 0);

        $bg = ($shown % 2 === 0) ? 'rgba(255,255,255,0.02)' : 'transparent';
        $output .= '<tr style="border-bottom:1px solid rgba(255,255,255,0.04);background:' . $bg . ';">';
        $output .= '  <td style="padding:10px 8px;text-align:left;font-weight:bold;color:#f59e0b;">' . $rank . '</td>';
        $output .= '  <td style="padding:10px 8px;text-align:left;display:flex;align-items:center;gap:8px;font-weight:600;">';
        if ($logo) {
            $output .= '    <img src="' . $logo . '" style="width:20px;height:20px;object-fit:contain;" alt="" />';
        }
        $output .= '    <span>' . $team . '</span>';
        $output .= '  </td>';
        $output .= '  <td style="padding:10px 8px;color:#cbd5e1;">' . $mp . '</td>';
        $output .= '  <td style="padding:10px 8px;color:#22c55e;">' . $w . '</td>';
        $output .= '  <td style="padding:10px 8px;color:#eab308;">' . $d . '</td>';
        $output .= '  <td style="padding:10px 8px;color:#ef4444;">' . $l . '</td>';
        $output .= '  <td style="padding:10px 8px;color:#94a3b8;">' . ($gd > 0 ? '+' . $gd : $gd) . '</td>';
        $output .= '  <td style="padding:10px 8px;font-weight:bold;color:#22c55e;font-size:14px;">' . $pts . '</td>';
        $output .= '</tr>';
    }

    $output .= '</tbody></table></div>';
    return $output;
});
add_shortcode('thaigo_standings', 'tgl_standings_shortcode_alias');
function tgl_standings_shortcode_alias($atts) {
    return do_shortcode('[tgl_standings ' . thaigolive_atts_to_string($atts) . ']');
}

// Helper Function
function thaigolive_atts_to_string($atts) {
    if (empty($atts)) return '';
    $res = array();
    foreach ($atts as $k => $v) {
        $res[] = sprintf('%s="%s"', esc_attr($k), esc_attr($v));
    }
    return implode(' ', $res);
}
