public function view()
 {
     session_start();
     // load trending items
     include 'models/itemModel.php';
     $itemModel = new itemModel();
     $trendingItemArray = array();
     $result = $itemModel->getTrendingItemList();
     for ($i = 0; $i < 5; $i++) {
         $row = pg_fetch_row($result);
         $item = array($row[0], $row[1], $row[2], $row[3]);
         // [0]: item name, [1]: owner name, [2]: price, [3]: image url
         array_push($trendingItemArray, $item);
     }
     /*
     		$itemModel = new itemModel();
     		$result = $itemModel->getItemKeyByMostLoanrequest();
     		$trendingItemIdArray = pg_fetch_all($result);
     
     		$trendingItemArray = [];
     		for ($i = 0; $i < 5; $i++) {
     			$result = $itemModel->getByKey($trendingItemIdArray[$i]["owner"], $trendingItemIdArray[$i]["item_name"]);
     			$trendingItemArray[] = pg_fetch_array($result);
     		}
     */
     // load view
     include 'views/home.php';
 }
 public function uploadCoverPhoto($item_name, $owner)
 {
     $fileName = $this->uploadFile();
     if ($fileName != null) {
         $itemModel = new itemModel();
         $queryResult = false;
         $queryResult = $itemModel->addCoverImage($item_name, $owner, $fileName);
         if (!$queryResult) {
             $photoUploadError = true;
             $photoUploadErrorMessage = "<p class=\"text-danger\">Image upload Failed! Please contact admin.</p>";
         }
     }
 }
 public function view()
 {
     session_start();
     include 'models/memberModel.php';
     include 'models/itemModel.php';
     $submitSuccess = false;
     $submitError = false;
     $username = $_SESSION['username'];
     $itemModel = new itemModel();
     if (isset($_POST["submit"])) {
         $item_name = $_POST['itemName'];
         $owner = $username;
         $category = $_POST['category'];
         $price = $_POST['price'];
         $description = $_POST['item_info'];
         $location = $_POST['location'];
         $date_start = explode("/", $_POST['start']);
         $date_end = explode("/", $_POST['end']);
         $date_start_string = $date_start[1] . "/" . $date_start[0] . "/" . $date_start[2];
         $date_end_string = $date_end[1] . "/" . $date_end[0] . "/" . $date_end[2];
         $result = $itemModel->addLoan($item_name, $owner, $category, $price, $description, $location);
         $dateResult = $itemModel->addAvailableDates($item_name, $owner, $date_start_string, $date_end_string);
         $uploadImage = new imageController();
         $uploadImage->uploadCoverPhoto($item_name, $owner);
         if (!$result) {
             // $loanCreationError = true;
             $submitError = true;
             $loanCreationErrorMessage = "<p class=\"text-danger\">Loan Creation Failed! Please contact admin.</p>";
         }
         if (!$dateResult) {
             $submitError = true;
             $dateErrorMessage = "<p class=\"text-danger\">Date Failed! Please contact admin.</p>";
         }
         if ($result) {
             $submitSuccess = true;
         } else {
             $submitError = true;
         }
     }
     // load view
     include 'views/loan.php';
 }
 public function view()
 {
     session_start();
     $itemName = '';
     $itemOwner = '';
     $itemBorrower = '';
     $isValidBid = false;
     // Check that URL has required fields
     if (empty($_GET['item']) || empty($_GET['owner']) || empty($_GET['borrower'])) {
         header("Location:index.php");
         return;
     }
     $itemName = $_GET['item'];
     $itemOwner = $_GET['owner'];
     $itemBorrower = $_GET['borrower'];
     $currentUser = $_SESSION['username'];
     // Getting the item
     include 'models/itemModel.php';
     $itemModel = new itemModel();
     $queryResult = $itemModel->getByKey($itemOwner, $itemName);
     // Ensures that message session is for item that exist
     if ($queryResult == false) {
         $this->goToPreviousPage();
         return;
     }
     $item = pg_fetch_array($queryResult);
     $itemImage = $item['image_url'];
     $itemPrice = $item['price'];
     // Getting the members
     include 'models/memberModel.php';
     $memberModel = new memberModel();
     // Ensures that message session is for members that exist
     if (!$memberModel->memberExist($itemOwner) || !$memberModel->memberExist($itemBorrower)) {
         $this->goToPreviousPage();
         return;
     }
     // Ensures that current logged in user belongs to message session
     if ($currentUser != $itemOwner && $currentUser != $itemBorrower) {
         $this->goToPreviousPage();
         return;
     }
     // Ensures that user is not sending message to self
     if ($itemOwner == $itemBorrower) {
         $this->goToPreviousPage();
         return;
     }
     // Getting the loan request
     include 'models/loanRequestModel.php';
     $loanRequestModel = new loanRequestModel();
     $bidMade = $loanRequestModel->getLoanRequestByOwnerItemBorrower($itemOwner, $itemName, $itemBorrower);
     if ($bidMade != false) {
         $bid = pg_fetch_array($bidMade);
         $date_start = $bid['date_start'];
         $bidStatus = $bid['status'];
         $bidPrice = $bid['price_offer'];
         $isValidBid = $bid['is_valid'];
     }
     // Checks if is an accept or reject
     if (isset($_POST['accept'])) {
         $loanRequestModel->acceptLoanRequest($itemName, $itemOwner, $itemBorrower, $date_start);
         $bidStatus = 'accepted';
     }
     if (isset($_POST['reject'])) {
         $loanRequestModel->rejectLoanRequest($itemName, $itemOwner, $itemBorrower, $date_start);
         $bidStatus = 'declined';
     }
     // get all past messages
     include 'models/messageModel.php';
     $messageModel = new messageModel();
     // Check for new message sent
     if (isset($_POST['msg-content'])) {
         $content = $_POST['msg-content'];
         $sender = $itemBorrower;
         $receiver = $itemOwner;
         if ($currentUser == $itemOwner) {
             $sender = $itemOwner;
             $receiver = $itemBorrower;
         }
         $messageModel->addMessage($itemName, $itemOwner, $sender, $receiver, $content);
     }
     $chatHistory = $messageModel->getChatHistoryInOrder($itemName, $itemOwner, $itemBorrower);
     // get user profile images
     $ownerProfile = $memberModel->getUserByUsername($itemOwner);
     $ownerIcon = pg_fetch_row($ownerProfile)[5];
     $borrowerProfile = $memberModel->getUserByUsername($itemBorrower);
     $borrowerIcon = pg_fetch_row($borrowerProfile)[5];
     // put all messages into an array
     $messageArray = array();
     while ($row = pg_fetch_row($chatHistory)) {
         $msgSender = $row[2];
         if ($msgSender == $itemOwner) {
             $msgSenderIcon = $ownerIcon;
         } else {
             $msgSenderIcon = $borrowerIcon;
         }
         $msgContent = $row[4];
         $msgTimestamp = $row[5];
         $message = array($msgSender, $msgSenderIcon, $msgContent, $msgTimestamp);
         array_push($messageArray, $message);
     }
     include 'views/message.php';
 }
} else {
    if (isset($_POST['item_name']) && isset($_POST['owner']) && isset($_POST['category']) && isset($_POST['price']) && isset($_POST['location']) && isset($_POST['description'])) {
        // adding item entry
        include 'models/itemModel.php';
        $itemModel = new itemModel();
        $result = $itemModel->addLoan($_POST['item_name'], $_POST['owner'], $_POST['category'], $_POST['price'], $_POST['description'], $_POST['location']);
        if ($result == true) {
            $result = "<p class='text-success'>Item Successfully Created!</p>";
        } else {
            $result = "<p class='text-danger'>Error Occured! Try checking your database constraint.</p>";
        }
    } else {
        if (isset($_POST['item_name']) && isset($_POST['owner']) && isset($_POST['image_url'])) {
            // adding image url entry
            include 'models/itemModel.php';
            $itemModel = new itemModel();
            if (isset($_POST['is_cover'])) {
                $result = $itemModel->addCoverImage($_POST['item_name'], $_POST['owner'], $_POST['image_url']);
            } else {
                $result = $itemModel->addNonCoverImage($_POST['item_name'], $_POST['owner'], $_POST['image_url']);
            }
            if ($result == true) {
                $result = "<p class='text-success'>Item Image Successfully Created!</p>";
            } else {
                $result = "<p class='text-danger'>Error Occured! Try checking your database constraint.</p>";
            }
        } else {
            if (isset($_POST['item_name']) && isset($_POST['owner']) && isset($_POST['commentor']) && isset($_POST['content'])) {
                // adding comment entry
                include 'models/commentModel.php';
                $commentModel = new commentModel();
<?php

include 'models/tableModel.php';
include 'models/memberModel.php';
include 'models/loanRequestModel.php';
include 'models/itemModel.php';
include 'models/reviewModel.php';
include 'models/messageModel.php';
$loanRequestModel = new loanRequestModel();
$tableModel = new tableModel();
$memberModel = new memberModel();
$itemModel = new itemModel();
$reviewModel = new reviewModel();
$messageModel = new messageModel();
?>

<div class="wrapper">
	<div class="col-md-10">
            <h1>Statistics</h1>
            <div class="panel panel-info">
                <div class="panel-body">
                    <!-- Nav tabs -->
                    <ul class="nav nav-tabs" role="tablist">
                        <li role="presentation" class="active"><a href="#user" aria-controls="home" role="tab" data-toggle="tab">User</a></li>
                        <li role="presentation"><a href="#items" aria-controls="profile" role="tab" data-toggle="tab">Items</a></li>
                        <li role="presentation"><a href="#loans" aria-controls="home" role="tab" data-toggle="tab">Loans</a></li>
                        <li role="presentation"><a href="#messages" aria-controls="home" role="tab" data-toggle="tab">Messages</a></li>
                        <li role="presentation"><a href="#others" aria-controls="home" role="tab" data-toggle="tab">Others</a></li>
                    </ul>
                    <!-- Tab panes -->
                    <div class="tab-content">
 public function view()
 {
     session_start();
     $owner = '';
     $itemName = '';
     if (!empty($_GET['owner']) && !empty($_GET['item'])) {
         $owner = $_GET['owner'];
         $itemName = $_GET['item'];
     }
     // get item info
     include 'models/itemModel.php';
     include 'models/memberModel.php';
     include 'models/itemAvailabilityModel.php';
     include 'models/commentModel.php';
     include 'models/loanRequestModel.php';
     $loanRequestModel = new loanRequestModel();
     $itemModel = new itemModel();
     $memberModel = new memberModel();
     $itemAvailabilityModel = new itemAvailabilityModel();
     $commentModel = new commentModel();
     $result = $itemModel->getByKey($owner, $itemName);
     $item = pg_fetch_array($result);
     $submitSuccess = false;
     $submitError = false;
     if (!empty($_POST)) {
         if ($_POST['action'] == 'requestLoan') {
             if ($_POST['start'] == '' || $_POST['end'] == '' || $_POST['bidPrice'] == '') {
                 $submitError = true;
             } else {
                 // process loan request
                 $start = $_POST['start'];
                 $end = $_POST['end'];
                 $bidPrice = $_POST['bidPrice'];
                 $request = $loanRequestModel->addLoanRequest($item['item_name'], $item['owner'], $_SESSION['username'], $start, $end, $bidPrice);
                 if ($request) {
                     $submitSuccess = true;
                 } else {
                     $submitError = true;
                 }
             }
         }
         if ($_POST['action'] == 'submitComment') {
             $commentModel->addComment($_POST['item_name'], $_POST['owner'], $_SESSION['username'], $_POST['content']);
         }
     }
     // get all available dates
     $result = $itemAvailabilityModel->getAllByItemKey($owner, $itemName);
     $availabilityArray = pg_fetch_all($result);
     // get all accepted pending
     $result = $loanRequestModel->getAllAcceptedByItem($itemName, $owner);
     $acceptedArray = pg_fetch_all($result);
     if ($acceptedArray) {
         $acceptedDates = [];
         foreach ($acceptedArray as $accepted) {
             $startDate = strtotime($accepted['date_start']);
             $endDate = strtotime($accepted['date_end']);
             $yearStart = intval(date("Y", $startDate));
             $monthStart = intval(date("m", $startDate));
             $dateStart = intval(date("d", $startDate));
             $yearEnd = intval(date("Y", $endDate));
             $monthEnd = intval(date("m", $endDate));
             $dateEnd = intval(date("d", $endDate));
             for ($y = $yearStart; $y <= $yearEnd; $y++) {
                 for ($m = $monthStart; $m <= $monthEnd; $m++) {
                     for ($d = $dateStart; $d <= $dateEnd; $d++) {
                         $acceptedDates[] = $d . '-' . $m . '-' . $y;
                     }
                 }
             }
         }
     }
     $freeDates = [];
     if ($availabilityArray) {
         foreach ($availabilityArray as $availability) {
             $startDate = strtotime($availability['date_start']);
             $endDate = strtotime($availability['date_end']);
             $yearStart = intval(date("Y", $startDate));
             $monthStart = intval(date("m", $startDate));
             $dateStart = intval(date("d", $startDate));
             $yearEnd = intval(date("Y", $endDate));
             $monthEnd = intval(date("m", $endDate));
             $dateEnd = intval(date("d", $endDate));
             for ($y = $yearStart; $y <= $yearEnd; $y++) {
                 for ($m = $monthStart; $m <= $monthEnd; $m++) {
                     for ($d = $dateStart; $d <= $dateEnd; $d++) {
                         $freeDates[] = $d . '-' . $m . '-' . $y;
                     }
                 }
             }
         }
     }
     if ($acceptedArray) {
         for ($i = 0; $i < count($freeDates); $i++) {
             for ($j = 0; $j < count($acceptedDates); $j++) {
                 if (strcmp($freeDates[$i], $acceptedDates[$j]) == 0) {
                     $freeDates[$i] = -1;
                 }
             }
         }
     }
     // get all comments
     date_default_timezone_set("Asia/Singapore");
     $result = $commentModel->getCommentsByItemKey($owner, $itemName);
     $commentArray = pg_fetch_all($result);
     include 'views/item.php';
 }
 public function view()
 {
     session_start();
     include 'models/memberModel.php';
     include 'models/reviewModel.php';
     include 'models/itemModel.php';
     include 'helpers/timestampParser.php';
     $timestampParser = new timestampParser();
     // get string of user to be viewed
     if (isset($_GET['profile']) && $_GET['profile'] != $_SESSION['username']) {
         $profileStringQuery = $_GET['profile'];
     } else {
         $profileStringQuery = $_SESSION['username'];
         $isViewingOwnProfile = true;
     }
     /* this part deals with the user attempting to submit a review */
     if (isset($_POST['submit-review'])) {
         // parse POST data
         $reviewer = $_SESSION['username'];
         $reviewee = $_GET['profile'];
         $content = str_replace("'", "''", $_POST['content']);
         if ($_POST['review'] == "positive") {
             $isPositive = 1;
         } else {
             $isPositive = 0;
         }
         // view will access the model directly to insert review into database
         $reviewModel = new reviewModel();
         $result = $reviewModel->addNewReview($reviewer, $reviewee, $content, $isPositive);
         // clear variables
         unset($_POST['submit-review']);
         unset($_POST['content']);
         unset($_POST['review']);
         if ($result) {
             $reviewSuccessMessage = '<p class="text-success">Review successfully added.</p>';
         } else {
             $reviewSuccessMessage = '<p class="text-danger">An error occured. Review not added.</p>';
         }
     }
     /* this part onwards deals with the rendering of the profile page */
     // query database to retrieve user information
     $memberModel = new memberModel();
     $queryResult = $memberModel->getUserByUsername($profileStringQuery);
     $resultCount = pg_num_rows($queryResult);
     // check if user exists
     if ($resultCount == 1) {
         // initialize data for profile page
         $data = pg_fetch_row($queryResult);
         $profileName = $data[0];
         $profileEmail = $data[3];
         $profileDescription = $data[4];
         $profileDisplayPictureURL = "img/display_pic/" . $data[5];
         $profileLastLoggedIn = $timestampParser->getFormattedTimestampFromTimestamp($data[7]);
         // parse both review and item results into 2 arrays
         $reviewArray = array();
         $itemArray = array();
         $counter = 0;
         $positiveReviews = 0;
         $negativeReviews = 0;
         // get all reviews of this user
         $reviewModel = new reviewModel();
         $reviewResult = $reviewModel->getAllReviewsOf($profileName);
         // create review array
         while ($row = pg_fetch_row($reviewResult)) {
             $row[3] == 1 ? $positiveReviews++ : $negativeReviews++;
             $review = array($row[0], $row[2], $row[3], $timestampParser->getFormattedTimestampFromTimestamp($row[4]));
             // row[0]: reviewer, row[2]: review content, row[3]: positive/negative, row[4]: time of review
             array_push($reviewArray, $review);
             $counter++;
         }
         $totalReviews = $positiveReviews + $negativeReviews;
         $counter = 0;
         // load items put up by user
         $itemModel = new itemModel();
         $itemResult = $itemModel->getAllItemsOfUser($profileName);
         // create item array
         while ($row = pg_fetch_row($itemResult)) {
             $itemImageResult = $itemModel->getCoverImageOfItem($row[0], $row[1]);
             // get cover photo for each item
             $imageURL = pg_fetch_row($itemImageResult)[0];
             // it should only have one row
             if ($imageURL == NULL) {
                 $imageURL = "img/tempLogo.jpg";
             } else {
                 $imageURL = "img/items/" . $imageURL;
             }
             $item = array($row[0], $imageURL);
             array_push($itemArray, $item);
             $counter++;
         }
         // lastly, run the profile view
         include 'views/profile.php';
     } else {
         // no result, redirect to home
         $home = new homeController();
         $home->view();
     }
 }