<?php
/** 
 *
 * @copyright Copyright 2003-2007 Paul Mathot Haarlem, The Netherlands & Carine Bruyndoncx, Belgium
 * @copyright parts Copyright 2003-2005 Zen Cart Development Team
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version v1.5.0 (or newer)
 */
if (!defined('IS_ADMIN_FLAG')) {
  die('Illegal Access');
}
require(DIR_WS_MODULES . 'require_languages.php');

if (isset($_POST['category'])){
  // POST form in tpl_main_page.php
  $_SESSION['pl_category'] = (int)$_POST['category'];
}
    
/* begin profiles  */
// set the current profile
if (isset($_GET[profile])) {
  $pl_set_profile = (int)$_GET['profile'];
} else {
  $pl_set_profile = PL_DEFAULT_PROFILE;
}
//eval('$pl_tmp = PL_ENABLE_' . $pl_set_profile . ';');

$pl_errorMessage = '';
if (!(defined('PL_ENABLE_' . $pl_set_profile))) {
  // profile does not exist
  $pl_errorMessage = 'ERROR! Profile does not exist, loading default Profile instead.';
  define('PL_PROFILE', PL_DEFAULT_PROFILE);
} else {
  define('PL_PROFILE', $pl_set_profile);
}
// eof set the current profile

/* bof define settings depending on current profile nr. */
// example:
// if the pricelist database settings define PL_SHOW_TAX_FREE_1, PL_SHOW_TAX_FREE_2 and PL_SHOW_TAX_FREE_3 (the values of PL_SHOW_TAX_FREE for profile 1, 2 and 3)
// the array below should have a value PL_SHOW_TAX_FREE
$pl_profile_settings =
  array(
        'PL_SHOW_PRICES',  
        'PL_DEFAULT_SHOW_ALL_CATS',
        'PL_PROFILE_NAME',
        'PL_PRINTING_STYLESHEET',
        'PL_MAINCATS_NEW_PAGE',
        'PL_MAINCATS_NEW_TABLE',
        'PL_NOWRAP',
        'PL_MAXCOLUMNS',
        'PL_MAXLINES',
        'PL_SHOW_TAX_FREE',
        'PL_SHOW_MODEL',
        'PL_SHOW_INACTIVE',
        'PL_SHOW_MANUFACTURER',
        'PL_SHOW_WEIGHT',
        'PL_SHOW_NOTES_A',
        'PL_SHOW_NOTES_B',
        'PL_SORT_ASC_DESC',
        'PL_SORT_PRODUCTS_BY',
        'PL_SHOW_BOXES',
        'PL_SHOW_SOH',
        'PL_SHOW_IMAGE',
        'PL_IMAGE_PRODUCT_HEIGHT',
        'PL_IMAGE_PRODUCT_WIDTH',
        'PL_SHOW_DESCRIPTION',
        'PL_IMGDESC_EXTRALINES',
        'PL_SHOW_PRICELIST_PAGE_HEADERS',
        'PL_SHOW_PRICELIST_PAGE_FOOTERS',
        'TEXT_PL_HEADER_LOGO',
        'PL_SHOW_ADDTOCART_BUTTON',
        'PL_ONLY_ADDTOCART_BUTTON',
        'PL_ADDTOCART_TARGET',
        'PL_USE_MASTER_CATS_ONLY',
        'PL_SHOW_PRICE',
        'PL_DEBUG',
        'PL_PAGE_HEIGHT',
        'PL_SHOW_SPECIAL_PRICE',
        'PL_SHOW_SPECIAL_DATE',        
        'PL_CATEGORY_TREE_MAIN_CATS_ONLY',
        'PL_TRUNCATE_DESCRIPTION'                
       );

foreach($pl_profile_settings as $pl_profile_setting){
  // here PL_SHOW_TAX_FREE (for example) is defined as the value of PL_SHOW_TAX_FREE_1, PL_SHOW_TAX_FREE_2 or PL_SHOW_TAX_FREE_3 depending on the selected profile
  define($pl_profile_setting, @constant($pl_profile_setting . '_' . PL_PROFILE));
}

// commented out because we only want one table heading, not seperate ones for each profile
//Added by Vartan Kat on july 2007 for Add to cart button
//eval('$pl_profile = TABLE_HEADING_ADDTOCART_' . PL_PROFILE . ';');
//define('TABLE_HEADING_ADDTOCART', $pl_profile);
//End of Added by Vartan Kat on july 2007 for Add to cart button

//added 2005-09-03 paulm (move to database)
// if (LP_PROFILE == 2) {
//  define('LP_EXTRA_CONDITION_2', 'p.products_weight = "0"');

define('PL_EXTRA_CONDITION', ''); // remove?

/* eof define settings depending on current profile nr. */

switch (true) {
    case (PL_SORT_PRODUCTS_BY == 'products_name'):
        define ('PL_SORT_PRODUCTS', 'pd.' . PL_SORT_PRODUCTS_BY);
        break;

    case (in_array(PL_SORT_PRODUCTS_BY , array('products_price','products_model','products_weight'))):
        define ('PL_SORT_PRODUCTS', 'p.' . PL_SORT_PRODUCTS_BY);
        break;

// BOF multiple_calculations addon
    case (in_array(PL_SORT_PRODUCTS_BY , array('products_advice_price','products_margin','products_purchase_price'))):
        define ('PL_SORT_PRODUCTS', 'p.' . PL_SORT_PRODUCTS_BY);
        break;
// EOF multiple_calculations addon

    default:
        define ('PL_SORT_PRODUCTS', 'p.' . 'products_id');
}

/* end profiles and other new zen parts */

// name column
$pl_header_columns_count = 1;
// optional colmuns
if (PL_SHOW_PRICE == 'true') {
    $pl_header_columns_count++;
}
if (PL_SHOW_TAX_FREE == 'true') {
    $pl_header_columns_count++;
}
if (PL_SHOW_MODEL == 'true') {
    $pl_header_columns_count++;
}
if (PL_SHOW_MANUFACTURER == 'true') {
    $pl_header_columns_count++;
}
if (PL_SHOW_WEIGHT == 'true') {
    $pl_header_columns_count++;
}
if (PL_SHOW_NOTES_A == 'true') {
    $pl_header_columns_count++;
}
if (PL_SHOW_NOTES_B == 'true') {
    $pl_header_columns_count++;
}
// stock by bmoroney
if (PL_SHOW_SOH == 'true') {
    $pl_header_columns_count++;
}
//Added by Vartan Kat on july 2007 for Add to cart button
if (PL_SHOW_ADDTOCART_BUTTON == 'true') {
    $pl_header_columns_count++;
}
//End of Added by Vartan Kat on july 2007 for Add to cart button
    
define ('PL_DATE', strftime(DATE_FORMAT_LONG));
define ('PL_HEADER_COLUMNS_COUNT', $pl_header_columns_count);

define ('PL_CURR_SYMBOL', $currencies->currencies[$_SESSION['currency']]['symbol_left'] . $currencies->currencies[$_SESSION['currency']]['symbol_right']);
define ('PL_LANG_ID', (int)$_SESSION['languages_id']);
// Initialize flags by default inactive categories and products are not shown
if (PL_SHOW_INACTIVE == 'true') {
    define ('PL_SHOW_CAT_INACTIVE', '');
    define ('PL_SHOW_PROD_INACTIVE', '');
} else {
    define ('PL_SHOW_CAT_INACTIVE', ' and c.categories_status = 1 ');
    define ('PL_SHOW_PROD_INACTIVE', ' and p.products_status = 1 ');
}

/* begin get data from database */
// get categories
$cats = array();
//categories_id language_id categories_name categories_description
if(PL_CATEGORY_TREE_MAIN_CATS_ONLY == 'true'){
  //$query = 'SELECT * FROM ' . TABLE_CATEGORIES . ' c LEFT JOIN ' . TABLE_CATEGORIES_DESCRIPTION . ' cd USING(categories_id) WHERE cd.language_id = "' . PL_LANG_ID . '"' . PL_SHOW_CAT_INACTIVE . ' ORDER BY sort_order, categories_name'; 
  //  xxx ?
  $query = 'SELECT c.parent_id, cd.categories_id, cd.language_id, cd.categories_name FROM ' . TABLE_CATEGORIES . ' c LEFT JOIN ' . TABLE_CATEGORIES_DESCRIPTION . ' cd USING(categories_id) WHERE cd.language_id = "' . PL_LANG_ID . '"' . PL_SHOW_CAT_INACTIVE . ' ORDER BY sort_order, categories_name';   

}else{
  $query = 'SELECT cd.categories_id, cd.language_id, cd.categories_name FROM ' . TABLE_CATEGORIES . ' c LEFT JOIN ' . TABLE_CATEGORIES_DESCRIPTION . ' cd USING(categories_id) WHERE cd.language_id = "' . PL_LANG_ID . '"' . PL_SHOW_CAT_INACTIVE . ' ORDER BY sort_order, categories_name';   
}
$result = mysql_query($query, $db->link) or die(mysql_error());

while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    if ((($line['categories_id'] == (int)$_SESSION['pl_category']) || ($line['parent_id'] != 0)) || (((int)$_SESSION['pl_category'] == 0) && (PL_DEFAULT_SHOW_ALL_CATS == 'true'))) {
        $cats[$line['categories_id']] = $line;
    }
}
mysql_free_result($result);

// get manufacturer_name
$manufacturers_name = array();
if (PL_SHOW_MANUFACTURER == 'true')
{
  $sql = "SELECT m.manufacturers_id, m.manufacturers_name FROM " . TABLE_MANUFACTURERS . " m, " . TABLE_PRODUCTS . " p WHERE m.manufacturers_id = p.manufacturers_id";
  //$result = mysql_query($sql, $db->link) or die(mysql_error());
  $result = $db->Execute($sql);
  /*
  while ($row = mysql_fetch_array($result)) {
      $manufacturers_name[$row['manufacturers_id']] = $row['manufacturers_name'];
  }
  mysql_free_result($result);
  */
  while (!$result->EOF) {
    $manufacturers_name[$result->fields['manufacturers_id']] = $result->fields['manufacturers_name'];
    $result->MoveNext(); 
  }
}
/* end get data from database */

/* prepare tables */
$productCount = 0;
if(pl_group_is_valid(PL_PROFILE)){
  $tableArray = pl_print_subcats($cats);
}
if (!(empty($tableArray)))
{
  /* add table and tr tags */
  $tableArray = add_table_tags ($tableArray);

  /* create columns, wrappertable start and end tags are added later at "print the pricelist" */
  $columnArray = create_columns ($tableArray);
  // count the number of pages
  define('PL_PAGES', count($columnArray));
}

/* begin functions */

function pl_display_price($price_raw, $tax = 0){
  global $currencies;
  // display price without symbol left or right
  $price = $currencies->display_price($price_raw, $tax);
  $price = str_replace($currencies->currencies[$_SESSION['currency']]['symbol_left'], '', $price);
  $price = str_replace($currencies->currencies[$_SESSION['currency']]['symbol_right'], '', $price);          
  
  return $price;
}
function pl_group_is_valid($profile){
  eval('$group_name = PL_GROUP_NAME_' . $profile . ';');
  eval('$group_name_defined = defined(\'PL_GROUP_NAME_' . $profile . '\');');
  
  if((!$group_name_defined)||($group_name == '')){  
    return true;
  }else{
    // if a group name is defined, we check if the customer is allowed to view this pricelist profile
    return zen_group_is_valid($group_name);
  }
  
}
// profiles switch
function pl_get_profiles ($current_profile)
{

    $profiles_list = '<ul>' . "\n";
    $k = 0;
    for($profile = 1; $profile <= 10; $profile++) {
        $enabled = 'false';
                     
        eval('$enabled = PL_ENABLE_' . $profile . ';');
        eval('$name = PL_PROFILE_NAME_' . $profile . ';');
        if(!pl_group_is_valid($profile)){
          // hide links to profiles the customer is not allowed to view anyway
          $enabled = 'false';
        }
        
        if ($enabled == 'true') {
            $k++;
            if ($current_profile == $profile) $selected = ' class="selectedPL"';
            else $selected = '';
            $profiles_list .= '<li' . $selected . '><a href="' . zen_href_link(FILENAME_PRICELIST, 'profile=' . $profile) . '">' . $name . '</a></li>' . "\n";
        }
    }
    $profiles_list .= '</ul>' . "\n";
    if (($k > 1)||(!pl_group_is_valid($current_profile)&&($k > 0))) {
        return $profiles_list;
    } else { // return empty string if there's only one profile
        return '';
    }
}
// adapted version of zen_get_category_tree() function (from zen admin)
function pl_zen_get_category_tree($parent_id = '0', $spacing = '', $exclude = '', $category_tree_array = '', $include_itself = false, $main_cats_only = false)
{
    global $db;
    if (!is_array($category_tree_array)) $category_tree_array = array();
    if ((sizeof($category_tree_array) < 1) && ($exclude != '0')) $category_tree_array[] = array('id' => '0', 'text' => TEXT_PL_CATEGORIES);

    if ($include_itself) {
        $category = $db->Execute("select cd.categories_name
                                from " . TABLE_CATEGORIES_DESCRIPTION . " cd
                                where cd.language_id = '" . (int)$_SESSION['languages_id'] . "'
                                and cd.categories_id = '" . (int)$parent_id . "'");

        $category_tree_array[] = array('id' => $parent_id, 'text' => $category->fields['categories_name']);
    }
// c.categories_status= '1' thnx to pixxi see: http://www.zen-cart.com/modules/ipb/index.php?showtopic=5405&st=255
    $categories = $db->Execute("select c.categories_id, cd.categories_name, c.parent_id
                                from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd
                                where c.categories_id = cd.categories_id
                                and cd.language_id = '" . (int)$_SESSION['languages_id'] . "'
                                and c.parent_id = '" . (int)$parent_id . "'
                                and c.categories_status= '1'
                                order by c.sort_order, cd.categories_name");

    while (!$categories->EOF) {
        if ($exclude != $categories->fields['categories_id']) $category_tree_array[] = array('id' => $categories->fields['categories_id'], 'text' => $spacing . $categories->fields['categories_name']);
        // if ($main_cats_only == false) { added for price-list (since selecting subcats does not work yet)
        if ($main_cats_only == false) {
            $category_tree_array = pl_zen_get_category_tree($categories->fields['categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $category_tree_array);
        }

        $categories->MoveNext();
    }

    return $category_tree_array;
}
// Return a product's special price expiration date (returns nothing if there is no offer)
// TABLES: products
function pl_get_products_special_date($product_id){
    //PL_SHOW_SPECIAL_DATE
    // note that zen_get_products_special_price() by default also looks pricing by attributes and other discounts
    // for those features the date returned by this function probably is invalid
    global $db;
    $specials = $db->Execute("select expires_date from " . TABLE_SPECIALS . " where products_id = '" . $product_id . "'"); //  and status ?
    $special_date = (($specials->fields['expires_date'] != '0000-00-00 00:00:00' and $specials->fields['expires_date'] != '' and $specials->fields['expires_date'] != '0001-01-01') ? zen_date_short($specials->fields['expires_date']) : false);
    return $special_date;
}

/* get products from db per category */
function pl_get_products_per_cat($cats, $id)
{
    global $productCount, $db;
    // get products
    // following fields are returned with (or were, a long time ago) select *: products_id  products_quantity  products_model  products_image  products_price  products_date_added  products_last_modified  products_date_available  products_weight products_status products_tax_class_id manufacturers_id products_ordered products_bundle language_id products_name products_description products_url products_viewed categories_id categories_image parent_id sort_order date_added last_modified categories_status
    // make query dependant of profile settings to save memory usage? (So only add required fields to query)
// stock by bmoroney
    //$query = 'SELECT p.products_id, p.products_quantity, p.products_model, p.products_price, p.products_status, p.products_tax_class_id, p.manufacturers_id, pd.products_name, pc.categories_id, p.products_weight ';
    $query = 'SELECT *';
    if(PL_USE_MASTER_CATS_ONLY == 'true'){
      // list each product only under it's master category (master_categories_id)
      $query .= ' FROM ' . TABLE_PRODUCTS . ' p LEFT JOIN ' . TABLE_PRODUCTS_DESCRIPTION . ' pd USING(products_id) LEFT JOIN ' . TABLE_PRODUCTS_TO_CATEGORIES . ' pc USING(products_id) LEFT JOIN ' . TABLE_CATEGORIES . ' c USING(categories_id) WHERE pd.language_id="' . PL_LANG_ID . '" AND p.master_categories_id="' . $id . '"' . PL_SHOW_PROD_INACTIVE . PL_SHOW_CAT_INACTIVE;
    }else{    
      // list product under all linked categories (which normally includes the master)
      $query .= ' FROM ' . TABLE_PRODUCTS . ' p LEFT JOIN ' . TABLE_PRODUCTS_DESCRIPTION . ' pd USING(products_id) LEFT JOIN ' . TABLE_PRODUCTS_TO_CATEGORIES . ' pc USING(products_id) LEFT JOIN ' . TABLE_CATEGORIES . ' c USING(categories_id) WHERE pd.language_id="' . PL_LANG_ID . '" AND c.categories_id="' . $id . '"' . PL_SHOW_PROD_INACTIVE . PL_SHOW_CAT_INACTIVE;
    }
    $query .= PL_EXTRA_CONDITION . ' ORDER BY ' . PL_SORT_PRODUCTS  . ' ' . PL_SORT_ASC_DESC; // bugfix: changed LP_SORT_PRODUCTS_BY by LP_SORT_PRODUCTS !

    $result = mysql_query($query, $db->link) or die(mysql_error());
    // $productCount += mysql_num_rows($result);
    while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
        // filter by selected manufacturers if any
        /*
        if (($action != 'printthis') ||
                (($action == 'printthis') &&
                    (($_GET['man_' . $line['manufacturers_id']] == 'on') ||
                        ($_GET['man_all'] == 'on')
                        )
                    )
                )
                */
        { // if (($line['categories_id'] == $category) || ($line['parent_id'] != 0))
            $cats[$line['categories_id']][++$cats[$line['categories_id']][cn]] = $line;
            $productCount++;
        }
    }
    mysql_free_result($result);

    return $cats;
}
/* end of get products from db per category */

/* begin calculate $tableArray */
function pl_print_subcats ($cats, $level = 0, $parent = 0)
{
    // static setting needed for recurse pl_print_subcats
    static $tableArray;
    static $printedLines;
    static $tableNr, $mainCat;
    global $extraLine; // hack 1/5 to correct number of lines for specials, descriptions and images
    // global $currentCat; // pm hack to not start a new table for every maincat :(
    foreach ($cats as $key => $value) {
        if ($value['parent_id'] == $parent) {
            if ($level == 0) { // main categories
                    if ((PL_MAINCATS_NEW_TABLE == 'true') | (PL_MAINCATS_NEW_PAGE == 'true')) {
                        // "normal" function: maincat always starts new table
                        $mainCat = show_main_category($cats, $key, $level);
                        $tableNr = 0;
                        $printedLines = 1;
                        $tableNr++;
                    } else {
                        // start new mainCat without starting new table (1/2) (hack)
                        // $currentCat = '??'; // "mainCat =" always starts a new table currentCat does not work yet
                        if ($printedLines >= PL_MAXLINES -1) { // -1 prevents separation of header and products
                                $tableNr++;
                            $printedLines = 1;
                        }
                        $tableArray[$mainCat][$tableNr] .= show_category($cats, $key, $level);
                        $printedLines++;
                    }
                } else { // subcategories
                        if ($printedLines >= PL_MAXLINES -1) { // -1 prevents separation of header and products
                                $tableNr++;
                            $printedLines = 1;
                        }
                        $tableArray[$mainCat][$tableNr] .= show_category($cats, $key, $level);
                        $printedLines++;
                    }
                    // print products (switched place with // recurse subcats 2004/06/03)
                    $cats = pl_get_products_per_cat($cats, $key);

                    for($k = 1; $k <= $cats[$key][cn]; $k++) {
                        if ($printedLines >= PL_MAXLINES) {
                            $tableNr++;
                            $printedLines = 1;
                        }
                        $tableArray[$mainCat][$tableNr] .= show_product($cats, $key, $k, $printedLines);
                        $printedLines++;
                        $printedLines = $printedLines + $extraLine; // hack 2/5 to correct number of lines for specials, descriptions and images
                    }
                    // recurse subcats
                    pl_print_subcats ($cats, $level + 1, $key);
                }
            }
            return $tableArray;
}

function add_table_tags ($tableArray)
{
    while (list($mainCat, $tables) = each($tableArray)) {
        // $columns = 0;
        while (list($key, $table) = each($tables)) {
            //echo count($tables); // returns nr of tables for each cat
            // bof start_table($mainCat)
            $newTableArray[$mainCat][$key] .= "\n" . '<table class="colPL" summary="' . TEXT_PL_HEADER_TITLE . '">' . "\n";
            $newTableArray[$mainCat][$key] .= columns_header ($mainCat);           
            // eof start_table($mainCat)
            
            $newTableArray[$mainCat][$key] .= $table;
            //stop_table();
            $newTableArray[$mainCat][$key] .= '</table>' . "\n";
        }
    }

    return($newTableArray);
}
function start_table($mainCat)
{
    $tableStart = "\n" . '<table class="colPL" summary="' . TEXT_PL_HEADER_TITLE . '">' . "\n";
    $columnsHeader = columns_header ($mainCat);
    $tableArray = $tableStart . $columnsHeader;
    return $tableArray;
}
function stop_table()
{
    $tableEnd = '</table>' . "\n";
    return $tableEnd;
}

function columns_header ($mainCat)
{
    // echo the maincat inside the table i.s.o. above the each page (currently not possible if maincats don't start new tables)
    // (PL_MAINCATS_NEW_TABLE == 'false') added for: start new mainCat without starting new table (2/2) (hack)
    if ((PL_MAINCATS_NEW_PAGE == 'false') && (PL_MAINCATS_NEW_TABLE == 'true')) $columnsHeader = '<tr>' . "\n" . '<th class="tmcPL" colspan="' . PL_HEADER_COLUMNS_COUNT . '">' . $mainCat . '</th></tr>' . "\n";
    $columnsHeader .= '<tr class="colhPL">' . "\n" . '<td class="prdPL">' . TABLE_HEADING_PRODUCTS . '</td>' . "\n";
    if (PL_SHOW_MODEL == 'true') {
        $columnsHeader .= '<td class="modPL"><div>' . TABLE_HEADING_MODEL . '</div></td>' . "\n";
    }
    if (PL_SHOW_MANUFACTURER == 'true') {
        $columnsHeader .= '<td class="manPL"><div>' . TABLE_HEADING_MANUFACTURER . '</div></td>' . "\n";
    }
    if (PL_SHOW_WEIGHT == 'true') {
        $columnsHeader .= '<td class="wgtPL"><div>' . TABLE_HEADING_WEIGHT . ' (' . TEXT_SHIPPING_WEIGHT . ')</div></td>' . "\n";
    }
// stock by bmoroney
    if (PL_SHOW_SOH == 'true') {
        $columnsHeader .= '<td class="sohPL"><div>' . TABLE_HEADING_SOH . '</div></td>' . "\n";
    }

    if (PL_SHOW_NOTES_A == 'true') {
        $columnsHeader .= '<td class="ntsPL"><div>' . TABLE_HEADING_NOTES_A . '</div></td>' . "\n";
    }
    if (PL_SHOW_NOTES_B == 'true') {
        $columnsHeader .= '<td class="ntsPL"><div>' . TABLE_HEADING_NOTES_B . '</div></td>' . "\n";
    }
    if (PL_SHOW_PRICE == 'true') {
        $columnsHeader .= '<td class="prcPL">' . TABLE_HEADING_PRICE_INC . PL_CURR_SYMBOL . '</td>' . "\n";
    }
    if (PL_SHOW_TAX_FREE == 'true') {
        $columnsHeader .= '<td class="prcPL">' . TABLE_HEADING_PRICE_EX . PL_CURR_SYMBOL . '</td>' . "\n";
    }
    
//Added by Vartan Kat on july 2007 for Add to cart button
    if (PL_SHOW_ADDTOCART_BUTTON == 'true') {
        $columnsHeader .= '<td>'. TABLE_HEADING_ADDTOCART . '</td>' . "\n";
    }
//End of Added by Vartan Kat on july 2007 for Add to cart button

    return $columnsHeader;
}

function show_main_category ($cats, $index, $level)
{
    $mainCat = $cats[$index]['categories_name'];
    return $mainCat;
}
function show_category ($cats, $index, $level)
{
    $catRow = '<tr class="scPL-' . $level . '">' . "\n" . '<th colspan="' . PL_HEADER_COLUMNS_COUNT . '">' . $cats[$index]['categories_name'] . '</th>' . "\n" . '</tr>' . "\n";
    return $catRow;
}

function show_product ($cats, $cat_index, $prod_index)
{
    global $manufacturers_name;
    //global $currencies;
    global $extraLine; // hack 3/5 to correct number of lines for specials, descriptions and images
    $products_id = $cats[$cat_index][$prod_index]['products_id'];

    $products_price_inc = pl_display_price($cats[$cat_index][$prod_index]['products_price'], zen_get_tax_rate($cats[$cat_index][$prod_index]['products_tax_class_id']));
    $products_price_ex = pl_display_price($cats[$cat_index][$prod_index]['products_price']);
    // $specials_price_only=false multiplies the number of queries per product!!
    //function zen_get_products_special_price($product_id, $specials_price_only=false)
    if(PL_SHOW_SPECIAL_PRICE == 'true'){
      $special_price_ex = zen_get_products_special_price($products_id, true);
    }
    if (zen_not_null($special_price_ex)) {
        $special_price_inc = pl_display_price($special_price_ex, zen_get_tax_rate($cats[$cat_index][$prod_index]['products_tax_class_id']));
        $special_price_ex = pl_display_price($special_price_ex);
        if(PL_SHOW_SPECIAL_DATE == 'true'){
          $special_date = pl_get_products_special_date($products_id);
        }else{
          $special_date = false;
        }
    }
    if ((PL_SHOW_INACTIVE == 'true') AND (($cats[$cat_index][$prod_index]['products_status'] == "0")
                OR ($cats[$cat_index]['categories_status'] == "0")
                )
            ) {
        $prodRow = '<tr class="inactivePL">' . "\n";
        $prodRow .= '<td class="prdPL"><div>' . $cats[$cat_index][$prod_index]['products_name'] . '</div></td>' . "\n";
    } else {
        //added to get product type handler jph
        $handler_page = zen_get_info_page($products_id);
        $prodRow = '<tr>' . "\n";
        //added handler and target jph
        $prodRow .= '<td class="prdPL"><div><a href="' . zen_href_link($handler_page, 'products_id=' . $products_id) . '" target="_blank">' . $cats[$cat_index][$prod_index]['products_name'] . '</a></div></td>' . "\n";

    }

    
    if (PL_SHOW_MODEL == 'true') {
        $prodRow .= '<td class="modPL"><div>' . $cats[$cat_index][$prod_index]['products_model'] . '&nbsp;</div></td>' . "\n";
    }
    if (PL_SHOW_MANUFACTURER == 'true') {
        $prodRow .= '<td class="manPL"><div>' . $manufacturers_name[$cats[$cat_index][$prod_index]['manufacturers_id']] . '&nbsp;</div></td>' . "\n";
    }
    if (PL_SHOW_WEIGHT == 'true') {
        $prodRow .= '<td class="wgtPL"><div>' . $cats[$cat_index][$prod_index]['products_weight'] . '&nbsp;</div></td>' . "\n";
    }
    if (PL_SHOW_NOTES_A == 'true') {
        $prodRow .= '<td class="ntsaPL">&nbsp;</td>' . "\n";
    }
    if (PL_SHOW_NOTES_B == 'true') {
        $prodRow .= '<td class="ntsbPL">&nbsp;</td>' . "\n";
    }
// stock by bmoroney
    if (PL_SHOW_SOH == 'true') {
        $prodRow .= '<td class="sohPL"><div>' . $cats[$cat_index][$prod_index]['products_quantity'] . '&nbsp;</div></td>' . "\n";
    }

    if ($special_price_ex > 0) {
        $price_class = 'prcPL notSplPL';
    } else {
        $price_class = 'prcPL';
    }
    if (PL_SHOW_PRICE == 'true') {    
        $prodRow .= '<td class="' . $price_class . '">' . $products_price_inc . '</td>' . "\n";
    }
    if (PL_SHOW_TAX_FREE == 'true') {
        $prodRow .= '<td class="' . $price_class . '">' . $products_price_ex . '</td>' . "\n";
    }
    
    
//Added by Vartan Kat on july 2007 for Add to cart button
    if (PL_SHOW_ADDTOCART_BUTTON == 'true') {
         if (PL_ONLY_ADDTOCART_BUTTON == 'true') {
    $prodRow .='<td>' . $display_qty . zen_draw_form('cart_quantity', zen_href_link(zen_get_info_page($products_id), zen_get_all_get_params(array('action')) . 'action=add_product'), 'post', 'enctype="multipart/form-data" target="' . PL_ADDTOCART_TARGET . '" class="AddButtonBox"') . "\n" . $the_button = PRODUCTS_ORDER_QTY_TEXT . '<input type="text" name="cart_quantity" value="' . (zen_get_buy_now_qty($products_id)) . '" maxlength="6" size="4" /><br />' . zen_get_products_quantity_min_units_display((int)$products_id) . '<br />' . zen_draw_hidden_field('products_id', (int)$products_id) . zen_image_submit(BUTTON_IMAGE_IN_CART, BUTTON_IN_CART_ALT). '</form></td>';
    }else{
            if (zen_has_product_attributes($products_id) ) {
          $prodRow .= '<td><a href="' . zen_href_link(zen_get_info_page($products_id), ($_GET['cPath'] > 0 ? 'cPath=' . $_GET['cPath'] . '&' : '') . 'products_id=' . $products_id) . '" target="' . PL_ADDTOCART_TARGET . '" >' . MORE_INFO_TEXT . '</a></td>';
          }else{

              // show the quantity box
              $prodRow .='<td>' . $display_qty . zen_draw_form('cart_quantity', zen_href_link(zen_get_info_page($products_id), zen_get_all_get_params(array('action')) . 'action=add_product'), 'post', 'enctype="multipart/form-data" target="' . PL_ADDTOCART_TARGET . '" class="AddButtonBox"') . "\n" . $the_button = PRODUCTS_ORDER_QTY_TEXT . '<input type="text" name="cart_quantity" value="' . (zen_get_buy_now_qty($products_id)) . '" maxlength="6" size="4" /><br />' . zen_get_products_quantity_min_units_display((int)$products_id) . '<br />' . zen_draw_hidden_field('products_id', (int)$products_id) . zen_image_submit(BUTTON_IMAGE_IN_CART, BUTTON_IN_CART_ALT). '</form></td>';
                }
                }
}
//End of Added by Vartan Kat on july 2007 for Add to cart button
    $prodRow .= '</tr>' . "\n";

    if ($special_price_ex > 0) {
        $colspan = ((int)PL_HEADER_COLUMNS_COUNT);
        if (PL_SHOW_PRICE == 'true') {
            $colspan--;
        } 
        if (PL_SHOW_TAX_FREE == 'true') {
            $colspan--;
        }
        
        $prodRow .= '<tr>' . "\n" . '<td class="splDatePL" colspan="' . $colspan . '">';
        if ($special_date == false) { 
            // no valid expire date
            $prodRow .= TEXT_PL_SPECIAL;
        } else {
            $prodRow .= TEXT_PL_AVAIL_TILL . $special_date;
        }
        $prodRow .= '</td>' . "\n";
        
        if (PL_SHOW_PRICE == 'true') {
            $prodRow .= '<td class="splPL">' . $special_price_inc . '</td>' . "\n";
        }
        if (PL_SHOW_TAX_FREE == 'true') {
            $prodRow .= '<td class="splPL">' . $special_price_ex . '</td>' . "\n";
        }
        $prodRow .= '</tr>' . "\n";
        $extraLine = 1; // hack 4/5 to correct number of lines for specials, descriptions and images
    } else {
        $extraLine = 0; // hack 5/5 to correct number of lines for specials, descriptions and images
    }
    
    if((PL_SHOW_IMAGE == 'true')||(PL_SHOW_DESCRIPTION == 'true')){
      $prodRow .= '<tr><td class="imgDescrPL" colspan = "'. (int)PL_HEADER_COLUMNS_COUNT . '">' . "\n" ;
      // add random class for nicer catalog images display
      $pl_random = rand(1, 4);
      // adding div wrapper for easier oferflow etc
      $prodRow .= '<div class="imgDescrRndPL_' . $pl_random . '">';

      if(PL_SHOW_IMAGE == 'true'){
        $prodRow .= zen_image(DIR_WS_IMAGES . $cats[$cat_index][$prod_index]['products_image'], '', PL_IMAGE_PRODUCT_WIDTH, PL_IMAGE_PRODUCT_HEIGHT, 'class="imgPL"');
      }
      if(PL_SHOW_DESCRIPTION == 'true'){
        
        if ((int)PL_TRUNCATE_DESCRIPTION > 0) {
          $disp_text = zen_clean_html($cats[$cat_index][$prod_index]['products_description']);
          $prodRow .= stripslashes(zen_trunc_string($disp_text, (int)PL_TRUNCATE_DESCRIPTION, '<a href="' . zen_href_link(zen_get_info_page($cats[$cat_index][$prod_index]['products_id']), 'products_id=' . $cats[$cat_index][$prod_index]['products_id']) . '"> ' . MORE_INFO_TEXT . '</a>'));
        }else{
          $prodRow .= $cats[$cat_index][$prod_index]['products_description'];
        }
      }
      $prodRow .= '</div>';
      $prodRow .= '</td></tr>' . "\n";
      $extraLine = $extraLine + (int)PL_IMGDESC_EXTRALINES;
    }
    
    $tableArray = $prodRow;
    return $tableArray;
}
/* end calculate $tableArray */
/* end pl_print_subcats functions */

/* begin calculate $columnArray */
function create_columns ($tableArray)
{
    while (list($mainCat, $tables) = each($tableArray)) {
        if (PL_MAINCATS_NEW_PAGE == 'true') $column = 0; // set columns to 0: if every maincat starts a new page)
        while (list($key, $table) = each($tables)) {
            // echo '<br>' . count($tables);
            if ($column >= PL_MAXCOLUMNS) {
                // start a new page if max number of columns is reached
                $page++;
                $column = 0;
            }
            $columnArray[$page]['cat'] = $mainCat;
            $columnArray[$page]['table'] .= '<td>' . $table . '</td>' . "\n";
            // $columnArray[$page]['table'] .= $table . "\n";
            $column++;
            $columnArray[$page]['column'] = $column; // save the number of columns on this page
            // echo '>' . $page . '=' . $column;
        }
        if (PL_MAINCATS_NEW_PAGE == 'true') $page++; // start a new page for every maincat
    }
    return($columnArray);
}     
/* end functions */
?>