<?php session_start(); ?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE" />
<meta http-equiv="PRAGMA" content="NO-CACHE" />
<link href="../style.css" rel="stylesheet" type="text/css" />
<title>
Sang Woo Jun
</title>
</head>
<?php
$feeds = json_decode( file_get_contents( 'data/feeds.json' ), true );
$addurl = $_POST["url"];
if ( $addurl != "" ) {
	$feeds[$addurl]["url"] = $addurl;
}

?>


<body>
<div id="container">
	<div id="top-bar">
	<h1>RSS Reader</h1>
	<i>(Since Google Reader is gone)</i>
	</div>

	<div id="top-menu">
	<a href=http://people.csail.mit.edu/wjun>Back to Home</a>
	</div>

	<ol>
	<?php
	$idx = 0;
	foreach($feeds as $feed) {
		$url = $feed["url"];
		$rss = simplexml_load_file($url);
		if ($rss) {
			echo "<li><a href=index.php?id=".$idx.">";
			echo "".$rss->channel->title."</a>";
	//		echo $feed["url"]."<br>";
			$items = $rss->channel->item;
			$lastrecent = $feed["latest"];
			$unreadcount = 0;
			foreach($items as $item) {
				$published_on = strtotime($item->pubDate);
				if ( $published_on > $lastrecent ) $unreadcount = $unreadcount + 1;
			}
			echo " <b>(".$unreadcount.")</b>";
		}
		$idx = $idx + 1;
	}
	?>
	</ol>
	<form id=addfeed action=index.php method=post>
	<input type=text name=url id=url size=30 />
	<input type=submit name=submit value="add feed" />
	</form>
	<hr>

<?php
$idx = 0;
foreach($feeds as $feed) {
	$url = $feed["url"];
	if ( $idx != $_GET["id"] || $_GET["id"] == "" ) {
		$idx = $idx + 1;
		continue;
	} else {
		$idx = $idx + 1;
	}

	$rss = simplexml_load_file($url);
	if($rss)
	{
		$mostrecent = 0;
		$lastrecent = $feed["latest"];
		echo '<h2>'.$rss->channel->title.'</h2>';
	//	echo '<li>'.$rss->channel->pubDate.'</li>';
		$pidx = 0;
		$items = $rss->channel->item;
		foreach($items as $item)
		{
			$title = $item->title;
			$link = $item->link;
			$published_on = strtotime($item->pubDate);
			$unread = true;
			if ( $lastrecent >= $published_on ) {
				$unread = false;
			}
			if ( $published_on > $mostrecent ) $mostrecent = $published_on;

			$description = $item->description;
//			echo "!!!".$item->guid;
			echo '<div id=post".$pidx." style="margin: 15px;">';
			echo '<h4>'.$pidx.'. <a href="'.$link.'">'.$title;
			if ( $unread == false ) echo ' *';
			echo ''.'</a></h4>';
			echo ''.$description.'</div>';
			$pidx = $pidx + 1;
		}
		$feeds[$url]["latest"] = $mostrecent;
	}
}
if ( $_SESSION["auth"] == "yes") {
	file_put_contents( 'data/feeds.json', json_encode($feeds));
}
?>
<br>
</div>
</body>
</html>
