<?php
require '../utils/dbPDO.php';
require '../utils/validate.php';
$dalingk = new dalingkDB();
$db = $dalingk->connect();
if (isset($_POST['asin']) && isset($_POST['title']) && isset($_POST['price'])) {
	$price = validFloat($_POST['price']);
	$title = validString($_POST['title'], 100);
	$asin = validString($_POST['asin'], 15);
	if ($asin && $title && $price) {
		$db->beginTransaction();
		$query = $db->prepare("INSERT INTO `MIS314`.`dvdtitles` (asin, title, price) VALUES (?,?,?)");
		$query->execute(array($asin, $title, $price));
		$db->commit();
		header('location: dvdTitles.php');
		exit();
	}
}
if (isset($_POST['deleteASIN'])) {
	$db->beginTransaction();
	$query = $db->prepare("DELETE FROM `MIS314`.`dvdtitles` WHERE `asin` = ?");
	$query->execute(array($_POST['deleteASIN']));
	$db->commit();
	header('location: dvdTitles.php');
	exit();
}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Movie Titles - Add, Delete</title>
	<link href="//yorktown.cbe.wwu.edu/sandvig/mis314/assignments/style.css" rel="stylesheet" type="text/css">
</head>
<body>
	<div class="pageContainer centerText">
		<h3>Movie Titles</h3><hr>
		<form class="formLayout" method="post">
			<div class="formGroup">
				<label>ASIN:</label>
				<input type="text" name="asin" required placeholder="ASIN" pattern=".{10,}" title="10 or more numbers & characters" selected/>
			</div>
			<div class="formGroup">
				<label>Title:</label>
				<input type="text" name="title" required placeholder="title" />
			</div>
			<div class="formGroup">
				<label>Price:</label>
				<input type="text" name="price" required placeholder="price" pattern="[0-9\.]{1,7}" title="Must be numeric" />
			</div>
			<div class="formGroup">
				<label></label>
				<button type="submit">Add to database</button>
			</div>
		</form>
		<p><?php echo $db->query("SELECT * FROM dvdtitles")->rowCount() . ' records in the database.'; ?></p>
		<table class="simpleTable shadow">
			<tr><th>ASIN</th><th>Title</th><th>Price</th><th>Image</th><th>Delete</th></tr>
			<?php
			foreach ($db->query("SELECT * FROM dvdtitles ORDER BY price;") as $row) {
				echo "<tr>";
				echo "<td>$row[asin]</td><td>$row[title]</td><td>$$row[price]</td><td><img src=\"http://images.amazon.com/images/P/$row[asin].01.MZZZZZZZ.jpg\"></td>";
				echo "<td><form method=\"post\"><input type=\"hidden\" value=\"$row[asin]\" name=\"deleteASIN\"><input type=\"submit\" value=\"Delete\"></form></td>";
				echo '</tr>';
			}
			?>
		</table>
	</div>
</body>
</html>
