<?php

/**
 * Created by PhpStorm.
 * User: cristina
 * Date: 3/3/2016
 * Time: 2:58 PM
 */
require_once '../../includes/main.php';
set_include_path(getIncludePath());
require 'DBConnect.php';
require 'DBCalls.php';
require 'secSession.php';
sec_session_start();
$passcode = filter_input(INPUT_POST, 'passAct', FILTER_SANITIZE_STRING);
$bookID = filter_input(INPUT_POST, 'bookID', FILTER_SANITIZE_STRING);
$con = new DBConnect('marketplace');
$calls = new DBCalls();
$bookURL = $calls->getBookURLFromID($con, $bookID);
$passCorrect = $calls->checkBookPasscode($con, $bookID, $passcode);
if ($passCorrect && $bookURL) {
    // SESSION var, so cleared when you exit the browser.
    $_SESSION['lastPass'] = $passcode;
    header("location:../books/{$bookURL}/index.php?");
} else {
    header("location:../books/{$bookURL}/index.php?badPass=true");
}
$depVersion = 16;
// TODO: Call the function to return the latest version
$releaseVersion = 1;
$username = isset($_SESSION['username']) ? $_SESSION['username'] : false;
$con = new DBConnect('marketplace');
$calls = new DBCalls();
$url = $_SERVER['PHP_SELF'];
$urlArr = explode("/", $url);
$bookName = array_pop($urlArr);
if ($bookName == "index.php") {
    $bookName = array_pop($urlArr);
}
$bookID = $calls->getBookIDFromURLName($con, $bookName);
$readerID = $calls->getIDFromReaderName($con, $username);
$ownsBook = $calls->ownsBook($con, $readerID, $bookID);
if (isset($_SESSION['lastPass'])) {
    $lastPass = $_SESSION['lastPass'];
    $passCheck = $calls->checkBookPasscode($con, $bookID, $lastPass);
}
$passCheck = isset($passCheck) ? $passCheck : false;
if ($ownsBook || isset($bookIsFree) && $bookIsFree || $passCheck) {
    $replace = array('{depVersion}', '{releaseVersion}', '{privateNotice}', '{authorTesting}', '{curTester}', '{testComplete}', '{usedPasscode}');
    $with = array($depVersion, $releaseVersion, false, false, false, false, $passCheck);
    new HTMLTemplate('pubblyBookIndex', $replace, $with);
} else {
    // TODO: If book has passcode, display bookPasscode template. Else display private book template.
    $badPass = isset($_GET['badPass']) ? true : false;
    $replace = array('{curID}', '{badPass}');
    $with = array($bookID, $badPass);
    new HTMLTemplate('bookPasscode', $replace, $with);
}