<?php 
function bongdako_fetch_and_merge_data($url) {
    $timestamp = time();
    $response = wp_remote_get($url.'?'.$timestamp, [
        'headers' => [
            'Referer' => home_url(),
        ],
        'timeout' => 60,
        'sslverify' => false,
        'curl' => [
            CURLOPT_SSL_VERIFYPEER => 0,
        ],
    ]);
    if (is_wp_error($response)) {
        return 'Error fetching data.';
    }

    $body = wp_remote_retrieve_body($response);

    // Separate the data for A and B arrays
    preg_match_all('/A\[(\d+)\] = \[(.*?)\];/s', $body, $matches_A, PREG_SET_ORDER);
    preg_match_all('/B\[(\d+)\] = \[(.*?)\];/s', $body, $matches_B, PREG_SET_ORDER);

    $result_A = [];
    $result_B = [];

    // Process A array
    foreach ($matches_A as $match) {
        $values = explode(',', $match[2]);

        // Clean up strings and remove quotes
        $cleaned_values = array_map(function ($value) {
            return trim(trim($value), '"');
        }, $values);

        $result_A[] = $cleaned_values;
    }

    // Process B array
    foreach ($matches_B as $match) {
        $values = explode(',', $match[2]);

        $cleaned_values = array_map(function ($value) {
            return trim(trim($value), '"');
        }, $values);

        $result_B[] = $cleaned_values;
    }

    $matches = [];

    foreach ($result_A as $match) {
        $leagueIndex = $match[1] - 1; // Phần tử thứ 2 trên mỗi phần tử của A là index của B
        $leagueId = isset($result_B[$leagueIndex]) ? $result_B[$leagueIndex][0] : '';
        $leagueName = isset($result_B[$leagueIndex]) ? $result_B[$leagueIndex][2] : "Unknown League";
        $leagueFlag = isset($result_B[$leagueIndex]) ? $result_B[$leagueIndex][10] : '';
        $statusMapping = [
            "0" => "Not started",
            "1" => "First half",
            "2" => "Half-time break",
            "3" => "Second half",
            "4" => "Extra time",
            "5" => "Penalty",
            "-1" => "Finished",
            "-10" => "Cancelled",
            "-11" => "TBD",
            "-12" => "Terminated",
            "-13" => "Interrupted",
            "-14" => "Postponed"
        ];

        $matchStatus = isset($match[8]) ? ($statusMapping[$match[8]] ?? "Unknown status") : "Unknown status";

        $matches[] = [
            "matchId" => (string)$match[0],
            "startTime" => $match[6],
            "teams" => [
                "home" => $match[4],
                "away" => $match[5]
            ],
            "status" => $matchStatus,
            "score" => [
                "home" => $match[9],
                "away" => $match[10]
            ],
            "yellow_card" =>[
                "home" => $match[15],
                "away" => $match[16]
            ],
            "league" => $leagueName,
            "referee" => $match[32] ?? "",
            'flag' => '/assets/upload/fbcountry/'.$leagueFlag.'-flag-small.png'
        ];

        // Stop adding matches after 10
        if (count($matches) >= 10) {
            break;
        }
    }

    return $matches;
}
function bongdako_fetch_and_merge_data_faked2($url) {

    $response = wp_remote_get($url, [
        'headers' => [
            'Referer' => home_url(),
        ],
        'timeout' => 60,
        'sslverify' => false,
        'curl' => [
            CURLOPT_SSL_VERIFYPEER => 0,
        ],
    ]);
    if (is_wp_error($response)) {
        return __('Có lỗi khi tải dữ liệu.','sport');
    }
    if (is_wp_error($response)) {
        return 'Error fetching data: ' . $response->get_error_message();
    }

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

    return $data['data'];
}


function bongdako_fetch_and_merge_data_faked($url) {
    $timestamp = time();
    $response = wp_remote_get($url . '?' . $timestamp, [
        'headers' => [
            'Referer' => home_url(),
        ],
        'timeout' => 60,
        'sslverify' => false,
        'curl' => [
            CURLOPT_SSL_VERIFYPEER => 0,
        ],
    ]);
    if (is_wp_error($response)) {
        return __('Có lỗi khi tải dữ liệu.','sport');
    }


    $body = wp_remote_retrieve_body($response);

    // Separate the data for A and B arrays
    preg_match_all('/A\[(\d+)\] = \[(.*?)\];/s', $body, $matches_A, PREG_SET_ORDER);
    preg_match_all('/B\[(\d+)\] = \[(.*?)\];/s', $body, $matches_B, PREG_SET_ORDER);

    $result_A = [];
    $result_B = [];

    // Process A array
    foreach ($matches_A as $match) {
        $values = explode(',', $match[2]);
        $cleaned_values = array_map(function ($value) {
            return trim(trim($value), '"');
        }, $values);

        $result_A[] = $cleaned_values;
    }

    // Process B array
    foreach ($matches_B as $match) {
        $values = explode(',', $match[2]);
        $cleaned_values = array_map(function ($value) {
            return trim(trim($value), '"');
        }, $values);

        $result_B[] = $cleaned_values;
    }

    $leagues = [];

    foreach ($result_A as $match) {
        
        $leagueIndex = $match[1] - 1; // Index of league in B
        $leagueId = isset($result_B[$leagueIndex]) ? $result_B[$leagueIndex][0] : '';
        $leagueName = isset($result_B[$leagueIndex]) ? unicode_to_utf8($result_B[$leagueIndex][2] ?? "Unknown League") : "Unknown League";
        $leagueFlag = isset($result_B[$leagueIndex]) ? $result_B[$leagueIndex][10] : '';
        $leagueLogo = isset($result_B[$leagueIndex]) ? $result_B[$leagueIndex][11] : '';
        $statusMapping = [
            "0" => "Not started",
            "1" => "First half",
            "2" => "Half-time break",
            "3" => "Second half",
            "4" => "Extra time",
            "5" => "Penalty",
            "-1" => "FT",
            "-10" => "Cancelled",
            "-11" => "TBD",
            "-12" => "Terminated",
            "-13" => "Interrupted",
            "-14" => "Postponed"
        ];

        $matchStatus = isset($match[8]) ? ($statusMapping[$match[8]] ?? "Unknown status") : "Unknown status";

        $matchData = [
            "matchId" => (string)$match[0],
            "startTime" => $match[6],
            "teams" => [
                "home" => $match[4],
                "away" => $match[5],
                "home_logo" => $match[37],
                "away_logo" => $match[38]
            ],
            "status" => $matchStatus,
            "score" => [
                "home" => $match[9],
                "away" => $match[10]
            ],
            "red_card" => [
                "home" => $match[13],
                "away" => $match[14]
            ],
            "yellow_card" => [
                "home" => $match[15],
                "away" => $match[16]
            ],
            "corner" => [
                "home" => $match[28],
                "away" => $match[29]
            ],
            "league_id" => $leagueId,
            "league" => $leagueName,
            "referee" => $match[32] ?? "",
            'flag' => '/assets/upload/fbcountry/' . $leagueFlag . '-flag-small.png'
        ];

        // Group matches by league
        if (!isset($leagues[$leagueId])) {
            $leagues[$leagueId] = [
                "league_id" => $leagueId,
                "leagueName" => $leagueName,
                "leagueFlag" => '/assets/upload/fbcountry/' . $leagueFlag . '-flag-small.png',
                "leagueLogo" => $leagueLogo,
                "nationId" => $leagueFlag,
                "matches" => []
            ];
        }

        $leagues[$leagueId]["matches"][] = $matchData;

        // Stop adding matches after 10 per league (optional)
        if (count($leagues[$leagueId]["matches"]) >= 10) {
            continue;
        }
    }

    return $leagues;
}

function isMobile() {
    return preg_match('/(android|iphone|ipad|ipod|mobile)/i', $_SERVER['HTTP_USER_AGENT']);
}

// Display merged data as JSON-LD
function bongdako_display_updateData() {
    $matches = bongdako_fetch_and_merge_data(DB_DOMAIN.'/gf/data/bf_th1_nt.js');
    $lastUpdated = date("Y-m-d\TH:i:s.u\Z");

    // Build the schema
    $schema = [
        '$schema' => get_option('schema1_link'),
        "@context" => get_option('schema2_link'),
        "@type" => get_option('type_text'),
        "name" => get_option('name_text'),
        "alternateName" => get_option('alternateName_text'),
        "logo" => get_option('logo_link'),
        "image" => get_option('image_link'),
        "description" => get_option('description'),
        "hasMap" => get_option('hasMap'),
        "url" => get_option('url'),
        "address" => get_option('address'),
        "geo" => [
            "@type" => get_option('type_geo'),
            "latitude" => get_option('latitude'),
            "longitude" => get_option('longitude')
        ],
        "openingHoursSpecification" => [
            "@type" => "OpeningHoursSpecification",
            "dayOfWeek" => ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
            "opens" => "09:00",
            "closes" => "18:00"
        ],
        "properties" => [
            "lastUpdated" => $lastUpdated,
            "matches" => $matches
        ]
    ];

    return json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}

function bongdako_insert_schema_in_head() {
    // Check if schema insertion is enabled
    if (!get_option('enable_schema_head', 0)) {
        return;
    }

    // Fetch the schema JSON
    $schema_json = bongdako_display_updateData();

    // Output it inside a <script> tag
    echo '<script type="application/ld+json">' 
    . $schema_json . 
    '</script>';
}

// Add to wp_head
add_action('wp_head', 'bongdako_insert_schema_in_head');