<?php
require_once 'utiluser.php';
require_once 'dbPDO.php';
require_once 'utilcart.php';
require_once 'utilsvalidate.php';
header('Content-Type: application/json');
$fields = array('search' => array('query'), 'book' => array('isbn'), 'cart' => array(), 'history' => array(), 'user' => array(), 'login' => array(), 'logout' => array(), 'recent' => array(), 'addBook' => array());
$output = array();
if (isset($_GET['type'])) {
    if (array_key_exists($_GET['type'], $fields)) {
        $valid = true;
        foreach ($fields[$_GET['type']] as $field) {
            $valid = $valid && array_key_exists($field, $_GET) && !empty($_GET[$field]);
        }
        if ($valid) {
            switch ($_GET['type']) {
            case 'search':
                $output = search($_GET['query']);
                break;
            case 'book':
                $output = book($_GET['isbn']);
                break;
            case 'cart':
                $output = cart();
                break;
            case 'history':
                $output = history();
                break;
            case 'user':
                $output = user();
                break;
            case 'login':
                $output = (isset($_POST['email'], $_POST['password'])) ? login($_POST['email'], $_POST['password']) : array('error' => 'Missing options');
                break;
            case 'logout':
                $output = logout();
                break;
            case 'checkout':
                $output = checkout();
                break;
            case 'recent':
                $output = recent();
                break;
            case 'addBook':
                $output = newBook();
                break;
            default:
                $outout = array('error' => 'Invalid request type');
                break;
            }
        } else {
            $output = array('error' => 'Invalid options');
        }
    } else {
        $output = array('error' => 'Invalid request type');
    }
} else {
    $output = array('error' => 'Missing request type');
}
echo json_encode(array('success' => !isset($output['error']), 'data' => $output, 'error' => (isset($output['error']) ? $output['error']: false)));
function search($q) {
    global $db;
    $out = array();
    str_replace('+', ' ', $q);
    $results = $db->prepare("SELECT d.ISBN, d.title 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 (CategoryName = :search OR title LIKE :search OR description LIKE :search OR publisher LIKE :search OR concat_ws(' ', nameF, nameL) LIKE :search) GROUP BY d.ISBN ORDER BY title;");
    $results->execute(array(':search' => "%$q%"));
    $number = $results->rowCount();
    foreach ($results->fetchAll() as $result) {
        $out[] = array('isbn' => $result['ISBN'], 'title' => $result['title']);
    }
    return $out;
}
function book($isbn) {
    global $db;
    $book = $db->prepare("SELECT d.ISBN, d.title, d.description, d.price, d.publisher, d.pubdate, d.edition, d.pages FROM bookdescriptions d WHERE d.ISBN LIKE ? GROUP BY d.ISBN;");
    $book->execute(array("$_GET[isbn]"));
    $number = $book->rowCount();
    if ($number == 1) {
        //output
        $authors = array();
        $q = $db->prepare("SELECT DISTINCT a.namef, a.namel FROM bookauthors a, bookauthorsbooks ab WHERE a.AuthorID = ab.AuthorID AND ab.ISBN LIKE ?;");
        $q->execute(array($_GET['isbn']));
        foreach ($q->fetchAll() as $author) {
            $authors[] = "$author[namel], $author[namef]";
        }
        $result = $book->fetch();
        $data = array('isbn' => $result['ISBN'], 'title' => $result['title'], 'description' => $result['description'], 'price' => $result['price'], 'publisher' => $result['pubdate'], '' => $result['edition'], 'pages' => $result['pages'], 'authors' => $authors);
        return $data;
    } else {
        $safeISBN = htmlspecialchars($_GET['isbn']);
        return array('error' => (($number == 0) ? 'No' : $number). " books with ISBN $safeISBN");
    }
}
function cart() {
    global $bookArray;
    return $bookArray;
}
function history() {
    global $userCustID, $db;
    $out = array();
    if ($userCustID > 0) {
        $orders = $db->prepare('SELECT o.orderID, o.orderdate FROM bookorders o WHERE o.custID = ? GROUP BY o.orderID ORDER BY o.orderdate DESC;');
        $orders->execute(array($userCustID));
        $number = $orders->rowCount();
        if ($number == 0) {
            return array('error' => 'No orders found');
        } else {
            $jsonOrder = array();
            $books = $db->prepare('SELECT i.qty, i.price, d.ISBN, d.title, d.pages FROM bookorderitems i, bookdescriptions d WHERE i.orderID = ? AND i.ISBN = d.ISBN ORDER BY d.ISBN;');
            foreach ($orders->fetchAll() as $order) {
                $items = array();
                $books->execute(array($order['orderID']));
                $orderTotal = 0;
                $pages = 0;
                foreach ($books->fetchAll() as $book) {
                    $items[] = array('isbn' => $book['ISBN'], 'title' => $book['title'], 'quantity' => $book['qty'], 'price' => $book['price'], 'itemTotal' => $book['qty'] * $book['price']);
                    $orderTotal += $book['price'] * $book['qty'];
                    $pages += $book['pages'] * $book['qty'];
                }
                $jsonOrder['items'] = $items;
                $orderDate = date(DATE_ATOM, $order['orderdate']);
                $jsonOrder['orderID'] = $order['orderID'];
                $jsonOrder['orderdate'] = $orderDate;
                $jsonOrder['subtotal'] = $orderTotal;
                $jsonOrder['shipping'] = sprintf("%.2f", pow($pages, .25));
                $jsonOrder['total'] = sprintf("%.2f", $orderTotal + pow($pages, .25));
                $out[] = $jsonOrder;
            }
        }
        return $out;
    } else {
        return array('error' => 'User not logged in');
    }
}
function user() {
    global $db, $userCustID;
    if ($userCustID > 0) {
        $user = $db->prepare('SELECT fname, lname, email, street, city, state, zip FROM bookCustomers WHERE custID = ?;');
        $user->execute(array($userCustID));
        $number = $user->rowCount();
        if ($number == 1) {
            $result = $user->fetch();
            $out = array('fname' => $result['fname'], 'lname' => $result['lname'], 'email' => $result['email'], 'street' => $result['street'], 'city' => $result['city'], 'state' => $result['state'], 'zip' => $result['zip']);
            return $out;
        } else {
            return array('error' => 'User not found');
        }
    } else {
        return array('error' => 'User not logged in');
    }
}
function login($e, $p) {
    global $db, $userUUID, $userCustID, $hmacPasswordSecret;
    $out = array();
    if ($userCustID == 0) {
        $email = filter_var($e, FILTER_SANITIZE_EMAIL);
        $password = validString($p, strlen($p), 5);
        if (strlen($email) > 0 && $password) {
            $findSalt = $db->prepare('SELECT hex(salt) AS salt, custID FROM bookCustomers WHERE email LIKE ?;');
            $findSalt->execute(array("$email"));
            $saltArray = $findSalt->fetch();
            $salt = hex2bin($saltArray['salt']);
            $custID = $saltArray['custID'];
            $pwHash = hex2bin(hash_hmac('sha512', $email . $password . $salt, $hmacPasswordSecret));
            $userpwd = $db->prepare('SELECT hex(password) FROM bookpwhash WHERE password = ?;');
            $userpwd->execute(array($pwHash));
            if ($userpwd->rowCount() == 1) {
                $db->beginTransaction();
                $update = $db->prepare('UPDATE bookuuidcustomers SET custID = :custID WHERE uuid = :uuid;');
                $update->execute(array(':custID' => $custID, ':uuid' => hex2bin($userUUID)));
                $db->commit();
                $out = array('success' => true);
            } else {
                $safeEmail = htmlspecialchars($email);
                $out = array('error' => 'User not found or password incorrect');
            }
        } else {
            $out = array('error' => 'Username or password are not valid');
        }
    } else {
        $out = array('error' => 'User already logged in');
    }
    return $out;
}
function logout() {
    global $db, $userCustID, $userUUID;
    $db->beginTransaction();
    $logout = $db->prepare('UPDATE bookuuidcustomers SET custID = 0 WHERE uuid = ? AND custID = ?;');
    $logout->execute(array(hex2bin($userUUID), $userCustID));
    $db->commit();
    return array('success' => true);
}
function recent() {
    global $db, $userUUID;
    $out = array();
    $recent = $db->prepare('SELECT DISTINCT d.title, d.ISBN, v.time FROM bookdescriptions d, bookcustomerviews v WHERE d.ISBN = v.ISBN AND v.uuid = ? ORDER BY v.time DESC;');
    $recent->execute(array(hex2bin($userUUID)));
    foreach ($recent->fetchAll() as $item) {
        $viewDate = date(DATE_ATOM, $item['time']);
        $out[] = array('isbn' => $item['ISBN'], 'title' => $item['title'], 'time' => $viewDate);
    }
    return $out;
}
function newBook() {
    global $db, $userCustID;
    $g = $_GET;
    return array('error' => 'Not Authorized');
}
?>
