<?php
require_once 'utiluser.php';
require_once 'utilsvalidate.php';
require_once 'encryption.php';
$title = 'Log in';
$content = '';
$newEmailError = '';
$newPasswordError = '';
$newEmail = '';
$loginError = '';
$loginEmail = '';
$beforeForm = '';
$to = '';
if (isset($_REQUEST['orderHistory'])) {
    $beforeForm = '<h1 class="subheading red">Please log in before viewing your order history.</h1>';
    $to = 'orderHistory';
} elseif (isset($_REQUEST['checkout'])) {
    $beforeForm = '<h1 class="subheading red">Please log in before placing your order.</h1>';
    $to = 'checkout';
}
//$hmacPasswordSecret = 'ts1f5SD4THOuUPo+89f/5XgZwYSs5nt5MIOOu1Csu3x9zP7bEdLuu7VBY8BhCW5XD5Tw4dm9vSlV451eY+mDzFJf02T2UofoZbt/u9Nb9Fy1rOznFqVpg+RuiN76xSSI40mwZGms1YVZQKcQQiVYjMcgDV6IxqH6lUY1rCs9w5o=';
if (isset($_REQUEST['logout'])) {
    $db->beginTransaction();
    $logout = $db->prepare('UPDATE bookuuidcustomers SET custID = 0 WHERE uuid = ? AND custID = ?;');
    $logout->execute(array(hex2bin($userUUID), $userCustID));
    $db->commit();
    header('location: index.php');
    exit();
} elseif ($userCustID > 0 && isset($_GET['update'])) {
    $fieldsSet = (isset($_POST['email'])
        && isset($_POST['fname'])
        && isset($_POST['lname'])
        && isset($_POST['street'])
        && isset($_POST['city'])
        && isset($_POST['state'])
        && isset($_POST['zip']));
    if ($fieldsSet) {
        $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) {
            $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)...");
            }
        }
        header('location: account.php');
        exit();
    }
    $title = 'Update My Account';
    $query = $db->prepare('SELECT custID, fname, lname, email, street, city, state, zip FROM bookCustomers WHERE custID = ?;');
    $query->execute(array($userCustID));
    $fname = '';
    $lname = '';
    $email = '';
    $street = '';
    $city = '';
    $state = '';
    $zip = '';
    $custID = '';
    $existing = '';
    $email = '';
    if ($query->rowCount() > 0) {
        $result = $query->fetch();
        $fname = $result['fname'];
        $lname = $result['lname'];
        $email = $result['email'];
        $street = $result['street'];
        $city = $result['city'];
        $state = $result['state'];
        $zip = $result['zip'];
        $existing = "<p class=\"center\">Welcome back <strong>$fname</strong>! Please update your account information.</p>";
    }
    $content .= <<<EOF
  <div class="formGroup">
  <form method="post" class="checkout required">
  <h1 class="red subheading">Update customer information</h1>$existing
  <div><label><span>Email:</span><input name="email" type="email" placeholder="joe@example.com" required="required" value="$email" maxlength="50" pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"></label></div>
  <div><label><span>First Name:</span><input name="fname" type="text" placeholder="First Name" required="required" value="$fname" autofocus maxlength="20" pattern="[a-zA-Z'-]{2,20}"></label></div>
  <div><label><span>Last Name:</span><input name="lname" type="text" placeholder="Last Name" required="required" value="$lname" maxlength="20" pattern="[a-zA-Z'-]{2,20}"></label></div>
  <div><label><span>Street Address:</span><input name="street" type="text" placeholder="Street Address" required="required" value="$street" maxlength="25"></label></div>
  <div><label><span>City:</span><input name="city" type="text" placeholder="City" required="required" value="$city" maxlength="30"></label></div>
  <div><label><span>State:</span><input name="state" type="text" placeholder="State" required="required" value="$state" maxlength="2" size="2"></label></div>
  <div><label><span>Zip:</span><input name="zip" type="text" placeholder="98226" required="required" value="$zip" maxlength="5" size="5"></label></div>
  <input type="submit"> <input value="Reset form" type="reset">$custID
  </form>
  </div>
EOF;

} elseif ($userCustID > 0) {
    $title = 'My Account';
    $user = $db->prepare('SELECT custID, fname, lname, email, street, city, state, zip FROM bookCustomers WHERE custID = ?;');
    $user->execute(array($userCustID));
    if ($user->rowCount() != 1) {
        header('location: account.php?logout=true');
        exit();
    }
    $result = $user->fetch();
    $fname = $result['fname'];
    $lname = $result['lname'];
    $email = $result['email'];
    $street = $result['street'];
    $city = $result['city'];
    $state = $result['state'];
    $zip = $result['zip'];
    $content .= "<h1 class=\"subheading\">Welcome back!</h1>";
    $content .= "<div class=\"formGroup\"><form method=\"get\" class=\"checkout\"><p class=\"subheading center\">We currently have the following information about you:</p><input type=\"hidden\" name=\"update\" value=\"1\">";
    $content .= "<div><label><span>Email:</span> <input value=\"$email\" readonly></label></div>";
    $content .= (strlen($fname . $lname) > 0) ? "<div><label><span>Name:</span> <input value=\"$fname $lname\" readonly></div>" : '';
    $content .= (strlen($street) > 0) ? "<div><label><span>Street Address:</span> <input value=\"$street\" readonly></div>" : '';
    $content .= (strlen($city) > 0) ? "<div><label><span>City:</span> <input value=\"$city\" readonly></div>" : '';
    $content .= (strlen($state) > 0) ? "<div><label><span>State:</span> <input value=\"$state\" readonly size=\"2\"></div>" : '';
    $content .= (strlen($zip) > 0) ? "<div><label><span>Zip:</span> <input value=\"$zip\" readonly size=\"5\"></div>" : '';
    $content .= "<div>Would you like to <a href=\"account.php?update=true\">update</a> this information?</div></form></div><br><div>View your <a href=\"orderHistory.php\">order history</a>?</div>";
} else {
    if (isset($_POST['newemail']) && isset($_POST['password']) && isset($_POST['confirm'])) {
        $email = filter_var($_POST['newemail'], FILTER_SANITIZE_EMAIL);
        $password = validString($_POST['password'], strlen($_POST['password']), 5);
        $confirm = validString($_POST['confirm'], strlen($_POST['confirm']), 5);
        $existing = $db->prepare('SELECT custID FROM bookCustomers WHERE email like ?;');
        $existing->execute(array("%$email%"));
        if (strlen($email) > 0 && $password === $confirm && $existing->rowCount() <= 0) {
            $db->beginTransaction();
            $new = $db->prepare("INSERT INTO bookCustomers (email, salt, fname, lname, street, city, state, zip) VALUES (:email, :salt, '', '', '', '', '', '');");
            $salt = openssl_random_pseudo_bytes(8);
            $pwHash = hex2bin(hash_hmac('sha512', $email . $password . $salt, $hmacPasswordSecret));
            $fields = array(':email' => $email, ':salt' => $salt);
            $password = $db->prepare('INSERT INTO bookpwhash (password) VALUES (?);');
            $password->execute(array($pwHash));
            $new->execute($fields);
            $custID = $db->lastInsertId();
            $updateUUID = $db->prepare('UPDATE bookuuidcustomers SET custID = ? WHERE uuid = ?;');
            $updateUUID->execute(array($custID, hex2bin($userUUID)));
            $db->commit();
            header('location: account.php');
            exit();
        } else {
            if (!$email) {
                $newEmailError .= '<div class="red">Please enter a valid email address.</div>';
            } elseif ($existing->rowCount() > 0) {
                $newEmailError .= '<div class="red">Please choose a different email address.</div>';
                $newEmail = $email;
            } else {
                $newEmail = $email;
            }
            if ($password != $confirm) {
                $newPasswordError .= '<div class="red">Please confirm you typed your password correctly twice.</div>';
            }
        }
    } elseif (isset($_POST['email']) && isset($_POST['password'])) {
        $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        $password = validString($_POST['password'], strlen($_POST['password']), 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();
                if ($to == 'orderHistory') {
                    header('location: orderHistory.php');
                } elseif ($to == 'checkout') {
                    header('location: checkout02.php');
                } else {
                    header('location: account.php');
                }
                exit();
            } else {
                $loginEmail = $email;
                $loginError = "<div class=\"red\">Username or password not found in database.</div>";
            }
        }
    }
    $redirect = "<input type=\"hidden\" name=\"$to\" value=\"true\">";
    $login = <<<EOF
  $beforeForm
  <div class="formGroup">
  <form method="post" class="checkout required" action="account.php">
  <h1 class="subheading">Log in</h1>
  <div><label><span>Email:</span><input name="email" type="email" placeholder="joe@example.com" required="required" maxlength="50" pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" value="$loginEmail"></label></div>
  <div><label><span>Password:</span><input name="password" type="password" required="required" pattern=".{6,}"></label></div>$loginError$redirect
  <input type="submit" value="Log in">
  </form>
  <form method="post" class="checkout required">
  <h1 class="subheading">Create a new account</h1>
  <div><label><span>Email:</span><input name="newemail" type="email" placeholder="joe@example.com" required="required" maxlength="50" pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" value="$newEmail"></label></div>$newEmailError
  <div><label><span>Password:</span><input name="password" type="password" required="required" pattern=".{6,}"></label></div>
  <div><label><span>Confirm Password:</span><input name="confirm" type="password" required="required" pattern=".{6,}"></label></div>$newPasswordError
  <input type="submit" value="Create">
  </form>
  </div>
EOF;
    $content = $login;
}
require 'template.php';
?>
