<?php
ob_start();
session_start();
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head> 
<?php

function getMoney($money) {
		if ($money < 1000000) {
         // Anything less than a million
         return number_format($money);
        } else if ($money < 1000000000) {
         // Anything less than a billion
         return number_format($money / 1000000, 1) . 'M';
        } else {
         // At least a billion
         return number_format($money / 1000000000, 1) . 'B';
        }
}

require_once 'core/classes.php';
require_once 'core/classes/user.php';

$possibleFilters = [
  "hats",
  "shirts",
  "tshirts",
  "pants",
  "gears",
  "packages",
  "heads",
  "torso",
  "leftarm",
  "rightarm",
  "leftleg",
  "rightleg"
];

if(isset($_GET["filter"])) {
  $filter = $_GET["filter"];
  if(!in_array($filter,$possibleFilters)) {
    header('location: /error?err=404');
    exit;
  }
} else {
  $filter = NULL;
}
if(isset($_GET['p'])) {
$page = $_GET['p'];	
} else {
$page = 1;	
}
$limit = 18;
$page -= 1;
$offset = $page * $limit;

$sql = "SELECT allStar FROM catalog ORDER BY RAND() LIMIT 1";
$q = $con->prepare(str_replace('allStar', 'name', $sql));
$q->execute();
$random_search_array = $q->fetch();
if($random_search_array || is_array($random_search_array)) {
$random_search = array_rand($random_search_array, 1);
}

$getitstarted = new PartyStarter;
$getitstarted->header();
?> </head>
<title><?php echo $pagename; ?> | <?php echo $sitename; ?></title>
  <body>
    <main class="container" style="width: 100%;">
      <br>
      <br>
      <form role="search" class="float-end" class="w-75">
        <div class="input-group mb-3 shadow-sm">
          <input class="form-control rounded-end-0" type="search" placeholder="<?php if(is_array($random_search_array)) { echo htmlspecialchars($random_search_array[$random_search]); } else { echo "Search an item..."; }; ?>" name="search" aria-label="Search">
          <button id="search" type="submit" class="btn btn-primary rounded-start-0"><i class="bi bi-search"></i> Search</button>
        </div>
      </form>
      <h2>Catalog</h2>
      <hr>
      <ul class="list-group float-start shadow-sm" style="width: 12rem;">
        <li class="list-group-item text-bg-secondary" aria-current="true">
          <small>Browse by</small>
          <br>
          <h4>Category</h4>
        </li>
        <a href="/catalog" class="list-group-item<?php if($filter == null) { ?> active<?php } ?>" aria-current="true">All categories</a>
        <a href="?filter=hats" class="list-group-item<?php if($filter == "hats") { ?> active<?php } ?>">Hats</a>
        <a href="?filter=shirts" class="list-group-item<?php if($filter == "shirts") { ?> active<?php } ?>">Shirts</a>
		<a href="?filter=tshirts" class="list-group-item<?php if($filter == "tshirts") { ?> active<?php } ?>">T-shirts</a>
        <a href="?filter=pants" class="list-group-item<?php if($filter == "pants") { ?> active<?php } ?>">Pants</a>
        <a href="?filter=gears" class="list-group-item<?php if($filter == "gears") { ?> active<?php } ?>">Gears</a>
        <a href="?filter=packages" class="list-group-item<?php if($filter == "packages") { ?> active<?php } ?>">Packages</a>
        <button class="list-group-item text-start<?php if($filter == "heads" || $filter == "torso" || $filter == "leftarm" || $filter == "rightarm" || $filter == "leftleg" || $filter == "rightleg") { ?> active<?php } ?>" type="button" data-bs-toggle="dropdown" aria-expanded="false">Body parts</button>
        <ul class="dropdown-menu">
          <li>
            <a class="dropdown-item<?php if($filter == "heads") { ?> active<?php } ?>" href="?filter=heads">Heads</a>
          </li>
          <li>
            <a class="dropdown-item<?php if($filter == "torso") { ?> active<?php } ?>" href="?filter=torso">Torso</a>
          </li>
          <li>
            <a class="dropdown-item<?php if($filter == "leftarm") { ?> active<?php } ?>" href="?filter=leftarm">Left arm</a>
          </li>
          <li>
            <a class="dropdown-item<?php if($filter == "rightarm") { ?> active<?php } ?>" href="?filter=rightarm">Right arm</a>
          </li>
          <li>
            <a class="dropdown-item<?php if($filter == "leftleg") { ?> active<?php } ?>" href="?filter=leftleg">Left leg</a>
          </li>
          <li>
            <a class="dropdown-item<?php if($filter == "rightleg") { ?> active<?php } ?>" href="?filter=rightleg">Right leg</a>
          </li>
        </ul>
        <li class="list-group-item">
		  <h5>Legend</h5>
          <span class="badge bg-success" >Limited</span>
          <br>
          <p class="text-white">Limited Items </p>
          <p>Items sold by people that are available for a limited time.</p>
          <!--<div class="pt-2"></div>
          <span class="badge bg-success">Limited <span class="badge bg-warning text-dark">U</span>
          </span>
          <br>
          <p class="text-white">Limited Unique Items</p>
          <p>A limited supply originally sold by <?php echo $sitename; ?>. Each unit is labeled with a serial number. Once sold out, you cannot buy them. </p>!-->
        </li>
      </ul>
      <div class="row row-cols-xl-6 row-cols-lg-4 row-cols-md-3 row-cols-sm-2 g-4" style="margin-left: 200px; margin-top: 1px;"> 
	  <?php
	if ($filter == NULL) {
    $sql = "SELECT allStar FROM catalog";
    $q = $con->prepare(str_replace('allStar', 'COUNT(*)', $sql));
    $q->execute();
	
	$numberOfItems = $q->fetchColumn();
    $q = $con->prepare(str_replace('allStar', '*', $sql));
    $q->execute();
    } else {
    $sql = "SELECT allStar FROM catalog WHERE type=:filter";
    $q = $con->prepare(str_replace('allStar', 'COUNT(*)', $sql));
	$q->bindParam(':filter', $filter);
    $q->execute();
	
	$numberOfItems = $q->fetchColumn();
    $q = $con->prepare(str_replace('allStar', '*', $sql));
	$q->bindParam(':filter', $filter);
    $q->execute();
	}
    if ($numberOfItems >= 1) {
	$rows = array_slice($q->fetchAll(), $offset, $limit);
    foreach ($rows as $item) {
	$query = $con->prepare('SELECT COUNT(id) FROM users WHERE id=:id');
	$query->bindParam(':id', $_SESSION['user'], PDO::PARAM_INT);
    $query->execute();
	$userExists = $query->fetchColumn();
	if($userExists <= 1) {
	$user = new User($con, $item["creator"]);
	  $creator = [
        "id" => (int)htmlspecialchars($item["creator"]),
        "username" => $user->getUsername($con, (int)htmlspecialchars($item["creator"]))
	  ];
    } else {
	   $creator = [
        "id" => 0,
        "username" => "[ unknown user ]"
      ];	
	}
    ?> 
	  <div class="position-relative col">
          <div class="card shadow-sm h-100 d-inline-block">
            <a href="item?id=<?php echo (int)htmlspecialchars($item["id"]); ?>">
			<div class="d-inline-block card-img-top border border-1">
			<img src="<?php if (!empty($item["thumbnail"])) {echo htmlspecialchars($item["thumbnail"]);} else {echo "assets/placeholder.png";} ?>"  height=150 width=150></a>
			<p class="me-1 mt-1 position-absolute top-0 end-0"><?php if($item['limited'] == 1) { echo '<span class="badge bg-success">Limited</span>'; }; ?></p>
			</div>
			<div class="card-body">
              <h5 class="card-title"><?php echo htmlspecialchars($item["name"]); ?></h5>
              <p class="card-text">
			    By <a href="user.php?id=<?php echo (int)htmlspecialchars($creator["id"]); ?>" class="btn-link"><?php echo htmlspecialchars($creator["username"]); ?></a><br>
				<span class="text-success"><span class="grufont fs-5">@ </span><?php echo getMoney((int)htmlspecialchars($item["price"])); ?></span>
              </p>
            </div>
          </div>
        </div>
        <?php
	} 
	} else {
      echo "</div> <h4 class='text-muted text-center'><i class='bi bi-egg-fried' style='font-size: 6rem;'></i><br> Looks like there are no items in the catalog yet...</h4>";} ?>
      <br>
      </div>
<?php
$numberOfPages = ceil($numberOfItems / $limit);
?>
<?php if(is_array($random_search_array)) { ?>
 <div class="d-flex flex-row justify-content-center mb-3">
  <ul class="pagination mt-3">
    <li class="page-item"><a class="page-link" href="?p=<?php if($page > 0) { echo $page; } else { echo 1; } ?>">Previous</a></li>
    <?php 
	for ($i=1; $i<=$numberOfPages; $i++) {  
        if($page == $i){
            $class = 'active';
        }else{
            $class = '';
        }

    if ($page > -1) { 
	 $i - 1;
	 echo "<li class='page-item'><a class='page-link' href='?p=$i'>$i</a></li>";
    }
	}
	?>
    <li class="page-item"><a class="page-link" href="?p=<?php if($page < $numberOfPages) { echo $page + 1; } else { echo $numberOfPages; } ?>">Next</a></li>
  </ul>
 </div>
<?php } ?>
    </main>
  </body>
</html>

