<?php
// x_feed.php  (PHP 5.6)
// Muestra un RSS como tabla simple + cache local para no golpear el feed siempre.

header('Content-Type: text/html; charset=utf-8');

$feed_url = 'https://nitter.poast.org/clarincom/rss'; // probá cambiar por otra instancia si falla
$cache_dir = __DIR__ . '/cache';
$cache_file = $cache_dir . '/clarincom_rss.xml';
$cache_ttl = 300; // 5 min

if (!is_dir($cache_dir)) {
    @mkdir($cache_dir, 0755, true);
}

function fetch_url($url) {
    // cURL (más compatible que allow_url_fopen)
    if (!function_exists('curl_init')) return false;

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (RSS fetch; +https://example.com)');

    $body = curl_exec($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http >= 200 && $http < 300 && $body && strpos($body, '<') !== false) return $body;
    return false;
}

function h($s) {
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

// Cache: si está fresco, usarlo; si no, intentar refrescar
$xml_raw = false;
if (file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_ttl)) {
    $xml_raw = file_get_contents($cache_file);
} else {
    $fresh = fetch_url($feed_url);
    if ($fresh !== false) {
        $xml_raw = $fresh;
        file_put_contents($cache_file, $fresh);
    } elseif (file_exists($cache_file)) {
        // fallback: usar cache viejo si existe
        $xml_raw = file_get_contents($cache_file);
    }
}

if (!$xml_raw) {
    echo "<h3>No pude leer el feed.</h3>";
    echo "<p>Probá cambiando <b>\$feed_url</b> por otra instancia de Nitter, o usá RSS.app.</p>";
    echo "<p>URL actual:</p><pre>" . h($feed_url) . "</pre>";
    exit;
}

// Parse RSS
libxml_use_internal_errors(true);
$xml = simplexml_load_string($xml_raw);
if (!$xml) {
    echo "<h3>El XML llegó pero no se pudo parsear.</h3>";
    echo "<pre>" . h(substr($xml_raw, 0, 2000)) . "</pre>";
    exit;
}

// Nitter suele devolver RSS 2.0: $xml->channel->item
$items = array();
if (isset($xml->channel->item)) {
    foreach ($xml->channel->item as $it) {
        $title = (string)$it->title;
        $link  = (string)$it->link;
        $date  = (string)$it->pubDate;
        $ts = $date ? strtotime($date) : 0;
        $items[] = array(
            'date' => $ts ? date('Y-m-d H:i', $ts) : '',
            'title' => $title,
            'link' => $link
        );
        if (count($items) >= 30) break;
    }
}

?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Feed @clarincom (RSS)</title>
  <style>
    body{font-family:Arial, sans-serif; padding:16px;}
    table{border-collapse:collapse; width:100%;}
    th,td{border:1px solid #ddd; padding:10px; vertical-align:top;}
    th{background:#f4f4f4; text-align:left;}
    .muted{color:#666; font-size:12px;}
  </style>
</head>
<body>

<h2>Feed @clarincom (RSS)</h2>
<div class="muted">Fuente: <?php echo h($feed_url); ?></div>

<?php if (empty($items)) { ?>
  <p>No hay items para mostrar. Puede ser bloqueo/limitación de la instancia.</p>
<?php } else { ?>
  <table>
    <thead>
      <tr>
        <th style="width:170px;">Fecha</th>
        <th>Título</th>
        <th style="width:120px;">Link</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($items as $r) { ?>
        <tr>
          <td><?php echo h($r['date']); ?></td>
          <td><?php echo h($r['title']); ?></td>
          <td><a target="_blank" rel="noopener" href="<?php echo h($r['link']); ?>">abrir</a></td>
        </tr>
      <?php } ?>
    </tbody>
  </table>
<?php } ?>

</body>
</html>