<?php

// Controller

$body = '';
if (isset($_GET['p'])) {
	switch($_GET['p']) {
	
		case 'h': { // Homepage
			$body = html_home();
		} break;
		
		case 'a': { // Anime a=id
			if (! isset($_GET['a'])) redirect('?p=e&e=0');
			$anime = db_getanime($_GET['a']);
			if ($anime === false) redirect('?p=e&e=1');
			$body = html_anime($anime);
		} break;

		case 's': { // Search q=str
			if (! isset($_GET['q'])) redirect('?p=e&e=0');
			$body = html_search( db_search($_GET['q']) );
		} break;
		
		case 'e': { // Error e=id
			$body = html_err( isset($_GET['e']) ? intval($_GET['e']) : -1 );
		} break;
		
		case 'x': { // Advanced search
			$body = html_advsearch();
		} break;
		
		case 'r': { // Advanced search results
			$body = print_r($_GET, true);
		} break;
		
		case 'p': { // Producer c=id
		} break;
		
		case 'g': { // Genre c=id
		} break;
		
		default: { // No page set
			redirect('?p=e&e=0');
		} break;
	}
} else {
	redirect('?p=h');
}

function redirect($u='?'){header('Location: '.$u);die();}
function h($s){return htmlentities($s,ENT_QUOTES);}

// DB

function dbh() {
	static $d = null;
	if (is_null($d)) $d = new \PDO('sqlite:malscrape.db');
	return $d;
}

function db_do($sql, $p=array()) {
	$stmt = dbh()->prepare($sql);
	$stmt->execute($p);
	return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}

function db_map($table, $from, $to) {
	$rows = db_do('SELECT * FROM '.$table.';');
	$ret = array();
	foreach($rows as $r) $ret[$r[$from]] = $r[$to];
	return $ret;
}

function db_search($q) {
	$q = trim($q); if (! strlen($q)) return array();
	return db_do('SELECT * FROM names WHERE name LIKE ? ORDER BY name ASC;', array("%{$q}%"));
}

function db_getanime($id) {
	$ainf = db_do('SELECT * FROM anime WHERE id=?;', array($id));
	if (! count($ainf)) return false;
	
	$names = db_do('SELECT * FROM names WHERE anime_id=?;', array($id));
	$gen_l = db_do('SELECT genre_id FROM genre_links WHERE anime_id=?;', array($id));
	$prd_l = db_do('SELECT producer_id FROM producer_links WHERE anime_id=?;', array($id));
	$rel = db_do('SELECT anime_id,name FROM related JOIN names ON related.to_id=names.anime_id WHERE related.from_id=? GROUP BY related.to_id;', array($id));
	
	return array(
		'anime' => $ainf[0],
		'names' => $names,
		'genres' => $gen_l,
		'producers' => $prd_l,
		'related' => $rel
	);
}

// Formatting

function get_genre($genre_id) {
	static $genres = null;
	if (is_null($genres)) $genres = db_map('genres', 'name', 'id');
		
	return isset($genres[$genre_id]) ? $genres[$genre_id] : '...';
}

function get_producer($p_id) {
	static $producers = null;
	if (is_null($producers)) $producers = db_map('producers', 'name', 'id');
	
	return isset($producers[$p_id]) ? $producers[$p_id] : '...';
}

// HTML views

function html_err($e_id) {
	static $errors = array(
		0 => 'Invalid request',
		1 => 'No such anime ID',
	);
	$msg = array_key_exists($e_id, $errors) ? $errors[$e_id] : 'Unknown error';
	return '<div class="pad"><strong>Error:</strong> '.h($msg).'</div>';
}

function html_home() {
	return '
	<div class="pad">
		Search Anime:<br>
		<form method="get" action="?">
			<input type="hidden" name="p" value="s">
			<input type="text" name="q" autofocus>
			<input type="submit" value="&gt;">
		</form>
		<br>
		<a href="?p=x">Advanced Search...</a>
	</div>
	';
}

function html_advsearch() {
	$props = array(
		'Score' => array(
			'name' => 'sc',
			'opts' => array(
				'gte' => 'at least',
				'lte' => 'under',
			),
			'prefix' => '',
		),
		'Duration' => array(
			'name' => 'sc',
			'opts' => array(
				'gte' => 'at least',
				'lte' => 'under',
			),
			'prefix' => 'mins',
		),
		'Rating' => array(
			'name' => 'sc',
			'opts' => array(
				'gte' => 'at least',
				'lte' => 'under',
			),
			'prefix' => '',
		),
	);
	
	$ret = '
		<div class="pad">
			<b>Advanced Search</b>
		</div>
		<div class="sec">Options</div>
		<div class="pad">
			<form method="get">
				<input type="hidden" name="p" value="r">
	';
	foreach($props as $title=>$pinf) {
		$opt_list = array();
		foreach($pinf['opts'] as $opt_id=>$opt_text) {
			$opt_list[] = '<option value="'.$opt_id.'">'.$opt_text.'</option>';
		}
		$ret .= '
				<span>
					<label>
						<input type="hidden" name="x['.$pinf['name'].'][on]" value="0">
						<input type="checkbox" name="x['.$pinf['name'].'][on]" value="1">
						'.$title.' is
					</label>
					<select name="x['.$pinf['name'].'][cmp]">
						'.implode($opt_list).'
					</select>
					<input type="text" name="x['.$pinf['name'].'][val]" class="short">
					'.$pinf['prefix'].'
				</span>
				<br>
		';
	}
	
	$ret .= '
				<span>
					<label>
						<input type="hidden" name="x[g][on]" value="0">
						<input type="checkbox" name="x[g][on]" value="1">
						Genre is
					</label>
					<input type="hidden" name="x[g][cmp]" val="eq">
					<select name="x[g][val]">
						
					</select>
				</span>
				<br>
				<input type="submit" value="Search">
			</form>
		</div>
	';
	
	return $ret;
}

function html_search($results) {
	$ret = array();
	foreach($results as $r) $ret[] = 
		'<a href="?p=a&a='.$r['anime_id'].'">'.($r['name']).'</a>'
	;
	return '<div class="pad">'.(count($ret) ? implode('<br>', $ret) : 'No results.').'</div>';
}

function html_anime($anime) {

	$names = array();
	foreach($anime['names'] as $name) $names[] = $name['name'];
	
	$producers = array();
	foreach($anime['producers'] as $p_id) $producers[] =
		'<a href="?p=p&c='.$p_id['producer_id'].'">'.(get_producer($p_id['producer_id'])).'</a>'
	;

	$genres = array();
	foreach($anime['genres'] as $g_id) $genres[] =
		'<a href="?p=g&c='.$g_id['genre_id'].'">'.(get_genre($g_id['genre_id'])).'</a>'
	;
	
	$related = array();
	foreach($anime['related'] as $rel) $related[] = 
		'<a href="?p=a&a='.$rel['anime_id'].'">'.($rel['name']).'</a>'
	;
	
	return '
	<div class="pad">
		<b>'.h($anime['names'][0]['name']).'</b>
	</div>
	<div class="sec">Information</div>
	<div class="pad">
		<b>Type:</b> '.$anime['anime']['type'].'<br>
		<b>Airing:</b> '.$anime['anime']['air_status'].'<br>
		<b>Air date:</b> '.$anime['anime']['air_date'].'<br>
		<b>Episodes:</b> '.$anime['anime']['episodes'].'<br>
		<b>Episode length:</b> '.$anime['anime']['duration'].' min<br>
		<b><a href="http://myanimelist.net/anime/'.$anime['anime']['id'].'">MAL</a> Rating:</b> '.$anime['anime']['score'].'
		('.$anime['anime']['vote_count'].' votes)
	</div>
	<div class="sec">Description</div>
	<div class="pad">
		'.nl2br($anime['anime']['description']).'
	</div>
	<div class="sec">Genres</div>
	<div class="pad">
		'.implode(', ', $genres).'
	</div>
	<div class="sec">Alternate names</div>
	<div class="pad">
		'.implode('<br>', $names).'
	</div>
	<div class="sec">Producers</div>
	<div class="pad">
		'.implode('<br>', $producers).'
	</div>
	<div class="sec">Related anime</div>
	<div class="pad">
		'.implode('<br>', $related).'
	</div>	
	';
}

// Template

?>
<!DOCTYPE html>
<html>
	<head>
		<title>MiniAnimeList</title>
		<meta charset="UTF-8">
		<link rel="stylesheet" type="text/css" href="mal.css">
	</head>
	<body>
		<div class="sec"><a class="hdrimg" href="?p=h"></a></div>
		<?=$body?> 
		<div class="ftr">-- MiniAnimeList --</div>
	</body>
</html>