<?php
// ============================================================
// come2canada.life — Cron Job: News-Scanner
// Datei hochladen als: /c2c/cron/cron_news.php
//
// cPanel Cron Job einrichten:
// Zeitplan: 0 7 * * * (täglich um 07:00)
// Befehl:   php /home/DEINUSER/public_html/c2c/cron/cron_news.php
// ============================================================

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

$feeds = [
    [
        'url'      => 'https://www.canada.ca/en/news/advanced-news-search/news-results.atom?typ=backgrounders&dprtmnt=departmentofcitizenshipandimmigration&start=2024-01-01&end=2099-12-31',
        'kategorie'=> 'Backgrounders',
    ],
    [
        'url'      => 'https://api.io.canada.ca/io-server/gc/news/en/v2?dept=departmentofcitizenshipandimmigration&type=newsrelease&atomEntriesOnly=true&sortOrder=publishedDate&orderDir=desc&pagenum=1&pagesize=20&format=atom',
        'kategorie'=> 'News Release',
    ],
    [
        'url'      => 'https://api.io.canada.ca/io-server/gc/news/en/v2?dept=departmentofcitizenshipandimmigration&type=statement&atomEntriesOnly=true&sortOrder=publishedDate&orderDir=desc&pagenum=1&pagesize=10&format=atom',
        'kategorie'=> 'Statement',
    ],
];

$neu = 0;
$fehler = 0;

foreach ($feeds as $feed) {
    $result = processFeed($feed['url'], $feed['kategorie']);
    $neu    += $result['neu'];
    $fehler += $result['fehler'];
}

// Log
logAktivitaet('news_scan', null, "Neu: $neu · Fehler: $fehler");
echo date('Y-m-d H:i:s') . " — News-Scan abgeschlossen. Neu: $neu, Fehler: $fehler\n";

// ── FEED VERARBEITEN ─────────────────────────────────────────

function processFeed(string $url, string $kategorie): array {
    $neu = 0; $fehler = 0;

    $xml = fetchUrl($url);
    if (!$xml) {
        echo "Fehler beim Laden: $url\n";
        return ['neu' => 0, 'fehler' => 1];
    }

    try {
        $feed = new SimpleXMLElement($xml);
    } catch (Exception $e) {
        echo "XML-Parse-Fehler: " . $e->getMessage() . "\n";
        return ['neu' => 0, 'fehler' => 1];
    }

    // Atom-Namespaces
    $entries = $feed->entry ?? [];

    foreach ($entries as $entry) {
        $guid  = trim((string)($entry->id ?? ''));
        $titel = trim((string)($entry->title ?? ''));
        $link  = '';

        foreach ($entry->link as $l) {
            if ((string)$l['rel'] === 'alternate' || empty((string)$l['rel'])) {
                $link = (string)$l['href'];
                break;
            }
        }
        if (!$link) $link = $guid;

        $pubDate = null;
        if (!empty($entry->published)) {
            $pubDate = date('Y-m-d H:i:s', strtotime((string)$entry->published));
        } elseif (!empty($entry->updated)) {
            $pubDate = date('Y-m-d H:i:s', strtotime((string)$entry->updated));
        }

        if (!$guid || !$titel) continue;

        // Duplikat-Check
        $check = db()->prepare("SELECT id FROM news WHERE guid = ?");
        $check->execute([$guid]);
        if ($check->fetch()) continue;

        // Titel auf Deutsch übersetzen
        $titelDe = translateTitle($titel);

        // In DB speichern
        try {
            $stmt = db()->prepare("
                INSERT INTO news (guid, titel_en, titel_de, link, kategorie, publiziert_am)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$guid, $titel, $titelDe, $link, $kategorie, $pubDate]);
            $neu++;
            echo "Neu: $titelDe\n";
        } catch (Exception $e) {
            echo "DB-Fehler: " . $e->getMessage() . "\n";
            $fehler++;
        }
    }

    return ['neu' => $neu, 'fehler' => $fehler];
}

// ── TITEL ÜBERSETZEN (Anthropic) ─────────────────────────────

function translateTitle(string $title): string {
    if (empty(trim($title))) return $title;

    $payload = json_encode([
        'model'      => ANTHROPIC_MODEL,
        'max_tokens' => 150,
        'messages'   => [[
            'role'    => 'user',
            'content' => "Übersetze diesen kanadischen Einwanderungs-News-Titel ins Deutsche. Nur die Übersetzung, kein anderer Text:\n\n$title"
        ]],
    ]);

    $ch = curl_init('https://api.anthropic.com/v1/messages');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'x-api-key: ' . ANTHROPIC_API_KEY,
            'anthropic-version: 2023-06-01',
        ],
    ]);
    $raw  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code !== 200 || !$raw) return $title;

    $resp = json_decode($raw, true);
    $text = trim($resp['content'][0]['text'] ?? '');
    return $text ?: $title;
}

// ── HTTP FETCH ────────────────────────────────────────────────

function fetchUrl(string $url): ?string {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT      => 'come2canada.life News Scanner/1.0',
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $data = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($code === 200 && $data) ? $data : null;
}
