<?php
	
	$body = '<p>Books in catalog';

	include('/var/www/html/sql.php');

	function conjuction($q) {
		$where = strrpos($q,'WHERE');
		$union = strrpos($q,'UNION');
		if ($where === FALSE) return "WHERE";
		if ($union !== FALSE && $union > $where) return "WHERE";
		return "AND";
	}
	function testValue($w) {
		if (strpos($w,'_') !== FALSE) {
			$varstr = explode('?',$_SERVER['REQUEST_URI']);
			$variables = explode('&',$varstr[1]);
			foreach ($variables as $var) {
				$testValue = urldecode($var);
				$pattern = '#[^a-zA-Z0-9\x7f-\xff]#';
				if (preg_replace($pattern,'_',$testValue) == str_replace('@','_',$w)) return $testValue;
			}
		}
		return $w;
	}
	
	$query = "SELECT Book FROM books ";
	$author = mysql_real_escape_string($_GET['author']);
	$subject = mysql_real_escape_string($_GET['subject']);
	if (!empty($author)) {
		$query .= conjuction($query);
		$query .= " Author='" . $author . "' ";
		$body .= ' by ' . $author;
	}
	if (!empty($subject)) {
		$query .= conjuction($query);
		$query .= " Subject='" . $subject . "' ";
		$preQuery = "SELECT Display FROM subjects WHERE Code='" . $subject . "';";
		$display = mysql_fetch_array(mysql_query($preQuery));
		$body .= ' about ' . $display[0];
	}

	// Test Zone
	foreach ($_GET as $key => $val) {
		if ($key == 'author' || $key == 'subject') break;
		if (strpos($key,'@') === FALSE) {
			if (!empty($subject)) $empty = TRUE; 
			$subject = mysql_real_escape_string($key);
			$preQuery = "SELECT Display FROM subjects WHERE Code='" . $subject . "';";
			$display = mysql_fetch_array(mysql_query($preQuery));
			if (count($display) > 1) {
				if ($empty) {
					$body .= ' or' ;
        	                        $query .= ' UNION SELECT Book from books ';
	                                unset($author);
				}
				$body .= ' about ' . $display[0];
				$query .= conjuction($query);
				$query .= " Subject='" . $subject . "' ";
			}
			else {
				$empty = FALSE;
				if ($key == 'title') $key = $val;
				$title = testValue($key);
				$body .= ' with titles similar to "' . $title . '"';
				unset($subject);
			}
		}
		else {
			if (!empty($author)) $empty = TRUE; 
			$author = testValue($key);
			if (strpos($author,' ') === FALSE) {
				if ($empty) {
					$body .= ' or';
        	                        $query .= ' UNION SELECT Book from books ';
	                                unset($subject);
				}
				$author = mysql_real_escape_string($author);
				$query .= conjuction($query);
				$query .= " Author='" . $author . "' ";
				$body .= ' by ' . $author;
			}
			else {
				$empty = FALSE;
				$title = testValue($author);
				$body .= ' with titles similar to "' . $author . '"';
				unset($author);
			}
		}	
	}
	// End of Test Zone

	$query .= "ORDER BY Book;";
	$result = mysql_query($query);
	
	if (mysql_num_rows($result) != 0) {
		$body .= ':</p>';
		$body .= '<ul style="margin-top: 0;">';
		while ($data = mysql_fetch_array($result)) {
			if (!empty($data['Book']) && is_dir('/var/www/html/beta/read/' . $data['Book'])) {
				$data_compare = strtolower($data['Book']);
				$title_compare = strtolower($title);
				similar_text($data_compare,$title_compare,$percent);

				// Substring Test
				$substr_test = (strpos($data_compare,$title_compare) !== FALSE) || (strpos($title_compare,$data_compare) !== FALSE);
				$title_array = explode(' ',$title_compare);
				$data_array = explode(' ',$data_compare);
				foreach (explode(' ',$title_compare) as $word)
					if (!in_array($word,explode(' ',$data_compare))) $substr_test = FALSE;
				if (empty($title)) $substr_test = TRUE;
				// End of Test

				if (!empty($title) && $percent < 50 && !$substr_test) continue;
				$body .= '<li><a href="https://www.okeebo.com/beta/read/' . $data['Book'] . '">' . $data['Book'] . '</a></li>';
			}
		}
		$body .= '</ul>';
		if (strpos($body,'<li>') === FALSE) {
			$body = str_replace('>Books','>No books',$body);
			$body = str_replace(':</p>','.</p>',$body);
		}
	}
	else $body = str_replace('>Books','>No books',$body) . '.</p>';

	mysql_close();
	
?><!DOCTYPE html>
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
	<meta name="viewport" content="initial-scale=1, minimum-scale=1" />
	<title>Okeebo</title>
	<link rel="stylesheet" href="../okeebo.css" />
	<link rel="stylesheet" media="print" href="../print.css" />
	<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
	<script type="text/javascript" src="../index.js"></script>
</head>

<body>

	<form id="login-form" method="POST">
		<input id="assertion-field" type="hidden" name="assertion" value="">
	</form>
    
    <a id="home" href="https://www.okeebo.com/beta/">Home</a>
    <a id="function" href="https://www.okeebo.com/beta/read/">Catalog</a>
    
    <div class="outer">
    	<?= $body ?>       
    </div>

	<input id="filter" style="display:none;" />

	<script type="text/javascript">
		<?php include('catalog.js'); ?>
	</script>
	<style>
                <?php include('catalog.css'); ?>
        </style>

    
</body>

</html>
