<?php
require_once 'db.php';
$instansi_id = 1;

$stmt_instansi = $pdo->prepare("SELECT * FROM instansi WHERE id = ?");
$stmt_instansi->execute([$instansi_id]);
$instansi = $stmt_instansi->fetch(PDO::FETCH_ASSOC);

$keywords_raw = trim($instansi['keyword_global']);
$keyword_list = array_filter(array_map('trim', explode(',', $keywords_raw)));
$instansi_entities = [];
foreach ($keyword_list as $kw) {
    $instansi_entities[] = ['entity' => $kw, 'type' => 'target', 'score' => 50];
}

$url = 'https://liputan24.net/?s=banjarbaru&feed=rss2';
$res = file_get_contents($url);
$rss_content = preg_replace('/xmlns[^=]*="[^"]*"/i', '', $res);
$rss = @simplexml_load_string($rss_content, 'SimpleXMLElement', LIBXML_NOCDATA);

foreach ($rss->channel->item as $item) {
    $judul = isset($item->title) ? strip_tags((string)$item->title) : '';
    $deskripsi = strip_tags(isset($item->description) ? (string)$item->description : ((string)$item->content ?: (string)$item->summary));
    
    $judul_lower = strtolower($judul);
    $desc_lower = strtolower($deskripsi);
    
    $matched_target_kws = [];
    $score = 0;
    foreach ($instansi_entities as $rule) {
        $entity = strtolower($rule['entity']);
        $pattern = '/\b' . preg_quote($entity, '/i') . '\b/i';
        
        if (preg_match($pattern, $judul_lower) || preg_match($pattern, $desc_lower)) {
            $score += $rule['score'];
            $matched_target_kws[] = $entity;
        }
    }
    
    echo "Judul: " . substr($judul, 0, 50) . "...\n";
    echo "Score: $score, Matched: " . implode(', ', $matched_target_kws) . "\n\n";
}
