<?php
require 'dbPDO.php';
require 'utilcart.php';
$title = 'Shopping Cart';
$nav = true;
$content = '<div class="cartitems">';
$updateCart = $db->prepare('UPDATE bookuuidcart SET quantity = :qty WHERE ISBN = :isbn AND uuid = :uuid;');
$insertCart = $db->prepare('INSERT INTO bookuuidcart (uuid, ISBN, quantity) VALUES (:uuid, :isbn, :qty);');
$deleteCart = $db->prepare('DELETE FROM bookuuidcart WHERE uuid = :uuid AND ISBN = :isbn;');
$addISBN = (isset($_POST['addISBN'])) ? preg_replace("/[^0-9.X]+/i", "", $_POST['addISBN']) : false;
if ($addISBN && strlen($addISBN) > 0) {
    if (array_key_exists($addISBN, $bookArray)) {
        $bookArray[$addISBN] += 1;
        $updateCart->execute(array(':uuid' => hex2bin($userUUID), ':isbn' => $addISBN, ':qty' => $bookArray[$addISBN]));
    } else {
        $bookArray[$addISBN] = 1;
        $insertCart->execute(array(':uuid' => hex2bin($userUUID), ':isbn' => $addISBN, ':qty' => $bookArray[$addISBN]));
    }
    header('location: shoppingCart.php');
    exit();
}
$deleteISBN = (isset($_POST['deleteISBN'])) ? preg_replace("/[^0-9.X]+/i", "", $_POST['deleteISBN']) : false;
if ($deleteISBN && strlen($deleteISBN) > 0) {
    if (array_key_exists($deleteISBN, $bookArray)) {
        $bookArray[$deleteISBN] -= 1;
        if ($bookArray[$deleteISBN] <= 0) {
            $deleteCart->execute(array(':uuid' => hex2bin($userUUID), ':isbn' => $deleteISBN));
            unset($bookArray[$deleteISBN]);
        } else {
            $updateCart->execute(array(':uuid' => hex2bin($userUUID), ':isbn' => $deleteISBN, ':qty' => $bookArray[$deleteISBN]));
        }
    }
    header('location: shoppingCart.php');
    exit();
}
if (count($bookArray) > 0) {
    $sql = "SELECT ISBN, title, price, pages from bookdescriptions WHERE ISBN = ?";
    for ($i = 1; $i < count($bookArray); $i++) {
        $sql .= " OR ISBN = ?";
    }
    $isbnArray = array_map('strval', array_keys($bookArray)); // PHP please stop casting things that look like integers to integers
    $sql .= " ORDER BY title;";
    $query = $db->prepare($sql);
    $query->execute($isbnArray);
    $total = 0;
    $shipping = 0;
    foreach ($query->fetchAll() as $row) {
        $isbn = $row['ISBN'];
        $qty = $bookArray[$isbn];
        $itemTotal = $qty * $row['price'];
        $pricef = sprintf("$%.2f", $row['price']);
        $totalf = sprintf("$%.2f", $itemTotal);
        $total += $itemTotal;
        $shipping += $row['pages'] * $qty;
        $content .= "<article class=\"bookteaser\"><a href=\"productPage.php?isbn=$row[ISBN]\"><h1>$row[title]</h1></a><div class=\"clearfix\"><a href=\"productPage.php?isbn=$row[ISBN]\"><img src=\"//yorktown.cbe.wwu.edu/sandvig/mis314/assignments/bookstore/bookimages/$row[ISBN].01.THUMBZZZ.jpg\"></a>Price: <span class=\"red\">$pricef</span><br>Quantity: $qty<br>Total: <span class=\"red\">$totalf</span></div><form method=\"post\" class=\"center\"><button type=\"submit\" value=\"$isbn\" name=\"addISBN\"><img src=\"cart.png\">Add</button><button type=\"submit\" value=\"$isbn\" name=\"deleteISBN\"><img src=\"rmcart.png\">Delete</button></form></article>";
    }
    $content .= '</div>';
    $totalf = sprintf("$%.2f", $total);
    $grandTotal = sprintf("$%.2f", $total + pow($shipping, .25));
    $shippingf = sprintf("$%.2f", pow($shipping, .25));
    $content .= "<div>Sub total: <span class=\"red\">$totalf</span></div>";
    $content .= "<div>Shipping: <span class=\"red\">$shippingf</span></div>";
    $content .= "<div>Total: <strong class=\"red\">$grandTotal</strong></div>";
    $content .= "<small>Shipping is the 4th root of the number of pages in your order.</small>";
    $content .= "<div><a href=\"checkout01.php\">Checkout</a></div>";
} else {
    $content = "<h1>No items in cart.</h1>";
}
require 'template.php';
?>
