<?php
require 'dbPDO.php';
require 'utiluser.php';
$title = "Book Search";
$nav = true;
$content = '';
if (isset($_GET['isbn'])) {
	$query = $db->prepare("SELECT d.ISBN, title, description, publisher, price, edition, pages, GROUP_CONCAT(DISTINCT concat('<a href=\"searchBrowse.php\?search=', namel, '\">', namef, ' ', namel, '</a>') ORDER BY namel SEPARATOR ', ') as authors FROM bookauthors a, bookauthorsbooks ba, bookdescriptions d, bookcategoriesbooks cb, bookcategories c WHERE a.AuthorID = ba.AuthorID AND ba.ISBN = d.ISBN AND d.ISBN = cb.ISBN AND c.CategoryID = cb.CategoryID AND d.isbn = ? GROUP BY d.ISBN ORDER BY title LIMIT 1;");
	$query->execute(array($_GET['isbn']));
	$number = $query->rowCount();
	if ($number > 0) {
		$result = $query->fetch();
		$title = "$result[title]";
		$content = "<article class=\"book\"><h1 class=\"center\">$result[title]</h1><div class=\"twoCols\"><div><a href=\"//yorktown.cbe.wwu.edu/sandvig/mis314/assignments/bookstore/bookimages/$result[ISBN].01.LZZZZZZZ.jpg\"><img src=\"//yorktown.cbe.wwu.edu/sandvig/mis314/assignments/bookstore/bookimages/$result[ISBN].01.MZZZZZZZ.jpg\" data-isbn=\"$result[ISBN]\"></a></div><div class=\"big\"><strong>By:</strong> $result[authors]<br><strong>Price:</strong> $$result[price]<br><br><strong>ISBN:</strong> $result[ISBN]<br><strong>Publisher:</strong> $result[publisher]<br><strong>Pages:</strong> $result[pages]<br><strong>Edition:</strong> $result[edition]<form action=\"shoppingCart.php\" method=\"post\"><input type=\"hidden\" name=\"addISBN\" value=\"$result[ISBN]\"><button><img src=\"cart.png\"> Add to cart</button></form></div></div><section class=\"description\">$result[description]</section></article>";
		if ($userUUID) {
			$db->beginTransaction();
			$isUpdate = $db->prepare("SELECT v.viewID FROM bookcustomerviews v WHERE v.ISBN = :isbn AND v.uuid = :uuid;");
			$isUpdate->execute(array(':uuid' => hex2bin($userUUID), ':isbn' => (string) $result['ISBN']));
			if ($isUpdate->rowCount()) {
				$pageView = $db->prepare('UPDATE bookcustomerviews SET time = :time WHERE ISBN = :isbn AND uuid = :uuid');
				$pageView->execute(array(':uuid' => hex2bin($userUUID), ':isbn' => (string) $result['ISBN'], ':time' => time()));
			} else {
				$pageView = $db->prepare('INSERT INTO bookcustomerviews (uuid, isbn, time) VALUES (:uuid, :isbn, :time);');
				$pageView->execute(array(':uuid' => hex2bin($userUUID), ':isbn' => (string) $result['ISBN'], ':time' => time()));
			}
			$db->commit();
		}
	} else {
		$title = 'No Results';
		$isbn = htmlspecialchars($_GET['isbn']);
		$content = "<div class=\"center\">ISBN <span class=\"red\">$isbn</span> is not in our database. Sorry!</div>";
	}
} else {
	header('location: index.php');
	exit();
}
require 'template.php';
?>
