<?php
require 'dbPDO.php';
require 'utilcart.php';
require 'encryption.php';
require 'utilsvalidate.php';
require 'utiluser.php';
$title = 'Checkout confirmation';
$nav = false;
$content = "<h1 class=\"subheading red\">You Purchased</h1><div class=\"cartitems\">";
$fieldsSet = (isset($_POST['email'])
    && isset($_POST['fname'])
    && isset($_POST['lname'])
    && isset($_POST['street'])
    && isset($_POST['city'])
    && isset($_POST['state'])
    && isset($_POST['zip']));
if (!$fieldsSet) {
    header('location: checkout01.php');
    exit();
}
if ($userCustID == 0) {
    header('location: account.php?checkout=true');
    exit();
}
$email = validString(filter_var($_POST['email'], FILTER_SANITIZE_EMAIL), 50);
$fname = validString($_POST['fname'], 20);
$lname = validString($_POST['lname'], 20);
$street = validString($_POST['street'], 25);
$city = validString($_POST['city'], 30);
$state = validString($_POST['state'], 2, 1);
preg_match("/^([0-9]{5})$/", $_POST['zip'], $zip);
$zip = validString($zip[0], 5, 4);
$validFields = $email && $fname && $lname && $street && $city && $state && $zip;
if (!$validFields) {
    header('location: checkout01.php');
    exit();
}
$db->beginTransaction();
// Customer has a previous order with us
$custID = $userCustID;
$user = $db->prepare("SELECT fname, lname, email, street, city, state, zip FROM bookCustomers WHERE custID = ?;");
$user->execute(array($custID));
$userCount = $user->rowCount();
if ($userCount == 1) {
    $fields = array(':fname' => $fname, ':lname' => $lname, ':street' => $street, 'city' => $city, 'state' => $state, ':zip' => $zip, ':custID' => $custID);
    $update = $db->prepare('UPDATE bookCustomers SET fname = :fname, lname = :lname, street = :street, city = :city, state = :state, zip = :zip WHERE custID = :custID;');
    $update->execute($fields);
} else {
    error_log("There is not one user with custID ($custID)...");
}
$db->commit();
$fields = array(':custID' => $custID, ':orderdate' => time());
$db->beginTransaction();
$clearCart = $db->prepare('DELETE FROM bookuuidcart WHERE uuid = ?');
$clearCart->execute(array(hex2bin($userUUID)));
$order = $db->prepare("INSERT INTO bookorders (custID, orderdate) VALUES (:custID, :orderdate);");
$order->execute($fields);
$orderID = $db->lastInsertId();
foreach($bookArray as $isbn => $qty) {
    $fields = array(':orderID' => $orderID, ':isbn' => $isbn, ':qty' => $qty);
    $item = $db->prepare('INSERT INTO bookorderitems (orderID, isbn, qty, price) VALUES (:orderID, :isbn, :qty, (SELECT price from bookdescriptions WHERE isbn = :isbn));');
    $item->execute($fields);
}
$db->commit();
$emailContent = "Order Confirmation from Better Books.\n\nOrder number: $orderID\n\nItems shipped:\n\n";
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;
    $itemNum = 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></article>";
        $emailContent .= ++$itemNum . ". $row[title]   Quantity: $qty\n";
    }
    $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=\"orderHistory.php\">Order History</a></div>";
    $emailContent .= "\nShipped to:\n$fname $lname\n$street\n$city $state, $zip\n\nTotal Cost: $grandTotal\n\nYour order will probably never arrive because this is not a real bookstore.\nHowever, if we were a real bookstore, your order would arrive 2 days behind schedule.\nThank you for shopping with Better Books.";
    mail($email, "Order Confirmation for order $orderID", $emailContent, 'From: dalingk@students.wwu.edu');
}
$bookArray = array();
require 'template.php';
?>
