<?php header('Content-type: text/html; charset=utf-8'); ?>
<?php
  /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */
  require_once "C:/wamp/www/cmsbuilder_1_31/cmsAdmin/lib/viewer_functions.php";

  function assertRecordExists($record) {
    // show error message if no matching record is found
    if (!$record) {
      print "Record not found!";
      exit;
    }
  }

  // if user supplied category num in query string (e.g. "?category=123"), select a random product from that category
  $catNum = (int) @$_GET['category'];
  if ( $catNum ) {
    list($selectedProductsRecords, $productsMetaData) = getRecords(array(
      'tableName'   => 'products',
      'where'       => "category = $catNum",
      'orderBy'     => 'RAND()',
      'limit'       => '1',
    ));
    $selectedProductsRecord = @$selectedProductsRecords[0]; // get first record
    assertRecordExists($selectedProductsRecord);
  }
  // if user did not supply a category, assume they supplied a product num and display that product (also, determine category num for right-side list from that product)
  else {
    list($selectedProductsRecords, $productsMetaData) = getRecords(array(
      'tableName'   => 'products',
      'where'       => whereRecordNumberInUrl(1),
      'limit'       => '1',
    ));
    $selectedProductsRecord = @$selectedProductsRecords[0]; // get first record
    assertRecordExists($selectedProductsRecord);
    $catNum = $selectedProductsRecord['category'];
  }

  // get all products in category
  list($categoryProductsRecords, $productsMetaData) = getRecords(array(
    'tableName'   => 'products',
    'where'       => "category = $catNum",
  ));
  
  // get category record so we can show its name:
  list($categoryRecords, $categoryMetaData) = getRecords(array( 
    'tableName'   => 'category', 
    'where'       => "num = $catNum", 
    'limit'       => '1', 
  )); 
  $categoryRecord = @$categoryRecords[0]; // get first record
  
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
 </head>
<body>
  <!-- DISPLAY SELECTED PRODUCT -->
    <h1>Selected Product</h1>
      <?php echo $selectedProductsRecord['title'] ?><br/>
  <!-- /DISPLAY SELECTED PRODUCT -->

  <!-- DISPLAY PRODUCTS IN CATEGORY -->
   <h1>Products in Category: <?php echo $categoryRecord['name'] ?></h1>
    <?php foreach ($categoryProductsRecords as $record): ?>
      <a href="?product=<?php echo $record['num'] ?>">
        <?php echo $record['title'] ?><br/>
      </a>
    <?php endforeach; ?>
  <!-- /DISPLAY PRODUCTS IN CATEGORY -->

</body>
</html>
