<?php

require_once __DIR__ . '/../config.php';

// ----------------------
// CURL FETCH FUNCTION
// ----------------------

function fetchUrl($url)
{
    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0 Safari/537.36',
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);

    $response = curl_exec($ch);

    curl_close($ch);

    return $response;
}

// ----------------------
// EXTRACT ARTICLE CONTENT
// ----------------------

function extractArticleContent($url)
{
    $html = fetchUrl($url);

    if (!$html) {
        return [
            'content' => null,
            'image' => null,
            'status' => 'failed'
        ];
    }

    libxml_use_internal_errors(true);

    $dom = new DOMDocument();
    $dom->loadHTML($html);

    $xpath = new DOMXPath($dom);

    // ----------------------
    // CONTENT EXTRACTION
    // ----------------------

    $content = null;

$queries = [
    "//article",
    "//*[contains(@class, 'article-body')]",
    "//*[contains(@class, 'article-content')]",
    "//*[contains(@class, 'entry-content')]",
    "//*[contains(@class, 'post-content')]",
    "//*[contains(@class, 'post-body')]",
    "//*[contains(@class, 'body-content')]",
    "//*[contains(@class, 'rich-text')]",
    "//*[contains(@class, 'content-body')]",
    "//*[contains(@class, 'story-body')]",
    "//*[contains(@class, 'news-content')]",
    "//*[contains(@class, 'content')]",
    "//main"
];

foreach ($queries as $query) {

    $nodes = $xpath->query($query);

    if ($nodes->length > 0) {

        foreach ($nodes as $node) {

            $text = trim($node->textContent);

            // Keep the LONGEST valid block
            if (
                !empty($text) &&
                strlen($text) > 200 &&
                strlen($text) > strlen($content ?? '')
            ) {
                $content = preg_replace('/\s+/', ' ', $text);
            }
        }
    }
}
    // ----------------------
    // LIMIT CONTENT LENGTH
    // ----------------------

    if ($content) {
        $content = substr($content, 0, 20000);
    }

    // ----------------------
    // FEATURED IMAGE
    // ----------------------

    $featuredImage = null;

    $imageNode = $xpath->query(
        "//meta[@property='og:image']"
    )->item(0);

    if ($imageNode) {
        $featuredImage = trim(
            $imageNode->getAttribute('content')
        );
    }

    return [
        'content' => $content,
        'image' => $featuredImage,
        'status' => $content ? 'success' : 'partial'
    ];
}

// ----------------------
// GET ACTIVE FEEDS
// ----------------------

$stmt = $pdo->query("
    SELECT *
    FROM media_sources
    WHERE is_active = 1
");

$sources = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ----------------------
// LOOP FEEDS
// ----------------------

foreach ($sources as $source) {

// ----------------------
// RSS FEEDS
// ----------------------

if ($source['type'] === 'rss') {

    echo "Checking RSS: " . $source['name'] . PHP_EOL;

    $rss = @simplexml_load_file($source['feed_url']);

    if (!$rss || empty($rss->channel->item)) {
        echo "Failed to load RSS feed." . PHP_EOL;
        continue;
    }

    foreach ($rss->channel->item as $item) {

        $title = trim((string)$item->title);
        $url = trim((string)$item->link);

        if (empty($title) || empty($url)) {
            continue;
        }

        $published = !empty($item->pubDate)
            ? date('Y-m-d H:i:s', strtotime((string)$item->pubDate))
            : date('Y-m-d H:i:s');

        // ----------------------
        // EXTRACT ARTICLE
        // ----------------------

        echo "Extracting article: " . $title . PHP_EOL;

        $articleData = extractArticleContent($url);

        // ----------------------
        // INSERT
        // ----------------------

        $insertStmt = $pdo->prepare("
            INSERT IGNORE INTO media_alerts (
                source_name,
                title,
                url,
                published_at,
                article_content,
                featured_image,
                extraction_status
            )
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");

        $insertStmt->execute([
            $source['name'],
            $title,
            $url,
            $published,
            $articleData['content'],
            $articleData['image'],
            $articleData['status']
        ]);

        echo "Added RSS: " . $title . PHP_EOL;
    }
}

// ----------------------
// HTML FEEDS
// ----------------------

if ($source['type'] === 'html') {

    echo "Checking HTML: " . $source['name'] . PHP_EOL;

    $html = fetchUrl($source['feed_url']);

    if (!$html) {
        echo "Failed to load HTML page." . PHP_EOL;
        continue;
    }

    libxml_use_internal_errors(true);

    $dom = new DOMDocument();
    $dom->loadHTML($html);

    $xpath = new DOMXPath($dom);

    // Merlin newsroom items
    $articles = $xpath->query("//*[contains(@class, 'news-item')]");

    foreach ($articles as $article) {

        $linkNode = $xpath->query(
            ".//a[contains(@href, '/newsroom/news-releases/')]",
            $article
        )->item(0);

        $dateNode = $xpath->query(
            ".//span[contains(@class, 'news-item__date')]",
            $article
        )->item(0);

        if (!$linkNode || !$dateNode) {
            continue;
        }

        $title = trim($linkNode->nodeValue);
        $url = trim($linkNode->getAttribute('href'));

        if (empty($title) || empty($url)) {
            continue;
        }

        // Convert relative URLs
        if (!str_starts_with($url, 'http')) {
            $url = 'https://www.merlinentertainments.biz' . $url;
        }

        // ----------------------
        // PUBLISHED DATE
        // ----------------------

        $published = date('Y-m-d H:i:s');

        $dateText = trim($dateNode->nodeValue);

        if (preg_match('/\d{1,2}\s+[A-Za-z]+\s+\d{4}/', $dateText, $matches)) {

            $parsedDate = strtotime($matches[0]);

            if ($parsedDate !== false) {
                $published = date('Y-m-d H:i:s', $parsedDate);
            }
        }

        // ----------------------
        // EXTRACT ARTICLE
        // ----------------------

        echo "Extracting article: " . $title . PHP_EOL;

        $articleData = extractArticleContent($url);

        // ----------------------
        // INSERT
        // ----------------------

        $insertStmt = $pdo->prepare("
            INSERT IGNORE INTO media_alerts (
                source_name,
                title,
                url,
                published_at,
                article_content,
                featured_image,
                extraction_status
            )
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");

        $insertStmt->execute([
            $source['name'],
            $title,
            $url,
            $published,
            $articleData['content'],
            $articleData['image'],
            $articleData['status']
        ]);

        echo "Added HTML: " . $title . PHP_EOL;
    }
}
}

echo "Done." . PHP_EOL;

// ----------------------
// CLEAN OLD ALERTS
// ----------------------

$cleanupStmt = $pdo->prepare("
    DELETE FROM media_alerts
    WHERE published_at < NOW() - INTERVAL 60 DAY
");

$cleanupStmt->execute();

?>