<?php
/**
 * index_config/bludit.php
 * ─────────────────────────────────────────────────────────────────────────────
 * Fetches the latest posts from a Bludit blog via its REST API.
 * Returns an array of post arrays, or an empty array on failure.
 *
 * Requires BLUDIT_URL, BLUDIT_API_TOKEN, BLUDIT_POST_COUNT,
 *          BLUDIT_SNIPPET_LEN, BLUDIT_CACHE_TTL  (all set in config.php).
 *
 * Usage (from index.php):
 *   $blog_posts = bludit_get_posts();
 */

function bludit_get_posts(): array {
    // Bail early if not configured
    if (!defined('BLUDIT_API_TOKEN') || BLUDIT_API_TOKEN === '') {
        return [];
    }

    $cache_file = sys_get_temp_dir() . '/tc_bludit_cache_' . md5(BLUDIT_URL) . '.json';
    $ttl        = (int)(BLUDIT_CACHE_TTL ?? 300);

    // Serve from cache if fresh
    if ($ttl > 0 && file_exists($cache_file) && (time() - filemtime($cache_file)) < $ttl) {
        $cached = json_decode(file_get_contents($cache_file), true);
        if (is_array($cached)) return $cached;
    }

    // Build API request
    $api_url = rtrim(BLUDIT_URL, '/') . '/api/pages';
    $count   = max(1, min(20, (int)(BLUDIT_POST_COUNT ?? 5)));

    $ctx = stream_context_create([
        'http' => [
            'method'  => 'GET',
            'header'  => implode("\r\n", [
                'X-Bludit-API-Token: ' . BLUDIT_API_TOKEN,
                'Accept: application/json',
            ]),
            'timeout' => 5,
            'ignore_errors' => true,
        ],
        'ssl' => ['verify_peer' => true],
    ]);

    $raw = @file_get_contents($api_url, false, $ctx);
    if ($raw === false) return [];

    $data = json_decode($raw, true);
    if (!isset($data['data']) || !is_array($data['data'])) return [];

    $snippet_len = (int)(BLUDIT_SNIPPET_LEN ?? 110);
    $posts       = [];

    foreach (array_slice($data['data'], 0, $count) as $page) {
        // Skip drafts / non-published
        if (($page['type'] ?? '') !== 'published') continue;

        // Build snippet from content (strip HTML, collapse whitespace)
        $raw_body = $page['content'] ?? $page['contentRaw'] ?? '';
        $plain    = preg_replace('/\s+/', ' ', strip_tags(html_entity_decode($raw_body)));
        $snippet  = mb_strlen($plain) > $snippet_len
            ? mb_substr($plain, 0, $snippet_len) . '…'
            : $plain;

        $posts[] = [
            'title'   => html_entity_decode($page['title'] ?? 'Untitled'),
            'snippet' => $snippet,
            'url'     => $page['permalink'] ?? (rtrim(BLUDIT_URL, '/') . '/' . ($page['key'] ?? '')),
            'date'    => $page['date'] ?? '',
            'tags'    => array_values((array)($page['tags'] ?? [])),
        ];

        if (count($posts) >= $count) break;
    }

    // Cache result
    if ($ttl > 0 && !empty($posts)) {
        file_put_contents($cache_file, json_encode($posts), LOCK_EX);
    }

    return $posts;
}
