<?php
function fetch_url_content($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    $html = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($http_code === 200) ? $html : false;
}

function normalize_image_url($url, $base_url) {
    $url = trim($url);
    if ($url === '' || strpos($url, '...') !== false) {
        return 'https://via.placeholder.com/150x80?text=No+Image';
    }
    if (preg_match('#^https?://#i', $url)) return $url;
    
    $parsed = parse_url($base_url);
    $host = $parsed['scheme'].'://'.$parsed['host'];
    if (isset($parsed['port'])) $host .= ':'.$parsed['port'];
    if ($url[0] !== '/') $url = '/'.$url;
    return $host.$url;
}

function fetch_fake_social_data() {
    // Append a cache-busting query string (timestamp) to the JSON URL
    $json_url = 'https://alceawis.de/other/extra/scripts/fakesocialmedia/0ld/data_akkoma.json?nocache=' . time();
    $json_data = fetch_url_content($json_url);
    
    if (!$json_data) return [];
    
    $data = json_decode($json_data, true);
    $preview_links = [];
    
    foreach ($data as $item) {
        if (isset($item['preview']) && !empty($item['preview'])) {
            $preview_links[] = [
                'preview' => $item['preview'],
                'url' => $item['url']
            ];
        }
    }
    
    return $preview_links;
}

function check_social_match($article_link, $social_data) {
    foreach ($social_data as $social_item) {
        // Check if the article link contains the social preview text or vice versa
        if (strpos($article_link, $social_item['preview']) !== false || 
            strpos($social_item['preview'], $article_link) !== false) {
            return $social_item['url'];
        }
    }
    return false;
}

function parse_articles_regex($html, $base_url, $blocked_domains, $social_data) {
    $articles = [];
    $pattern = '#<div\s+class=["\']item[^"\']*["\'][^>]*>.*?<img[^>]*src=["\']([^"\']+)["\'][^>]*>.*?<h2[^>]*class=["\']heading[^"\']*["\'][^>]*>\s*<a[^>]*href=["\']([^"\']+)["\'][^>]*>(.*?)</a>.*?(<p[^>]*class=["\']summary[^"\']*["\']>(.*?)</p>)?.*?data-timestamp=["\']([^"\']+)["\']#si';

    if (preg_match_all($pattern, $html, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $m) {
            $link = trim($m[2]);
            $blocked = false;
            foreach ($blocked_domains as $d) {
                if (stripos($link, $d) !== false) {
                    $blocked = true;
                    break;
                }
            }
            if ($blocked) continue;

            $host = parse_url($link, PHP_URL_HOST);
            $badge = strtoupper(preg_replace('/^www\./','',$host));
            
            // Check if this article has a matching social media post
            $social_url = check_social_match($link, $social_data);

            $articles[] = [
                'image' => normalize_image_url($m[1], $base_url),
                'link' => $link,
                'title' => trim(htmlspecialchars_decode($m[3])),
                'excerpt' => isset($m[5]) ? trim(htmlspecialchars_decode($m[5])) : '',
                'badge' => $badge,
                'date' => isset($m[6]) ? $m[6] : '',
                'social_url' => $social_url
            ];
        }
    }

    return $articles;
}

$base_url = 'https://nintendonews.com/news';
$blocked_domains = ['nintendolife.de','nintendoeverything.com'];
$per_page = 10;

// Fetch social media data
$social_data = fetch_fake_social_data();

$page_param = isset($_GET['page']) ? max(1,intval($_GET['page'])) : 1;
$autopage = isset($_GET['autopage']);

$url = $base_url . '?page=' . $page_param;
$html = fetch_url_content($url);
$all_articles = $html ? parse_articles_regex($html, $base_url, $blocked_domains, $social_data) : [];

$total_articles = count($all_articles);
$total_pages = 100;
$current_page = $page_param;
$articles_to_show = $all_articles;

if ($autopage && isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'articles' => $articles_to_show,
        'current' => $current_page,
        'total' => $total_pages
    ]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Nintendo News</title>
    <style>
        body{font-family:Arial,sans-serif;}
        .article{position:relative;border:1px solid #ccc;margin-bottom:10px;padding:15px;border-radius:8px;display:flex;gap:15px;}
        .article img{max-width:150px;border-radius:4px;}
        .badge{position:absolute;bottom:5px;right:10px;font-size:11px;color:#666;background:#f2f2f2;padding:2px 6px;border-radius:3px;}
        .date{position:absolute;top:5px;left:10px;font-size:11px;color:#333;background:#fff;padding:2px 6px;border-radius:3px;border:1px solid #ccc;}
        #page-indicator{position:fixed;bottom:10px;right:10px;font-size:12px;color:#444;background:#eee;padding:2px 6px;border-radius:4px;}
        .social-iframe{width:100%;height:300px;border:1px solid #ddd;margin-top:10px;border-radius:4px;}
    </style>
</head>
<body>
    <h1>Latest Nintendo News</h1>
    <ul id="article-list" style="list-style:none;padding:0;">
        <?php foreach($articles_to_show as $a): ?>
        <li class="article">
            <div class="date"><?=htmlspecialchars($a['date'])?></div>
            <div><img src="<?=htmlspecialchars($a['image'])?>" alt="<?=htmlspecialchars($a['title'])?>"></div>
            <div>
                <h3><a href="<?=htmlspecialchars($a['link'])?>" target="_blank"><?=htmlspecialchars($a['title'])?></a></h3>
                <p><?=htmlspecialchars($a['excerpt'])?></p>
            </div>
            <span class="badge"><?=htmlspecialchars($a['badge'])?></span>
            
            <?php if ($a['social_url']): ?>
            <div style="width:100%;margin-top:10px;">
                <!-- Display the full social URL above the iframe in small text -->
                <div style="font-size:8px;color:#888;margin-bottom:4px;word-wrap:break-word;">
                    <?=htmlspecialchars($a['social_url'])?>
                </div>
                <iframe src="replyhandlerfull.html?url=<?=urlencode($a['social_url'])?>" class="social-iframe"></iframe>
            </div>
            <?php endif; ?>
        </li>
        <?php endforeach; ?>
    </ul>

    <div id="page-indicator">Page <?=$current_page?></div>

    <script>
        let currentPage = <?=$current_page?>;
        let loading = false;
        const indicator = document.getElementById('page-indicator');
        const list = document.getElementById('article-list');

        window.addEventListener('scroll', async () => {
            if (loading) return;
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 100) {
                loading = true;
                const next = currentPage + 1;
                const resp = await fetch(`?autopage=1&page=${next}&ajax=1`);
                const data = await resp.json();
                if (data.articles.length === 0) return;
                
                data.articles.forEach(a => {
                    const li = document.createElement('li');
                    li.className = 'article';
                    
                    let socialIframe = '';
                    if (a.social_url) {
                        socialIframe = `<div style="width:100%;margin-top:10px;">
                            <!-- Display the full social URL above the iframe in small text -->
                            <div style="font-size:8px;color:#888;margin-bottom:4px;word-wrap:break-word;">
                                ${a.social_url}
                            </div>
                            <iframe src="replyhandlerfull.html?url=${encodeURIComponent(a.social_url)}" class="social-iframe"></iframe>
                        </div>`;
                    }
                    
                    li.innerHTML = `
                        <div class="date">${a.date}</div>
                        <div><img src="${a.image}" alt="${a.title}"></div>
                        <div>
                            <h3><a href="${a.link}" target="_blank">${a.title}</a></h3>
                            <p>${a.excerpt}</p>
                        </div>
                        <span class="badge">${a.badge}</span>
                        ${socialIframe}
                    `;
                    list.appendChild(li);
                });
                
                currentPage = next;
                indicator.textContent = `Page ${currentPage}`;
                loading = false;
            }
        });
    </script>
</body>
</html>
