if (!defined('ABSPATH')) return;

// =======================================================
// 🗺️ TEAM ALIASES
// =======================================================
function mi_get_aliases($team) {
    $aliases_map = [
        'man city' => ['manchester city', 'man. city', 'mancity'],
        'manchester city' => ['man city', 'man. city', 'mancity'],
        'man utd' => ['manchester united', 'man united', 'manutd', 'manchester utd'],
        'manchester united' => ['man utd', 'man united', 'manutd'],
        'man united' => ['manchester united', 'man utd'],
        'psg' => ['paris saint germain', 'paris sg', 'paris saint-germain'],
        'paris saint germain'=> ['psg', 'paris sg'],
        'spurs' => ['tottenham', 'tottenham hotspur'],
        'tottenham' => ['spurs', 'tottenham hotspur'],
        'wolves' => ['wolverhampton', 'wolverhampton wanderers'],
        'inter' => ['inter milan', 'internazionale'],
        'inter milan' => ['inter', 'internazionale'],
        'ac milan' => ['milan', 'ac milan'],
        'milan' => ['ac milan'],
        'atletico' => ['atletico madrid', 'atletico de madrid'],
        'atletico madrid' => ['atletico'],
        'rb leipzig' => ['rbl', 'rasenballsport leipzig'],
        'al hilal' => ['alhilal'],
        'al nassr' => ['alnassr'],
        'lahore' => ['lahore qalandars', 'lq'],
        'multan' => ['multan sultans', 'ms'],
        'karachi' => ['karachi kings', 'kk'],
        'islamabad' => ['islamabad united', 'iu'],
        'peshawar' => ['peshawar zalmi', 'pz'],
        'quetta' => ['quetta gladiators', 'qg'],
    ];

    $team = strtolower(trim($team));
    return $aliases_map[$team] ?? [];
}

// =======================================================
// 🔤 NORMALIZE TEXT
// =======================================================
function mi_normalize($text) {
    $text = strtolower($text);
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = str_replace(['–','—','−','&amp;','&nbsp;'], [' ',' ',' ','&',' '], $text);
    $text = str_replace(['-','_','.',',',"'",'"','(',')','[',']'], ' ', $text);
    $text = preg_replace('/[^a-z0-9 ]/', '', $text);
    $text = preg_replace('/\s+/', ' ', $text);
    return trim($text);
}

// =======================================================
// 🔍 CHANNEL FINDER
// =======================================================
function mi_find_channel($blocks, $block_texts, $t1, $t2) {

    $t1_aliases = array_merge([$t1], mi_get_aliases($t1));
    $t2_aliases = array_merge([$t2], mi_get_aliases($t2));

    foreach ($block_texts as $i => $text) {

        $has_t1 = false;
        $has_t2 = false;

        foreach ($t1_aliases as $alias) {
            if (strpos($text, $alias) !== false) { $has_t1 = true; break; }
        }

        foreach ($t2_aliases as $alias) {
            if (strpos($text, $alias) !== false) { $has_t2 = true; break; }
        }

        if ($has_t1 && $has_t2) {
            return ['channel'=>$blocks[2][$i],'strategy'=>'Both Teams Match'];
        }
    }

    $t1_partial = substr($t1,0,4);
    $t2_partial = substr($t2,0,4);

    foreach ($block_texts as $i => $text) {

        foreach ($t1_aliases as $alias) {
            if (strpos($text,$alias)!==false && strlen($t2_partial)>=3 && strpos($text,$t2_partial)!==false) {
                return ['channel'=>$blocks[2][$i],'strategy'=>"T1 Alias '{$alias}' + T2 Partial"];
            }
        }

        foreach ($t2_aliases as $alias) {
            if (strpos($text,$alias)!==false && strlen($t1_partial)>=3 && strpos($text,$t1_partial)!==false) {
                return ['channel'=>$blocks[2][$i],'strategy'=>"T2 Alias '{$alias}' + T1 Partial"];
            }
        }
    }

    if (strlen($t1)>5) {
        foreach ($block_texts as $i=>$text) {
            foreach ($t1_aliases as $alias) {
                if (strpos($text,$alias)!==false) {
                    return ['channel'=>$blocks[2][$i],'strategy'=>"Single Team '{$alias}'"];
                }
            }
        }
    }

    if (strlen($t2)>5) {
        foreach ($block_texts as $i=>$text) {
            foreach ($t2_aliases as $alias) {
                if (strpos($text,$alias)!==false) {
                    return ['channel'=>$blocks[2][$i],'strategy'=>"Single Team '{$alias}'"];
                }
            }
        }
    }

    return null;
}

// =======================================================
// 🎨 ADMIN MENU
// =======================================================
add_action('admin_menu', function() {
    add_menu_page(
        'Match Importer PRO',
        'Match Importer',
        'manage_options',
        'match-importer',
        'match_importer_page',
        'dashicons-update',
        30
    );
});

// =======================================================
// 🖥️ ADMIN PAGE
// =======================================================
function match_importer_page() {

    if (isset($_POST['run_import'])) {
        echo '<div style="background:#000;color:#0f0;padding:15px">';
        auto_match_importer_run(true);
        echo '</div>';
    }

    echo '<div class="wrap"><h1>Match Importer</h1>
    <form method="post">
    <button name="run_import" class="button button-primary">Run Import</button>
    </form></div>';
}

// =======================================================
// ⚙️ CRON
// =======================================================
add_action('mi_hourly_cron','auto_match_importer_run');

if (!wp_next_scheduled('mi_hourly_cron')) {
    wp_schedule_event(time(),'hourly','mi_hourly_cron');
}

// =======================================================
// 🚀 MAIN FUNCTION
// =======================================================
function auto_match_importer_run($manual=false){

    $res = wp_remote_get('https://totalsportekx.is/');
    if (is_wp_error($res)) return;

    $html = wp_remote_retrieve_body($res);

    preg_match_all('/href="https:\/\/totalsportekx.is\/game\/([^"\/]+)\//i',$html,$matches);

    if (empty($matches[1])) return;

    $slugs = array_unique($matches[1]);
    $events = [];

    foreach ($slugs as $slug){
        $parts = explode('-vs-',$slug);
        if(count($parts)!==2) continue;

        $t1 = ucwords(str_replace('-',' ',$parts[0]));
        $t2 = ucwords(str_replace('-',' ',$parts[1]));

        $events[] = [
            'title'=>"$t1 vs $t2",
            't1'=>mi_normalize($t1),
            't2'=>mi_normalize($t2)
        ];
    }

    $res2 = wp_remote_get('https://linesportz.shop/index.php/feed/');
    if (is_wp_error($res2)) return;

    $html2 = wp_remote_retrieve_body($res2);

    preg_match_all('/(.{0,600}?)CH-(\d+)/i',$html2,$blocks);

    if(empty($blocks[0])) return;

    $block_texts=[];
    foreach($blocks[0] as $i=>$raw){
        $block_texts[$i]=mi_normalize(strip_tags($raw));
    }

    foreach($events as $event){

        $exists = get_page_by_title($event['title'],'OBJECT','post');
        if($exists) continue;

        $result = mi_find_channel($blocks,$block_texts,$event['t1'],$event['t2']);
        if(!$result) continue;

        wp_insert_post([
            'post_title'=>$event['title'],
            'post_content'=>'[match_stream id="'.$result['channel'].'"]',
            'post_status'=>'publish',
            'post_author'=>1
        ]);
    }
}<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="https://ripplenetwork.forum/wp-sitemap-index.xsl" ?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><sitemap><loc>https://ripplenetwork.forum/wp-sitemap-posts-post-1.xml</loc></sitemap><sitemap><loc>https://ripplenetwork.forum/wp-sitemap-posts-page-1.xml</loc></sitemap><sitemap><loc>https://ripplenetwork.forum/wp-sitemap-taxonomies-category-1.xml</loc></sitemap><sitemap><loc>https://ripplenetwork.forum/wp-sitemap-users-1.xml</loc></sitemap></sitemapindex>
