<?php
/*
  $Id: xsell_products.php,v 6.5.4 2017/12/17 01:41:11 datazen Exp $

  CRE Loaded, Open Source E-Commerce Solutions
  http://www.loadedcommerce.com

  Copyright (c) 2017 Loaded Commerce
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/

require('includes/application_top.php');
require(DIR_WS_CLASSES . 'currencies.php');
require(DIR_WS_CLASSES . 'Product.class.php');
$currencies = new currencies();

if (isset($_POST['page'])) {
  $page = $_POST['page'] ;
} else if (isset($_GET['page'])) {
  $page = $_GET['page'] ;
} else {
  $page = 1;
}

if (isset($_POST['action'])) {
  $action = $_POST['action'] ;
} else if (isset($_GET['action'])) {
  $action = $_GET['action'] ;
} else {
  $action = '' ;
}

switch($action){
  case 'update_cross' :
    if (isset($_POST['product'])) {
      foreach ($_POST['product'] as $temp_prod){
        tep_db_query('delete from ' . TABLE_PRODUCTS_XSELL . ' where xsell_id = "'.$temp_prod.'" and products_id = "'.$_GET['add_related_product_ID'].'"');
      }
    }
    $sort_start_query = tep_db_query('select sort_order from ' . TABLE_PRODUCTS_XSELL . ' where products_id = "'.$_GET['add_related_product_ID'].'" order by sort_order desc limit 1');
    $sort_start = tep_db_fetch_array($sort_start_query);
    $sort = (($sort_start['sort_order'] > 0) ? $sort_start['sort_order'] : '0');
    if (isset($_POST['cross'])) {
      foreach ($_POST['cross'] as $temp){
        $sort++;
        $insert_array = array();
        $insert_array = array('products_id' => $_GET['add_related_product_ID'],
                              'xsell_id' => $temp,
                              'sort_order' => $sort);
        tep_db_perform(TABLE_PRODUCTS_XSELL, $insert_array);
      }
    }
    $messageStack->add('xsell', sprintf(CROSS_SELL_SUCCESS, Product::getProductName($_GET['add_related_product_ID'], $languages_id)), 'success');
    break;
}

include(DIR_WS_INCLUDES . 'html_top.php');
include(DIR_WS_INCLUDES . 'header.php');
include(DIR_WS_INCLUDES . 'column_left.php');

function getXSellProducts($products_id) {
  global $languages_id;

  $products_cross_query = tep_db_query('SELECT p.products_id, p.products_model, pd.products_name, p.products_id, x.products_id, x.xsell_id, x.sort_order, x.ID
                                          from '.TABLE_PRODUCTS.' p, '.TABLE_PRODUCTS_DESCRIPTION.' pd, '.TABLE_PRODUCTS_XSELL.' x WHERE x.xsell_id = p.products_id and x.products_id = "' . $products_id . '" and p.products_id = pd.products_id and pd.language_id = "' . (int)$languages_id . '" order by x.sort_order asc');

  $result = array();
  while ($products_cross = tep_db_fetch_array($products_cross_query)) {
    $result[] = $products_cross;
  }

  return $result;
}
?>
<div id="content" class="content p-relative">
  <h1 class="page-header"><i class="fa fa-laptop"></i> <?php echo HEADING_TITLE; ?></h1>

  <?php if (file_exists(DIR_WS_INCLUDES . 'toolbar.php')) include(DIR_WS_INCLUDES . 'toolbar.php'); ?>

  <div class="col">
    <!-- begin panel -->
    <?php
    if ($messageStack->size('xsell') > 0) {
      echo $messageStack->output('xsell');
    }
    ?>
    <div id="alert-xsell" class="row" style="display:none;"><div class="col p-0 mt-0 mb-3"><div class="note note-info m-0"><h4 class="m-0"><?php echo TEXT_SETTING_SELLS; ?>&nbsp;<span class="alert-xsell-name fw-600"></span></h4></div></div></div>
    <div class="dark">
      <!-- body_text //-->
      <div id="table-languages" class="table-languages">
        <div class="row">
          <div class="col-md-9 col-xl-10 dark panel-left rounded-left">

            <?php
            if (!isset($_GET['add_related_product_ID']) || $_GET['add_related_product_ID'] == '') {
              ?>
              <table class="table table-hover w-100 mt-2">
                <thead>
                  <tr class="th-row">
                    <th scope="col" class="th-col dark text-left"><?php echo TABLE_HEADING_PRODUCT_NAME; ?></th>
                    <th scope="col" class="th-col dark text-left d-none d-lg-table-cell col-blank"><?php echo TABLE_HEADING_PRODUCT_MODEL; ?></th>
                    <th scope="col" class="th-col dark text-center"><?php echo TABLE_HEADING_CROSS_SELLS; ?></th>
                    <th scope="col" class="th-col dark text-right"><?php echo TABLE_HEADING_ACTION; ?></th>
                  </tr>
                </thead>
                <tbody>
                <?php
                if (isset($_POST['search'])) {
                  $search = str_replace("'", "&#39", tep_db_prepare_input($_POST['search']));
                  $products_query_raw = "SELECT p.products_id,
                                                p.products_model,
                                                p.products_image,
                                                pd.products_name,
                                                p.products_id
                                           FROM " . TABLE_PRODUCTS . " p,
                                                " . TABLE_PRODUCTS_DESCRIPTION . " pd
                                          WHERE p.products_id = pd.products_id
                                            and (pd.products_name like '%" . tep_db_input($search) . "%' or p.products_model like '%" . tep_db_input($search) . "%')
                                            and pd.language_id = '" . (int)$languages_id . "'
                                       ORDER BY p.products_model, pd.products_name ASC";
                } else {
                  $products_query_raw = 'select p.products_id, p.products_model, p.products_image, pd.products_name, p.products_id from ' . TABLE_PRODUCTS . ' p, ' . TABLE_PRODUCTS_DESCRIPTION . ' pd where p.products_id = pd.products_id and pd.language_id = "' . (int)$languages_id . '" order by p.products_id asc';
                }
                $products_split = new splitPageResults($page, MAX_DISPLAY_SEARCH_RESULTS, $products_query_raw, $products_query_numrows);
                $products_query = tep_db_query($products_query_raw);
                while ($products = tep_db_fetch_array($products_query)) {

                  if ( ((!isset($_GET['pID'])) || ($_GET['pID'] == $products['products_id'])) && (!isset($pInfo)) ) {
                    $pInfo = new objectInfo($products);
                  }

                  $selected = (isset($pInfo) && (is_object($pInfo)) && ($products['products_id'] == $pInfo->products_id)) ? ' selected' : '';
                  if ($selected) {
                    echo '<tr class="table-row dark selected" onclick="document.location.href=\'' . tep_href_link(FILENAME_XSELL_PRODUCTS, 'page=' . $page . '&add_related_product_ID=' . $pInfo->products_id . '&action=edit') . '\'">' . "\n";
                  } else {
                    echo '<tr class="table-row dark" onclick="document.location.href=\'' . tep_href_link(FILENAME_XSELL_PRODUCTS, 'page=' . $page . '&pID=' . $products['products_id']) . '\'">' . "\n";
                  }
                  $col_selected = ($selected) ? ' selected' : '';
                  ?>

                  <td class="table-col dark text-left<?php echo $col_selected; ?>"><?php echo $products['products_name']; ?></td>
                  <td class="table-col dark text-left<?php echo $col_selected; ?> d-none d-lg-table-cell col-blank"><?php echo $products['products_model']; ?></td>

                  <td class="table-col dark text-center<?php echo $col_selected; ?>">
                    <?php
                    $cnt = count(getXSellProducts($products['products_id']));
                    if ($cnt > 0) {
                      echo '<span class="badge badge-success">' . $cnt . '</span>';
                    } else {
                      echo '<span class="badge badge-secondary">0</span>';
                    }
                    ?>
                  </td>

                  <!--td class="table-col dark text-center<?php echo $col_selected; ?>"><a href="<?php echo tep_href_link(FILENAME_XSELL_PRODUCTS, tep_get_all_get_params(array('action')) . 'add_related_product_ID=' . $products['products_id'], 'NONSSL');?>"><?php echo TEXT_EDIT_SELLS;?></a>&nbsp;</td>
                  <td class="table-col dark text-center<?php echo $col_selected; ?>"><?php echo (($i > 0) ? '<a href="' . tep_href_link(FILENAME_XSELL_PRODUCTS, tep_get_all_get_params(array('action')) . 'sort=1&add_related_product_ID=' . $products['products_id'], 'NONSSL') .'">'.TEXT_SORT.'</a>&nbsp;' : '--')?></td -->

                  <td class="table-col dark text-right<?php echo $col_selected; ?>">
                    <?php echo ($selected) ? '<i class="fa fa-long-arrow-right fa-lg text-success"></i>' : '<a href="' . tep_href_link(FILENAME_XSELL_PRODUCTS, 'page=' . $_GET['page'] . '&pID=' . $products['products_id']) . '"><i class="fa fa-info-circle fa-lg text-muted"></i></a>'; ?>
                  </td>
                  </tr>
                  <?php /*
                  if ($cnt > 0) {
                    ?>
                    <tr>
                      <td style="display:none;" id="xs-<?php echo $products['products_id']; ?>" colspan="4">TEST</td>
                    </tr>
                    <?php
                  } */

                }
                ?>

                </tbody>
              </table>

              <div class="pagination-container ml-2 mr-2 mb-4">
                <div class="results-right mt-2"><?php echo $products_split->display_count($products_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $page, TEXT_DISPLAY_NUMBER_OF_PRODUCTS); ?></div>
                <div class="results-left"><?php echo $products_split->display_links($products_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $page); ?></div>
              </div>

              <?php
            } elseif ( (isset($_GET['add_related_product_ID']) && $_GET['add_related_product_ID'] != '') && (!isset($_GET['sort']) || $_GET['sort'] == '') ){
              $products_name_query = tep_db_query('select pd.products_name, p.products_model, p.products_image from '.TABLE_PRODUCTS.' p, '.TABLE_PRODUCTS_DESCRIPTION.' pd where p.products_id = "'.$_GET['add_related_product_ID'].'" and p.products_id = pd.products_id and pd.language_id ="'.(int)$languages_id.'"');
              $products_name = tep_db_fetch_array($products_name_query);

              echo tep_draw_form('update_cross', FILENAME_XSELL_PRODUCTS, tep_get_all_get_params(array('action')) . 'action=update_cross', 'post');
              ?>
              <table class="table table-hover w-100 mt-2">
                <thead>
                  <tr class="th-row">
                    <th scope="col" class="th-col dark text-left"><?php echo TABLE_HEADING_PRODUCT_NAME . '/' . TABLE_HEADING_PRODUCT_MODEL; ?></th>
                    <th scope="col" class="th-col dark text-left d-none d-lg-table-cell col-blank"><?php echo TABLE_HEADING_PRODUCT_IMAGE; ?></th>
                    <th scope="col" class="th-col dark text-center"><?php echo TABLE_HEADING_CROSS_SELL_THIS; ?></th>
                    <th scope="col" class="th-col dark text-left"><?php echo TABLE_HEADING_PRODUCT_PRICE; ?></th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $products_query_raw = 'select p.products_id, p.products_model, p.products_image, p.products_price, pd.products_name, p.products_id from '.TABLE_PRODUCTS.' p, '.TABLE_PRODUCTS_DESCRIPTION.' pd where p.products_id = pd.products_id and pd.language_id = "'.(int)$languages_id.'" order by p.products_id asc';
                  $products_split = new splitPageResults($page, MAX_DISPLAY_SEARCH_RESULTS, $products_query_raw, $products_query_numrows);
                  $products_query = tep_db_query($products_query_raw);

                  while ($products = tep_db_fetch_array($products_query)) {
                    $xsold_query = tep_db_query('select * from ' . TABLE_PRODUCTS_XSELL . ' where products_id = "' . $_GET['add_related_product_ID'] . '" and xsell_id = "'.$products['products_id'].'"');

                    if ($products['products_id'] == $_GET['add_related_product_ID']) continue;

                    ?>
                    <tr class="table-row dark">
                      <td class="table-col dark text-left">&nbsp;<?php echo '<div class="f-w-600">' . $products['products_name'] . '</div><div class="small"><i>' . $products['products_model'];?></i></div></td>
                      <td class="table-col dark text-left d-none d-lg-table-cell col-blank">&nbsp;<?php echo ((is_file(DIR_FS_CATALOG_IMAGES.$products['products_image'])) ?  tep_image(HTTP_SERVER . DIR_WS_CATALOG_IMAGES.$products['products_image'], '', SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT, 'style="height:'.SMALL_IMAGE_WIDTH.'" class="img-responsive"') : '<br>No Image<br>');?>&nbsp;</td>
                      <td class="table-col dark text-center">&nbsp;<?php echo tep_draw_hidden_field('product[]', $products['products_id']) . tep_draw_checkbox_field('cross[]', $products['products_id'], ((tep_db_num_rows($xsold_query) > 0) ? true : false), '', 'class="js-switch" onMouseOver="this.style.cursor=\'hand\'"');?></td>
                      <td class="table-col dark text-left">&nbsp;<?php echo $currencies->format($products['products_price']);?>&nbsp;</td>
                    </tr>
                    <?php
                  }
                  ?>
                </tbody>              </table>

              <div class="pagination-container ml-2 mr-2">
                <div class="results-right mt-2"><?php echo $products_split->display_count($products_query_numrows-1, MAX_DISPLAY_SEARCH_RESULTS, $page, TEXT_DISPLAY_NUMBER_OF_XSELL); ?></div>
                <div class="results-left"><?php echo  $products_split->display_links($products_query_numrows-1, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $page, tep_get_all_get_params(array('page', 'info', 'x', 'y', 'cID', 'action'))); ?></div>
              </div>

              <div class="float-right mr-3 mt-3 mb-3" role="group">
                <button class="btn btn-default btn-sm mr-1" onclick="window.location='<?php echo tep_href_link(FILENAME_XSELL_PRODUCTS); ?>'"><?php echo IMAGE_BACK; ?></button>
                <button class="btn btn-success btn-sm" onclick="document.update_cross.submit();"><?php echo IMAGE_UPDATE; ?></button>
              </div>

              </form>

              <?php
            }
            ?>
			<?php
			  // RCI code start
			  echo $cre_RCI->get('xsell', 'bottom');
			  // RCI code eof
			?>

          </div>
          <div class="col-md-3 col-xl-2 dark panel-right rounded-right">
            <?php
              $heading = array();
              $contents = array();

              if (isset($_GET['add_related_product_ID']) && $_GET['add_related_product_ID'] != '') $action = 'edit';
              // right sidebar logic goes here
              switch ($action) {
                case 'edit':
                  $heading[] = array('text' => '<div class="text-truncate">' . TABLE_HEADING_CURRENT_SELLS . '</div>');
                  $contents[] = array('align' => 'center', 'text' => '<div class="mt-2 mb-2">
                    <button class="btn btn-success btn-sm mt-2 mb-2 btn-update" onclick="document.update_cross.submit();">' . IMAGE_UPDATE . '</button>
                    <button class="btn btn-grey btn-sm mt-2 mb-2 btn-back" onclick="window.location=\'' . tep_href_link(FILENAME_XSELL_PRODUCTS) . '\'">' . IMAGE_BACK . '</button>
                    </div>');

                  $products_cross_image_query = tep_db_query('select p.products_id, p.products_model, p.products_image, p.products_id, x.products_id, x.xsell_id, x.sort_order, x.ID from '.TABLE_PRODUCTS.' p,  '.TABLE_PRODUCTS_XSELL.' x where x.xsell_id = p.products_id and x.products_id = "' . $_GET['add_related_product_ID'] . '" order by x.sort_order asc');
                  while ($products_cross_image = tep_db_fetch_array($products_cross_image_query)){
                    $contents[] = array('align' => 'center', 'text' => '<div class="sidebar-img mt-3 well ml-4 mr-4 mb-1">' . tep_image( DIR_WS_CATALOG_IMAGES . $products_cross_image['products_image'],$products_name['products_name'],SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</div><div class="sidebar-text mt-0 mb-3">' . $products_cross_image['products_model'] . '</div>');
                  }

                  break;

                default:
                  $heading[] = array('text' => '<div class="text-truncate">' . tep_get_products_name($pInfo->products_id, $languages_id) . '</div>');
                  $contents[] = array('text' => '<div class="row"><div class="col p-0 mt-3 ml-2 mr-2"><div class="note note-info m-0"><p class="mb-0 mt-0 f-w-400">' . sprintf(TEXT_INFO_EDIT_XSELL, $pInfo->products_name) . '</p></div></div></div>');
                  $contents[] = array('align' => 'center', 'text' => '<div class="mt-2 mb-2"><button class="btn btn-success btn-sm mt-2 mb-2 btn-edit" onclick="window.location=\'' . tep_href_link(FILENAME_XSELL_PRODUCTS, 'action=edit&add_related_product_ID=' . $pInfo->products_id, 'NONSSL') . '\'">' . IMAGE_EDIT . '</button></div>');
                  $contents[] = array('align' => 'center', 'text' => '<div class="sidebar-img mt-3 well ml-4 mr-4 mb-1">' . tep_info_image($pInfo->products_image, tep_get_products_name($pInfo->products_id, $languages_id), 100, 100) . '</div><div class="sidebar-text mb-0 mt-0">' . $pInfo->products_image . '</div><div class="sidebar-text mt-0 mb-3">(' . SMALL_IMAGE_WIDTH . 'x' . ((SMALL_IMAGE_HEIGHT == '') ? SMALL_IMAGE_WIDTH : SMALL_IMAGE_HEIGHT) . ')</div>');
              }

              // use $box->showSidebar()
              if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
                $box = new box;
                echo $box->showSidebar($heading, $contents);
              }
            ?>
          </div>
        </div>
      </div>
      <!-- end body_text //-->

    </div>
    <!-- end panel -->
  </div>
</div>
<!-- body_eof //-->
<script>
$(document).ready(function(){

  // fade any error messages
  $('#alert-success').delay(6000).fadeOut('slow');

  var action = '<?php echo $action; ?>';

  //  instantiate checkbox switches
  var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
  elems.forEach(function(html) {
    var switchery = new Switchery(html, { size: 'small',
                                          color: '#28a745',
                                          secondaryColor: '#a8acb1' });
  });

  if (action == 'edit') {
    var name = '<?php echo $products_name['products_name']; ?>';
    $('.alert-xsell-name').text(name);
    $('#alert-xsell').show();
  }
});
</script>

<?php
include(DIR_WS_INCLUDES . 'html_bottom.php');
require(DIR_WS_INCLUDES . 'application_bottom.php');
?>
