<?php
/**
 * Personal Feed API — Hiking, Sport Bikes, 3-Wheelers, Wu-Tang Clan
 * Sources: Reddit JSON API (no key), National Park Service API (free)
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$cacheFile = __DIR__ . '/../uploads/personal_cache.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 1800) {
    header('Content-Type: application/json');
    readfile($cacheFile);
    exit;
}

function fetchUrl($url, $timeout = 10) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => '',
        CURLOPT_USERAGENT => 'linux:cfdportal:v1.0 (by /u/cfdportal)',
    ]);
    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($code >= 200 && $code < 400) ? $res : false;
}

function parseReddit($subreddit, $category, $limit = 8) {
    // Use RSS/Atom feed — more reliable from shared hosting than JSON API
    $url = "https://www.reddit.com/r/{$subreddit}/hot.rss?limit={$limit}";
    $raw = fetchUrl($url);
    if (!$raw) return [];

    libxml_use_internal_errors(true);
    $xml = simplexml_load_string($raw);
    if (!$xml) return [];

    $ns = $xml->getNamespaces(true);
    $posts = [];

    foreach ($xml->entry as $entry) {
        $title = html_entity_decode((string)($entry->title ?? ''), ENT_QUOTES, 'UTF-8');
        $link = (string)($entry->link['href'] ?? '');
        $author = '';
        if (isset($entry->author->name)) {
            $author = str_replace('/u/', '', (string)$entry->author->name);
        }
        $published = (string)($entry->published ?? $entry->updated ?? '');
        $content = (string)($entry->content ?? '');

        // Extract image from media:thumbnail or content HTML
        $image = '';
        if (isset($ns['media'])) {
            $media = $entry->children($ns['media']);
            if (isset($media->thumbnail)) {
                $image = (string)$media->thumbnail->attributes()->url;
            }
        }
        // Also try to find larger image in content HTML
        if (preg_match('/img\s+src="([^"]+)"/i', $content, $imgMatch)) {
            $contentImg = html_entity_decode($imgMatch[1], ENT_QUOTES, 'UTF-8');
            // Upgrade thumbnail to full size
            if (strpos($contentImg, 'preview.redd.it') !== false) {
                $image = preg_replace('/width=\d+&amp;height=\d+/', 'width=640&height=480', $contentImg);
                $image = str_replace('&amp;', '&', $image);
            } elseif (!$image) {
                $image = $contentImg;
            }
        }
        // Upgrade small thumbnails
        if ($image && strpos($image, 'width=140') !== false) {
            $image = str_replace(['width=140', 'height=140', 'crop=1:1,smart'], ['width=640', 'height=480', ''], $image);
        }

        // Extract text snippet from content
        $selftext = strip_tags(html_entity_decode($content, ENT_QUOTES, 'UTF-8'));
        $selftext = trim(preg_replace('/\s+/', ' ', $selftext));
        // Remove "[link] [comments]" and "submitted by /u/..."
        $selftext = preg_replace('/submitted by.*$/i', '', $selftext);
        $selftext = preg_replace('/\[link\].*$/i', '', $selftext);

        $posts[] = [
            'title' => $title,
            'image' => $image,
            'url' => $link,
            'score' => 0,
            'comments' => 0,
            'author' => $author,
            'created' => $published ? date('c', strtotime($published)) : date('c'),
            'subreddit' => $subreddit,
            'category' => $category,
            'source' => 'reddit',
            'hasImage' => !empty($image),
            'selftext' => substr($selftext, 0, 200),
        ];
    }

    return $posts;
}

// Wu-Tang wisdom quotes
$wuQuotes = [
    ["Cash Rules Everything Around Me — C.R.E.A.M., get the money, dollar dollar bill y'all.", "Wu-Tang Clan"],
    ["The sword style is immensely strong and eternally eternal.", "GZA"],
    ["Life is a beautiful struggle.", "Method Man"],
    ["Knowledge is the foundation.", "RZA"],
    ["Protect ya neck.", "Wu-Tang Clan"],
    ["I bomb atomically, Socrates' philosophies and hypotheses.", "Inspectah Deck"],
    ["It's been twenty-two long hard years, I'm still standin'.", "Raekwon"],
    ["Diversify your bonds.", "Wu-Tang Financial"],
    ["Wu-Tang is for the children.", "ODB"],
    ["The game of chess is like a sword fight. You must think first before you move.", "RZA"],
    ["Fear is stronger than love. Remember that.", "GZA"],
    ["I think everybody should get rich and famous so they can see that it's not the answer.", "ODB"],
    ["Half of what I say is meaningless, but I say it so that the other half may reach you.", "RZA"],
    ["We was too poor to have heroes. We was our own heroes.", "Ghostface Killah"],
];

// Fetch all feeds
$hiking = array_merge(
    parseReddit('hiking', 'hiking', 6),
    parseReddit('CampingandHiking', 'hiking', 4)
);

$bikes = array_merge(
    parseReddit('sportbikes', 'bikes', 5),
    parseReddit('motorcycles', 'bikes', 5)
);

$trikes = array_merge(
    parseReddit('canam', 'trikes', 5),
    parseReddit('Slingshot', 'trikes', 3),
    parseReddit('CanAmRyker', 'trikes', 2)
);

$wutang = parseReddit('wutang', 'wutang', 8);

// National Park Service bonus content for hiking
$npsKey = 'qAlRM8JfAoLVMPmXMxDpJfmIKCjxRGaEhnaFR3MV';
$npsRaw = fetchUrl("https://developer.nps.gov/api/v1/parks?limit=5&sort=-relevanceScore&q=hiking%20trail&api_key={$npsKey}");
$npsPosts = [];
if ($npsRaw) {
    $npsData = json_decode($npsRaw, true);
    foreach (($npsData['data'] ?? []) as $park) {
        $img = '';
        foreach (($park['images'] ?? []) as $i) {
            if (!empty($i['url'])) { $img = $i['url']; break; }
        }
        $npsPosts[] = [
            'title' => ($park['fullName'] ?? '') . ' — ' . ($park['states'] ?? ''),
            'image' => $img,
            'url' => $park['url'] ?? '',
            'score' => 0,
            'comments' => 0,
            'author' => 'National Park Service',
            'created' => date('c'),
            'subreddit' => 'NPS',
            'category' => 'hiking',
            'source' => 'nps',
            'hasImage' => !empty($img),
            'selftext' => substr($park['description'] ?? '', 0, 200),
        ];
    }
}
$hiking = array_merge($hiking, $npsPosts);

// Pick random Wu quote
$quote = $wuQuotes[array_rand($wuQuotes)];

$result = [
    'feeds' => [
        'hiking' => $hiking,
        'bikes' => $bikes,
        'trikes' => $trikes,
        'wutang' => $wutang,
    ],
    'wuQuote' => ['text' => $quote[0], 'author' => $quote[1]],
    'cached_at' => date('c'),
];

@file_put_contents($cacheFile, json_encode($result));
jsonResponse($result);
