<?php
/**
* cart.php
* Artzy page to show shopping cart
*
* @author Ed Parrish
* @version 1.2 05/09/08
*/
ob_start();
session_start();
define('CART_TIME', 2592000); // 30 days
define('MAX_QTY', 10);

include("includes/formlib.php");
require("includes/db.php");

main("Shopping Cart");

// Control the operation of the page
function main($title = "") {
    $db = new DB();
    if (isset($_REQUEST['add'])) {
        $pid = $_REQUEST['add'];
        addItem($db, $pid);
    } else if (isset($_REQUEST['del'])) {
        $pid = $_REQUEST['del'];
        deleteItem($db, $pid);
    } else if (isset($_REQUEST['update'])) {
        $pid = $_REQUEST['update'];
        updateItem($db, $pid);
    }
    $other = getJavaScript();
    include("includes/header.php");
    showContent($title, $db);
    include("includes/footer.php");
}

function getJavaScript() {
    return<<<SCRIPT
<script type="text/javascript">
  function updateQty(item) {
    itemId = item.name;
    newQty = item.options[item.selectedIndex].text;
    location.href = 'cart.php?update='+itemId+'&qty='+newQty;
  }
</script>

SCRIPT;
}

/**
 * Generates an encrypted session variable and sets a cookie that
 * persists beyond the session.
 *
 * @return The users cart id.
 */
function getCartId() {
    if (isset($_COOKIE["cartId"])) {
        return $_COOKIE["cartId"];
    } else { // no cookie is set
        if (!session_id()) {
            session_start();
        }
        setcookie("cartId", session_id(), time() + CART_TIME);
        return session_id();
    }
}

// Get and sanitize the quantity
function getQuantity() {
    $qty = 1;
    if (isset($_REQUEST['qty'])) $qty = $_REQUEST['qty'];
    $qty = intval($qty);
    if ($qty < 0) $qty = 0;
    if ($qty > MAX_QTY) $qty = MAX_QTY;
    return $qty;
}

// Add items
function addItem($db, $pid) {
    $cartID = getCartId();
    $qty = getQuantity();

    // Check if item already exists in the users cart
    $sql = "
        SELECT *
        FROM shoppingcarts
        WHERE CartID='$cartID'
        AND ProductID=$pid
        ";
    $result = $db->query($sql);
    $numRows = mysql_num_rows($result);

    if($numRows != 0) { // Item already exists
        $qty = mysql_result($result, 0, 'Quantity');
        $_REQUEST['qty'] = $qty + 1; // increment qty
        updateItem($db, $pid);
    } else { // Item does not exist

        // Get the current price
        $sql = "
            SELECT Price
            FROM products
            WHERE ID=$pid
             ";
        $result = $db->query($sql);
        if (mysql_num_rows($result) == 0) return;
        $price = mysql_result($result, 0, 0);

        // Insert the item
        $sql = "
            INSERT INTO shoppingcarts
            VALUES('$cartID', $pid, NOW(), $price, $qty)
             ";
        $db->query($sql);
    }
}

// Delete items
function deleteItem($db, $pid) {
    $cartID = getCartId();
    $sql = "
        DELETE FROM shoppingcarts
        WHERE CartID='$cartID'
        AND ProductID=$pid
         ";
    $db->query($sql);
}

// Update item quantities
function updateItem($db, $pid) {
    $cartID = getCartId();
    $qty = getQuantity();
    if ($qty <= 0) {
        deleteItem($db, $pid);
    } else {
        $sql = "UPDATE shoppingcarts
                SET Quantity=$qty
                WHERE CartID='$cartID'
                AND ProductID=$pid
                ";
        $db->query($sql);
    }
}

// Display the content of a page
function showContent($title, $db) {
    $cartID = getCartId();
    $sql = "
        SELECT ID, ProductName, PriceEach, Quantity
        FROM shoppingcarts, products
        WHERE ID=ProductID
        AND CartID='$cartID'
        ";
    $result = $db->query($sql);
    echo "<h1>$title</h1>\n";
    echo "<table>\n";
    showHeading();
    $total = 0;
    while ($row = mysql_fetch_row($result)) {
        list($id, $prodName, $price, $qty) = $row;
        $total += $price * $qty;
        $price = "$".number_format($price, 2);
        showItem($id, $prodName, $price, $qty);
    }
    $total = "$".number_format($total, 2);
    showFooter($total);
    echo "</table>\n";
}

// Display the table heading
function showHeading() {
    echo <<<HTML
<tr>
  <td bgcolor="blue">
    <font face="verdana" size="2" color="white">
      &nbsp;<b>Product</b>
    </font>
  </td>
  <td bgcolor="blue">
    <font face="verdana" size="2" color="white">&nbsp;<b>Quantity</b>&nbsp;</font>
  </td>
  <td bgcolor="blue">
    <font face="verdana" size="2" color="white">&nbsp;<b>Price</b>&nbsp;</font>
  </td>
  <td bgcolor="blue">
    <font face="verdana" size="2" color="white">&nbsp;<b>Action</b>&nbsp;</font>
  </td>
</tr>

HTML;
}

// Display each table item
function showItem($id, $prodName, $price, $qty) {
    $f = new FormLib();
    $data = array();
    for ($i = 1; $i <= MAX_QTY; $i++) {
        $data[$i] = $i;
    }
    $other = 'onChange="updateQty(this)"';
    $opt = $f->makeSelect($id, $data, $qty, $other);
    echo <<<HTML
<tr>
  <td>
    <font face="verdana" size="2" color="black">$prodName</font>
  </td>
  <td>
      <font face="verdana" size="2" color="black">
        $opt
      </font>
  </td>
  <td>
      <font face="verdana" size="2" color="black">$price</font>
  </td>
  <td>
      <font face="verdana" size="2" color="black">
          <a href="cart.php?del=$id">Remove?</a>
      </font>
  </td>
</tr>
<tr>
  <td width="100%" colspan="5">
    <hr size="1" color="red" noshade>
  </td>
</tr>

HTML;
}

// Display the table ending
function showFooter($total) {
    echo <<<HTML
<tr>
  <td colspan="2">
    <font face="verdana" size="2" color="black">
      <a href="products.php">&lt;&lt; Keep Shopping</a>
    </font>
  </td>
  <td colspan="2" >
    <font face="verdana" size="3" color="black">
      <p><strong>&nbsp;Total: $total</strong></p>
    </font>
  </td>
</tr>

HTML;
}
?>