<?php

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

// ----------------------
// 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);

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

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

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

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

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

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

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

    $html = @file_get_contents($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;
        }

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

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

// Extract actual date from strings like:
// "Corporate / 27 February 2026"

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);
    }
}

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

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

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

echo "Done.";

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

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

$cleanupStmt->execute();

?>