<?php
/*
  $Id: product_attributes.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');
$languages = tep_get_languages();

$action = (isset($_GET['action']) ? $_GET['action'] : '');
$page_info = '';
if (tep_not_null($action)) {
  switch ($action) {
            case 'add_product_options':
                $options_type = $_POST['options_type'];
                $options_length= (int)$_POST['options_length'];
                $products_options_sort_order = (int)$_POST['products_options_sort_order'];
                tep_db_query("insert into " . TABLE_PRODUCTS_OPTIONS . " (products_options_id, products_options_sort_order, options_type, options_length) values ('" . $_POST['products_options_id'] . "', '" . $products_options_sort_order . "', '" . $options_type . "', '" . $options_length . "')");
                for ($i = 0, $n = sizeof($languages); $i < $n; $i ++) {
                    $language_id = $languages[$i]['id'];
                    $products_options_name = isset($_POST['option_name'][$language_id]) ? $_POST['option_name'][$language_id] : '';
                    $products_options_instruct = isset($_POST['products_options_instruct'][$language_id]) ? $_POST['products_options_instruct'][$language_id] : '';
                    tep_db_query("insert into " . TABLE_PRODUCTS_OPTIONS_TEXT . " (products_options_text_id, products_options_name, language_id, products_options_instruct) values ('" . $_POST['products_options_id'] . "', '" . tep_db_input($products_options_name) . "', '" . $language_id . "', '" . tep_db_input($products_options_instruct) . "')");
                }
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
            case 'add_product_option_values':
                $value_name_array = $_POST['value_name'];
                for ($i = 0, $n = sizeof($languages); $i < $n; $i ++) {
                    $value_name = tep_db_prepare_input($value_name_array[$languages[$i]['id']]);
                    tep_db_query("insert into " . TABLE_PRODUCTS_OPTIONS_VALUES . " (products_options_values_id, language_id, products_options_values_name) values ('" . $_POST['value_id'] . "', '" . $languages[$i]['id'] . "', '" . tep_db_input($value_name) . "')");
                }
                tep_db_query("insert into " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " (products_options_id, products_options_values_id) values ('" . $_POST['option_id'] . "', '" . $_POST['value_id'] . "')");
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
            case 'add_product_attributes':
            	//echo '<pre>'; print_r($_POST);exit;
                $valueprice = str_replace(',','',$_POST['value_price']);
				if (strpos($valueprice, '-') !== false) {
					$_POST['price_prefix'] = '-';
					$_POST['value_price'] = str_replace('-','',$valueprice);
				} else {
					$_POST['price_prefix'] = '+';
					$_POST['value_price'] = str_replace('+','',$valueprice);
				}
                $values_id = isset($_POST['values_id']) ? (int)$_POST['values_id'] : 0;
                $value_price = isset($valueprice) ? (float)$_POST['value_price'] : 0;
                $price_prefix = isset($_POST['price_prefix']) ? $_POST['price_prefix'] : '+';
                $sort_order = isset($_POST['sort_order']) ? (int)$_POST['sort_order'] : 0;
                $option_sort_order = isset($_POST['option_sort_order']) ? (int)$_POST['option_sort_order'] : 0;

                //tep_db_query("insert into " . TABLE_PRODUCTS_ATTRIBUTES . " values ('', '" . (int)$_POST['products_id'] . "', '" . (int)$_POST['options_id'] . "', '" . $values_id . "', '" . $value_price . "', '" . $price_prefix . "', '" . $sort_order . "','')");
				tep_db_query("insert into " . TABLE_PRODUCTS_ATTRIBUTES . " set `products_id` = '" . (int)$_POST['products_id'] . "',  `options_id` = '" . (int)$_POST['options_id'] . "', `options_values_id` = '" . $values_id . "', `options_values_price` = '" . $value_price . "', `price_prefix` = '" . $price_prefix . "', `options_default` = '0', `products_options_sort_order` = '" . $sort_order . "', `main_options_sorting`= '".$option_sort_order."'");
                $products_attributes_id = tep_db_insert_id();
                //add validation
				$typeQry = tep_db_fetch_array(tep_db_query("SELECT `options_type` FROM `products_options` po INNER JOIN `products_options_text` pot WHERE `products_options_id` = '".$_POST['options_id']."' "));
				$typerow = $typeQry['options_type'];
				  if (tep_not_null($typerow)) {
					switch ($typerow) {
						case 0:
						case 5:
						case 6:
							//echo 'select, boolean, datepicker';
							$data = array();
							if($typerow == 0){
								$type = 'select';
							}elseif($typerow == 5){
								$type = 'boolean';
							}elseif($typerow == 6){
								$type = 'datepacker';
							}
							$required = 0;
							if($_POST['mandetory']){
								$required = 1;
							}
							$data = array("type" => $type, "required" => $required);
							$jsondata = json_encode($data);
							$chk = tep_db_query("select id from products_options_validation where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."'");
							if(tep_db_num_rows($chk) > 0){
								$update = tep_db_query("UPDATE products_options_validation set settings = '".$jsondata."' where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."' ");
							}else{
								$insert = tep_db_query("INSERT INTO products_options_validation SET `option_id` = '".(int)$_POST['options_id']."', `products_id` = '".(int)$_POST['products_id']."', settings = '".$jsondata."'");
							}
						break;
						case 1:
							//echo 'textbox';
							$data = array();
							$type = 'textbox';
							$required = 0;
							if($_POST['mandetory']){
								$required = 1;
							}
							$minchar = (int)$_POST['minchar'];
							$maxchar = (int)$_POST['maxchar'];
							$validatetype = $_POST['validation_type'];
							$data = array("type" => $type, "required" => $required, "minchar" => $minchar, "maxchar" => $maxchar, "validatetype" => $validatetype);
							$jsondata = json_encode($data);
							$chk = tep_db_query("select id from products_options_validation where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."'");
							if(tep_db_num_rows($chk) > 0){
								$update = tep_db_query("UPDATE products_options_validation set settings = '".$jsondata."' where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."' ");
							}else{
								$insert = tep_db_query("INSERT INTO products_options_validation SET `option_id` = '".(int)$_POST['options_id']."', `products_id` = '".(int)$_POST['products_id']."', settings = '".$jsondata."'");
							}
						break;
						case 2:
							//echo 'radio';
							$data = array();
							$type = 'radio';
							$required = 0;
							if($_POST['mandetory']){
								$required = 1;
							}
							$data = array("type" => $type, "required" => $required);
							$jsondata = json_encode($data);
							$chk = tep_db_query("select id from products_options_validation where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."'");
							if(tep_db_num_rows($chk) > 0){
								$update = tep_db_query("UPDATE products_options_validation set settings = '".$jsondata."' where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."' ");
							}else{
								$insert = tep_db_query("INSERT INTO products_options_validation SET `option_id` = '".(int)$_POST['options_id']."', `products_id` = '".(int)$_POST['products_id']."', settings = '".$jsondata."'");
							}
						break;
						case 3:
							//echo 'checkbox';
							$data = array();
							$type = 'checkbox';
							$required = 0;
							if($_POST['mandetory']){
								$required = 1;
							}
							$data = array("type" => $type, "required" => $required);
							$jsondata = json_encode($data);
							$chk = tep_db_query("select id from products_options_validation where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."'");
							if(tep_db_num_rows($chk) > 0){
								$update = tep_db_query("UPDATE products_options_validation set settings = '".$jsondata."' where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."' ");
							}else{
								$insert = tep_db_query("INSERT INTO products_options_validation SET `option_id` = '".(int)$_POST['options_id']."', `products_id` = '".(int)$_POST['products_id']."', settings = '".$jsondata."'");
							}
						break;
						case 4:
							//echo 'textarea';
							$data = array();
							$type = 'textarea';
							$required = 0;
							if($_POST['mandetory']){
								$required = 1;
							}
							$minchar = (int)$_POST['minchar'];
							$maxchar = (int)$_POST['maxchar'];
							$validatetype = $_POST['validation_type'];
							$data = array("type" => $type, "required" => $required, "minchar" => $minchar, "maxchar" => $maxchar, "validatetype" => $validatetype);
							$jsondata = json_encode($data);
							$chk = tep_db_query("select id from products_options_validation where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."'");
							if(tep_db_num_rows($chk) > 0){
								$update = tep_db_query("UPDATE products_options_validation set settings = '".$jsondata."' where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."' ");
							}else{
								$insert = tep_db_query("INSERT INTO products_options_validation SET `option_id` = '".(int)$_POST['options_id']."', `products_id` = '".(int)$_POST['products_id']."', settings = '".$jsondata."'");
							}
						break;
					}
				  }
                if (DOWNLOAD_ENABLED == 'true' && isset($_POST['products_attributes_filename']) && $_POST['products_attributes_filename'] != '') {
                    tep_db_query("insert into " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " values (" . $products_attributes_id . ", '" . $_POST['products_attributes_filename'] . "', '" . $_POST['products_attributes_maxdays'] . "', '" . $_POST['products_attributes_maxcount'] . "')");
                }
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
            case 'update_option_name':
                for ($i = 0, $n = sizeof($languages); $i < $n; $i ++) {
                    $option_name = $_POST['option_name'];
                    $products_options_sort_order = $_POST['products_options_sort_order'];
                    $options_type = $_POST['option_type'];
                    $options_length = $_POST['products_options_length'];
                    $option_id = $_POST['option_id'];
                    $products_options_instruct = $_POST['products_options_instruct'];

                    tep_db_query("update " . TABLE_PRODUCTS_OPTIONS . " set options_type = '" . $options_type . "', options_length = '" . $options_length . "', products_options_sort_order = '" . $products_options_sort_order . "' where products_options_id = '" . $option_id . "'");
                    tep_db_query("update " . TABLE_PRODUCTS_OPTIONS_TEXT . " set products_options_instruct = '" . tep_db_input($products_options_instruct[$languages[$i]['id']]) . "', products_options_name = '" . tep_db_input($option_name[$languages[$i]['id']]) . "' where  products_options_text_id = '" . $_POST['option_id'] . "' and language_id = '" . $languages[$i]['id'] . "'");

                }
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
            case 'update_value':
                for ($i = 0, $n = sizeof($languages); $i < $n; $i ++) {
                    $value_name = $_POST['value_name'];
                    tep_db_query("update " . TABLE_PRODUCTS_OPTIONS_VALUES . " set products_options_values_name = '" . tep_db_input($value_name[$languages[$i]['id']]) . "' where products_options_values_id = '" . $_POST['value_id'] . "' and language_id = '" . $languages[$i]['id'] . "'");
                }
                tep_db_query("update " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " set products_options_id = '" . $_POST['option_id'] . "', products_options_values_id = '" . $_POST['value_id'] . "'  where products_options_values_to_products_options_id = '" . $_POST['value_id'] . "'");
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
            case 'update_product_attribute':
                $valueprice = str_replace(',','',$_POST['value_price']);
				if (strpos($valueprice, '-') !== false) {
					$_POST['price_prefix'] = '-';
					$_POST['value_price'] = str_replace('-','',$valueprice);
				} else {
					$_POST['price_prefix'] = '+';
					$_POST['value_price'] = str_replace('+','',$valueprice);
				}
                tep_db_query("update " . TABLE_PRODUCTS_ATTRIBUTES . " set products_id = '" . $_POST['products_id'] . "', options_id = '" . $_POST['options_id'] . "', options_values_id = '" . $_POST['values_id'] . "', options_values_price = '" . $_POST['value_price'] . "', price_prefix = '" . $_POST['price_prefix'] . "', main_options_sorting = '".$_POST['option_sort_order']."', products_options_sort_order = '" . $_POST['sort_order'] . "' where products_attributes_id = '" . $_POST['attribute_id'] . "'");
				  //update the default value for Select option
				  if(isset($_POST['select_default']) && $_POST['select_default'] == 1){
						$defaultUpdate = tep_db_query("UPDATE " . TABLE_PRODUCTS_ATTRIBUTES . " SET options_default = '0' where options_id = '" . $_POST['options_id'] . "' AND products_id = '" . $_POST['products_id'] . "' ");
						$defaultUpdate = tep_db_query("UPDATE " . TABLE_PRODUCTS_ATTRIBUTES . " SET options_default = '1' where products_attributes_id = '".(int)$_POST['attribute_id']."' ");
				  }else{
						$defaultUpdate = tep_db_query("UPDATE " . TABLE_PRODUCTS_ATTRIBUTES . " SET options_default = '0' where products_attributes_id = '".(int)$_POST['attribute_id']."' ");
				  }
				  //insert if mandetory
					$required = 0;
					if(isset($_POST['mandetory']) && $_POST['mandetory'] == 'on'){
						$required = 1;
					}
                    $typeQry = tep_db_fetch_array(tep_db_query("SELECT `options_type` FROM `products_options` po INNER JOIN `products_options_text` pot WHERE `products_options_id` = '".$_POST['options_id']."' "));
                    $typerow = $typeQry['options_type'];
                    if($typerow == 0){
                    	$type = 'select';
                    }elseif($typerow == 1){
                    	$type = 'textbox';
                    }elseif($typerow == 2){
                    	$type = 'radio';
                    }elseif($typerow == 3){
                    	$type = 'checkbox';
                    }elseif($typerow == 4){
                    	$type = 'textarea';
                    }elseif($typerow == 5){
                    	$type = 'boolean';
                    }elseif($typerow == 6){
                    	$type = 'datepicker';
                    }
					$data = array();
					$data = array("type" => $type, "required" => $required);
					$jsondata = json_encode($data);
					$chk = tep_db_query("select id from products_options_validation where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."'");
					if(tep_db_num_rows($chk) > 0){
						$update = tep_db_query("UPDATE products_options_validation set settings = '".$jsondata."' where `option_id` = '".(int)$_POST['options_id']."' AND `products_id` = '".(int)$_POST['products_id']."' ");
					}else{
						$insert = tep_db_query("INSERT INTO products_options_validation SET `option_id` = '".(int)$_POST['options_id']."', `products_id` = '".(int)$_POST['products_id']."', settings = '".$jsondata."'");
					}

                if (DOWNLOAD_ENABLED == 'true') {
                    $download_query_raw ="select products_attributes_filename from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . "
                    where products_attributes_id='" . $_POST['attribute_id'] . "'";
                    $download_query = tep_db_query($download_query_raw);
                    if (tep_db_num_rows($download_query) > 0) {
                        $download_attribute_found = true;
                    } else {
                        $download_attribute_found = false;
                    }
                    if ($_POST['products_attributes_filename'] != '') {
                        if ($download_attribute_found) {
                            tep_db_query("update " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . "
                                set products_attributes_filename='" . $_POST['products_attributes_filename'] . "',
                                products_attributes_maxdays='" . $_POST['products_attributes_maxdays'] . "',
                                products_attributes_maxcount='" . $_POST['products_attributes_maxcount'] . "'
                                where products_attributes_id = '" . $_POST['attribute_id'] . "'");
                        } else {
                            tep_db_query("insert " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . "
                                set products_attributes_id = '" . $_POST['attribute_id'] . "',
                                products_attributes_filename='" . $_POST['products_attributes_filename'] . "',
                                products_attributes_maxdays='" . $_POST['products_attributes_maxdays'] . "',
                                products_attributes_maxcount='" . $_POST['products_attributes_maxcount'] . "'");
                        }
                    } else {
                        if ($download_attribute_found) {
                            tep_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . "
                                where products_attributes_id = '" . $_POST['attribute_id'] . "'");
                        }
                    }
                }
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
            case 'delete_option':
                tep_db_query("delete from " . TABLE_PRODUCTS_OPTIONS_TEXT . " where products_options_text_id = '" . $_GET['option_id'] . "'");
                tep_db_query("delete from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id = '" . $_GET['option_id'] . "'");
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
            case 'delete_value':
                tep_db_query("delete from " . TABLE_PRODUCTS_OPTIONS_VALUES . " where products_options_values_id = '" . $_GET['value_id'] . "'");
                tep_db_query("delete from " . TABLE_PRODUCTS_OPTIONS_VALUES . " where products_options_values_id = '" . $_GET['value_id'] . "'");
                tep_db_query("delete from " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " where products_options_values_id = '" . $_GET['value_id'] . "'");
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
            case 'delete_attribute':
                tep_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_attributes_id = '" . $_GET['attribute_id'] . "'");
                tep_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " where products_attributes_id = '" . $_GET['attribute_id'] . "'");
                tep_redirect(tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $page_info));
                break;
        }
}

include(DIR_WS_INCLUDES . 'html_top.php');
?>   <link href="assets/plugins/jstree/dist/themes/default/style.min.css" rel="stylesheet" />
        <link href="assets/plugins/DataTables/media/css/dataTables.bootstrap.min.css" rel="stylesheet" />
        <link href="assets/plugins/DataTables/extensions/Responsive/css/responsive.bootstrap.min.css" rel="stylesheet" />
        <link href="assets/plugins/select2/dist/css/select2.min.css" rel="stylesheet" />
        <script language="javascript"><!--
            function go_option() {
                if (document.option_order_by.selected.options[document.option_order_by.selected.selectedIndex].value != "none") {
                    location = "<?php echo tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'option_page=' . ($_GET['option_page'] ? $_GET['option_page'] : 1)); ?>&option_order_by="+document.option_order_by.selected.options[document.option_order_by.selected.selectedIndex].value;
                }
            }
            var options_obj = new Object();
            <?php
                $values_query = tep_db_query("select povtpo.products_options_id, pov.products_options_values_id, pov.products_options_values_name from " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " povtpo,  " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pov.products_options_values_id = povtpo.products_options_values_id and language_id = '" . (int)$languages_id . "' order by povtpo.products_options_id");
                $notFirstTime = False;
                $last_option = '';
                if(tep_db_num_rows($values_query) > 0){
                while ($values = tep_db_fetch_array($values_query)) {
                    if ( $values['products_options_id'] != $last_option ) {
                        if ( $notFirstTime ) {
                            $option_str .= ']; options_obj["' . $values['products_options_id'] . '"] = [' . $values['products_options_values_id'];
                        } else {
                            $option_str .= ' options_obj["' . $values['products_options_id'] . '"] = [' . $values['products_options_values_id'];
                        }
                        $last_option = $values['products_options_id'];
                    } else {
                        $option_str .= ', ' . $values['products_options_values_id'];
                    }
                    $notFirstTime = true;
                }
                $option_str.= "]; \n";
                }

                echo $option_str;

            ?>
            var values_obj = new Object();
            <?php
                $values_query = tep_db_query("select products_options_values_id, products_options_values_name from " . TABLE_PRODUCTS_OPTIONS_VALUES . " where language_id = '" . (int)$languages_id . "' order by products_options_values_id");
                while ($values = tep_db_fetch_array($values_query)) {
                    $value_str .= ' values_obj["' . $values['products_options_values_id'] . '"] = \'' . addslashes($values['products_options_values_name']) . '\'; ';
                }

                echo $value_str . "\n";

            ?>
            function setvalues(form) {
                opt = document[form].options_id.options[document[form].options_id.selectedIndex].value;
                document[form].values_id.options.length = 0;
                if ( options_obj[opt] instanceof Array ) {
                    for ( var v in options_obj[opt] ) {
                        if(gisInteger(v)) {
                            document[form].values_id.options[document[form].values_id.options.length] = new Option( values_obj[options_obj[opt][v]], options_obj[opt][v] );
                        }
                    }
                } else {
                    document[form].values_id.options[document[form].values_id.options.length] = new Option( '<?php echo JAVASCRIPT_TEXT_OPTION_TYPE_TEXT; ?>', 0 );
                }

            }
            function gisInteger (s)
            {
                var i;

                if (gisEmpty(s))
                    if (gisInteger.arguments.length == 1) return 0;
                    else return (gisInteger.arguments[1] == true);

                for (i = 0; i < s.length; i++)
                {
                    var c = s.charAt(i);

                    if (!gisDigit(c)) return false;
                }

                return true;
            }

            function gisEmpty(s)
            {
                return ((s == null) || (s.length == 0))
            }

            function gisDigit (c)
            {
                return ((c >= "0") && (c <= "9"))
            }
        //--></script>
        <?php
include(DIR_WS_INCLUDES . 'header.php');
include(DIR_WS_INCLUDES . 'column_left.php');
?>
<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">

    <ul class="nav nav-tabs no-bg" id="mainTab" role="tablist">
      <li class="nav-item">
        <a class="nav-link active f-s-14 f-w-400" id="groups-tab" data-toggle="tab" href="#groups" role="tab" aria-controls="groups" aria-selected="true"><i class="fa fa-th-large mr-2"></i><?php echo HEADING_TITLE_OPT; ?></a>
      </li>
      <li class="nav-item">
        <a class="nav-link f-s-14 f-w-400" id="values-tab" data-toggle="tab" href="#values" role="tab" aria-controls="values" aria-selected="false"><i class="fa fa-th mr-2"></i><?php echo HEADING_TITLE_VAL; ?></a>
      </li>
      <li class="nav-item">
        <a class="nav-link f-s-14 f-w-400" id="attributes-tab" data-toggle="tab" href="#attributes" role="tab" aria-controls="attributes" aria-selected="false"><i class="fa fa-list mr-2"></i><?php echo HEADING_TITLE_ATTR; ?></a>
      </li>
    </ul>
    <div class="tab-content dark" id="mainTabContent">
      <div class="tab-pane fade show active" id="groups" role="tabpanel" aria-labelledby="groups-tab">
        <!-- begin panel -->
          <!-- body_text //-->
          <div id="table-attributes-groups" class="table-attributes-groups">
            <div class="row">
              <div class="col-sm-6 p-b-10">
                <a href="#new-option" data-toggle="modal" class="btn btn-primary btn-sm"><i class="fa fa-plus"></i> New Option Group</a>
              </div>
            </div>
            <div class="row">
            <div class="col-sm-12">
              <?php
              include('ajax/products_attributes/modal_new_option_group.php');
              $options = "select * from " . TABLE_PRODUCTS_OPTIONS . " po," . TABLE_PRODUCTS_OPTIONS_TEXT . " pot where pot.products_options_text_id = po.products_options_id and pot.language_id = '" . (int)$languages_id . "' order by products_options_id";
              $option_query = tep_db_query($options);
              ?>
              <table role="grid" id="data-table-options" class="table table-bordered table-hover dataTable no-footer dtr-inline">
                <thead>
                  <tr role="row">
                    <th class="sorting table-title-cell-bg"><?php echo TABLE_HEADING_OPT_NAME; ?></th>
                    <th class="sorting table-title-cell-bg"><?php echo TABLE_HEADING_OPT_TYPE; ?></th>
                    <th class="sorting table-title-cell-bg"><?php echo TABLE_HEADING_OPT_SIZE; ?></th>
                    <th class="sorting table-title-cell-bg text-center"><?php echo TABLE_HEADING_OPTION_SORT_ORDER; ?></th>
                    <th class="sorting table-title-cell-bg col-xs-2 text-center"><?php echo TABLE_HEADING_ACTION; ?></th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $next_id = 1;
                  $rows = 0;
                  $options = tep_db_query($options);
                  while ($options_values = tep_db_fetch_array($options)) {
                    $rows++;
                    ?>
                    <tr role="row">
                      <td> <strong class="txt-item-name"><?php echo htmlspecialchars($options_values["products_options_name"]); ?></strong><br/>
                      <?php echo $options_values["products_options_instruct"]; ?></td>
                      <td><?php echo translate_type_to_name($options_values["options_type"]); ?></td>
                      <td><?php echo $options_values["options_length"]; ?></td>
                      <td class="text-center"><?php echo $options_values["products_options_sort_order"]; ?></td>
                      <td class="text-center"><a onclick="editOptionEntry('<?php echo $options_values["products_options_id"]; ?>')" class="btn btn-success btn-xs text-white editOption"><i class="fa fa-pencil"></i></a> <a onclick="deleteOptionEntry('<?php echo $options_values["products_options_id"]; ?>', '<?php echo htmlspecialchars($options_values["products_options_name"]); ?>')" class="btn btn-danger btn-xs text-white editOption"><i class="fa fa-times"></i></a></td>
                    </tr>
                    <?php
                  }
                  ?>
                </tbody>
              </table>
              <!-- end tab options content -->
              </div>
            </div>
          </div>
          <!-- end body_text //-->
        <!-- end panel -->
      </div>
      <div class="tab-pane fade" id="values" role="tabpanel" aria-labelledby="values-tab">
        <!-- begin panel -->
          <!-- body_text //-->
          <div id="table-attributes-values" class="table-attributes-values">
            <div class="row">
              <div class="col-sm-6 p-b-10">
                <a href="#new-option-value" data-toggle="modal" class="btn btn-primary btn-sm"><i class="fa fa-plus"></i> Add Option Value</a>
              </div>
            </div>

            <?php include('ajax/products_attributes/modal_new_option_value.php');?>
            <div class="row">
              <div class="col-sm-12">
                <?php
                $values = "select distinct pov.products_options_values_id, pov.products_options_values_name, pov2po.products_options_id from
                " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov,
                " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " pov2po
                where
                pov2po.products_options_values_id = pov.products_options_values_id and
                pov.language_id = '" . (int)$languages_id . "'
                order by pov.products_options_values_id";
                $values = tep_db_query($values);
                ?>
                <table role="grid" id="data-table-option-value" class="table table-bordered table-hover dataTable no-footer dtr-inline">
                  <thead>
                    <tr role="row">
                      <th class="sorting table-title-cell-bg"><?php echo TABLE_HEADING_OPT_NAME;?></th>
                      <th class="sorting table-title-cell-bg"><?php echo TABLE_HEADING_OPT_VALUE;?></th>
                      <th class="sorting table-title-cell-bg col-xs-2 text-center"><?php echo TABLE_HEADING_ACTION;?></th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php
                    while ($values_values = tep_db_fetch_array($values)) {
                      $options_name = tep_options_name($values_values['products_options_id']);
                      $values_name = $values_values['products_options_values_name'];
                      ?>
                      <tr role="row">
                        <td><?php echo htmlspecialchars($options_name); ?></td>
                        <td><?php echo htmlspecialchars($values_name); ?></td>
                        <td class="text-center"><a onclick="editOptionValues('<?php echo $values_values["products_options_values_id"]; ?>')" class="btn btn-success btn-xs text-white"><i class="fa fa-pencil"></i></a> <a onclick="deleteOptionValue('<?php echo $values_values['products_options_values_id']; ?>', '<?php echo htmlspecialchars($values_name); ?>')" class="btn btn-danger btn-xs text-white editOption"><i class="fa fa-times"></i></a> </td>
                      </tr>
                      <?php
                    }
                    ?>
                  </tbody>
                </table>
              </div>
            </div>

          </div>
          <!-- end body_text //-->
        <!-- end panel -->
      </div>
      <div class="tab-pane fade" id="attributes" role="tabpanel" aria-labelledby="attributes-tab">
        <!-- begin panel -->
          <!-- body_text //-->
          <div id="table-product-attributes" class="table-product-attributes">
            <div class="row">
              <div class="col-sm-6 p-b-10">
                <a href="#new-attribute" data-toggle="modal" class="btn btn-primary btn-sm"><i class="fa fa-plus"></i> New Attribute</a>
              </div>
            </div>
            <div class="row">
            <div class="col-sm-12">
              <?php include('ajax/products_attributes/modal_new_attribute.php');?>
              <table id="data-table" class="table table-striped table-bordered">
                <thead>
                  <tr>
                    <th><?php echo TABLE_HEADING_PRODUCT;?></th>
                    <th>Type</th>
                    <th>Option Group</th>
                    <th><?php echo TABLE_HEADING_OPT_VALUE;?></th>
                    <th>Sort</th>
                    <th><?php echo TABLE_HEADING_OPT_PRICE;?></th>
                    <th>Default</th>
                    <th><?php echo TABLE_HEADING_OPT_PRICE_PREFIX;?></th>
                    <th><?php echo TABLE_HEADING_ACTION;?></th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $attributes = "select pa.* from " . TABLE_PRODUCTS_ATTRIBUTES . " pa,
                  " . TABLE_PRODUCTS_DESCRIPTION . " pd
                  where
                  pd.products_id = pa.products_id and
                  pd.language_id = '" . (int)$languages_id . "'
                  order by pd.products_name, pa.products_options_sort_order";
                  $attributes = tep_db_query($attributes);
                  $reqdmark = '';
                  while ($attributes_values = tep_db_fetch_array($attributes)) {
					//echo "select `settings` from `products_options_validation` where `option_id` = '".(int)$attributes_values['options_id']."' and products_id = '".(int)$attributes_values['products_id']."'  <br>";
					$validateQry = tep_db_query("select `settings` from `products_options_validation` where `option_id` = '".(int)$attributes_values['options_id']."' and products_id = '".(int)$attributes_values['products_id']."' ");
					if(tep_db_num_rows($validateQry) > 0){
						$row = tep_db_fetch_array($validateQry);
						$setings = json_decode($row['settings'],1);
						$isreqd = $setings['required'];
						if($isreqd){
							$reqdmark = ' <font style="color:#ff0000">*</font>';
						}else{
							$reqdmark = '';
						}
					}
                    $typeQry = tep_db_fetch_array(tep_db_query("SELECT `options_type`, products_options_name FROM `products_options` po INNER JOIN `products_options_text` pot
																ON pot.`products_options_text_id` = po.`products_options_id`
																WHERE `products_options_id` = '".(int)$attributes_values['options_id']."' AND pot.language_id = '" . (int)$languages_id . "'"));
                    $typerow = $typeQry['options_type'];
                    if($typerow == 0){
                    	$optionstype = 'Select';
                    }elseif($typerow == 1){
                    	$optionstype = 'Text';
                    }elseif($typerow == 2){
                    	$optionstype = 'Radio';
                    }elseif($typerow == 3){
                    	$optionstype = 'Checkbox';
                    }elseif($typerow == 4){
                    	$optionstype = 'Textarea';
                    }elseif($typerow == 5){
                    	$optionstype = 'Boolean';
                    }elseif($typerow == 6){
                    	$optionstype = 'Datepicker';
                    }
                    $the_download_query = tep_db_query("select products_attributes_filename, products_attributes_maxdays, products_attributes_maxcount from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " where products_attributes_id='" . $attributes_values['products_attributes_id'] . "'");
                    $the_download= tep_db_fetch_array($the_download_query);
                    //  Missing file check
                    $filename_is_missing='';
                    if ( $the_download['products_attributes_filename'] ) {
                      if ( !file_exists(DIR_FS_DOWNLOAD . $the_download['products_attributes_filename']) ) {
                        $filename_is_missing=' <span class="badge badge-danger" title="'.MISSING.'"><i class="fa fa-times"></i></span>';
                      } else {
                        $filename_is_missing=' <span class="badge badge-success" title="'.GOOD_FILE.'"><i class="fa fa-check"></i></span>';
                      }
                    }
                    ?>
                    <tr>
                      <td><?php echo tep_get_products_name($attributes_values['products_id']);?></td>
                      <td><?php echo $optionstype;?></td>
                      <!--<td><?php echo $the_download['products_attributes_filename'] . $filename_is_missing; ?></td>-->
                      <td><?php echo tep_options_name($attributes_values['options_id']) . $reqdmark;?></td>
                      <td><?php echo tep_values_name($attributes_values['options_values_id']);?></td>
                      <td><?php echo $attributes_values['products_options_sort_order']; ?></td>
                      <td><?php echo $attributes_values['options_values_price']; ?></td>
                      <td><?php echo ($attributes_values['options_default'])?'Yes':'No'; ?></td>
                      <td><?php echo $attributes_values['price_prefix']; ?></td>
                      <td class="text-center" style="padding:10px 0px;width:12%;">
                        <a title="View In Catalog" href="<?php echo tep_catalog_href_link('product_info.php', 'products_id=' . $attributes_values['products_id']); ?>" target="_blank" class="btn btn-info btn-xs addattributes text-white"><i class="fa fa-eye"></i></a>&nbsp;
                      	<?php if($typerow == 1 || $typerow == 4){ ?>
      						<a onclick="addvalidation('<?php echo $attributes_values['options_id']; ?>','<?php echo $typerow;?>',<?php echo $attributes_values['products_id']; ?>,'<?php echo $typeQry['products_options_name'];?>')" data-toggle="modal" class="btn btn-warning btn-xs addattributes text-white"><i class="fa fa-cog" title="Add Validation" data-toggle="tooltip" data-placement="bottom"></i></a>&nbsp;
                      	<?php } ?>
                      	<a onclick="editProductAttributes('<?php echo $attributes_values['products_attributes_id']; ?>')" class="btn btn-success btn-xs text-white"><i class="fa fa-pencil"></i></a>
                      	<?php /*<a data-href="<?php echo tep_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'action=delete_attribute&attribute_id=' . $attributes_values['products_attributes_id'],'NONSSL');?>" data-toggle="modal" data-target="#confirm-delete-attribute" class="btn btn-danger btn-xs text-white"><i class="fa fa-times"></i></a>*/ ?>
                      	<a onclick="deleteProductAttributes('<?php echo $attributes_values['products_attributes_id']; ?>')" class="btn btn-danger btn-xs text-white"><i class="fa fa-times"></i></a>

                      </td>
                    </tr>
                    <?php
                  }
                  ?>
                </tbody>
              </table>
              </div>
            </div>
          </div>
          <!-- end body_text //-->
        <!-- end panel -->
      </div>
    </div>



  </div>
</div>
<!-- body_eof //-->
        <script src="assets/plugins/DataTables/media/js/jquery.dataTables.js"></script>
        <script src="assets/plugins/DataTables/media/js/dataTables.bootstrap.min.js"></script>
        <script src="assets/plugins/DataTables/extensions/Responsive/js/dataTables.responsive.min.js"></script>
        <script src="assets/plugins/select2/dist/js/select2.min.js"></script>
        <script src="assets/plugins/eModal/eModal.min.js"></script>
        <script>
            $(document).ready(function() {
                if ($('#data-table').length !== 0) {
                    $('#data-table').DataTable({
                        responsive: true
                    });
                }

                if ($('#data-table-option-value').length !== 0) {
                    $('#data-table-option-value').DataTable({
                        responsive: true
                    });
                }

                if ($('#data-table-options').length !== 0) {
                    $('#data-table-options').DataTable({
                        responsive: true
                    });
                }
                $(".default-select2").select2();

            });

            /**** Edit and delete for Options Groups ****/
            function editOptionEntry(id) {
                var params = {
                    buttons: false,
                    loadingHtml: '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span><span class="h4">Loading</span>',
                    title: 'Edit Product Option',
                    url: './ajax/products_attributes/modal_edit_option_groups.php?editOpID='+id,
                };

                return eModal.ajax(params);
            }

            function deleteOptionEntry(id, opname) {
                var params = {
                    buttons: false,
                    loadingHtml: '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span><span class="h4">Loading</span>',
                    title: 'Delete Product Option Group '+opname,
                    url: './ajax/products_attributes/modal_delete_option_groups.php?delOpID='+id,
                };

                return eModal.ajax(params);
            }

            /**** Edit and delete for Options Values ****/
            function editOptionValues(id) {
                var params = {
                    buttons: false,
                    loadingHtml: '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span><span class="h4">Loading</span>',
                    title: 'Edit Product Option Value',
                    url: './ajax/products_attributes/modal_edit_option_values.php?editOpValID='+id,
                };

                return eModal.ajax(params);
            }

            function deleteOptionValue(id, opvname) {
                var params = {
                    buttons: false,
                    loadingHtml: '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span><span class="h4">Loading</span>',
                    title: 'Delete Product Option Value '+opvname,
                    url: './ajax/products_attributes/modal_delete_option_values.php?delOpValID='+id,
                };

                return eModal.ajax(params);
            }

            /**** Edit attributes ****/
            function editProductAttributes(id) {
                var params = {
                    buttons: false,
                    loadingHtml: '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span><span class="h4">Loading</span>',
                    title: 'Edit Product Attributes',
                    url: './ajax/products_attributes/modal_edit_attributes.php?editAttributelID='+id,
                };

                return eModal.ajax(params);
            }
            function deleteProductAttributes(aID){
                var params = {
                    buttons: false,
                    loadingHtml: '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span><span class="h4">Loading</span>',
                    title: 'Delete Product Attributes',
                    url: './ajax/products_attributes/modal_delete_attributes.php?deleteAttributelID='+aID,
                };
                return eModal.ajax(params);
            }
            /*
            $('#confirm-delete-attribute').on('show.bs.modal', function(e) {
                $(this).find('.btn-delete-confirm').attr('href', $(e.relatedTarget).data('href'));
            });
            */
		function getoptionvalue(options_id){
			if(options_id > 0){
				$.ajax({
					url : 'ajax_common.php?action=getalloptionvaluesdropdown',
					type : 'post',
					data : {'options_id':options_id},
					success: function(res){
						if(res == 'noopt'){
							$("#optionvaluename").hide(500);
							$('#morevalidation').html('<div class="form-group"><label class="col-md-3 control-label">Min Char allowed</label> <div class="col-md-5" style="display:inline-block;"> <input class="form-control" type="number" id="minchar" name="minchar" value=""> </div> <div class="col-md-2"></div></div> <div class="form-group"><label class="col-md-3 control-label">Max Char allowed</label> <div class="col-md-5" style="display:inline-block;"> <input class="form-control" type="number" id="maxchar" name="maxchar" value=""> </div> <div class="col-md-2"></div></div> <div class="form-group"><label class="col-md-3 control-label">Validation Type</label> <div class="col-md-5" style="display:inline-block;"> <select id="validation_type" name="validation_type" class="form-control"> <option value="STRING" selected>STRING</option> <option value="INTEGER">INTEGER</option> <option value="CURRENCY">CURRENCY</option> <option value="EMAIL">EMAIL</option> </select> </div></div>');
						} else if(res == 'noneed'){
							$("#optionvaluename").hide(500);
							$('#morevalidation').html('');
						} else if(res == 'nooptnoneed'){
							$("#optionvaluename").hide(500);
							$("#attpricesection").hide(500);
							$("#attoptionreqdsection").hide(500);
							$("#attvaluesortsection").hide(500);
							$('#morevalidation').html('');
						} else {
							$("#optionvaluename").show(500);
							$('#option_values_id').html(res);
							$('#morevalidation').html('');
						}
					}
				});
			} else {
				$("#optionvaluename").hide(500);
			}
		}

		var option_name_arr = JSON.stringify(<?php  echo strtolower($js_option_name_arr); ?>);
		var obj = JSON.parse(option_name_arr);
		$("#insert_option_text").click(function(){
			var opt_error = 0;
			var opt_name = $("input[id='option_name']").val().trim();
			for(var i=0;i<obj.length;i++){
				if(obj[i].toLowerCase() == opt_name.toLowerCase()){
					opt_error = 1
				}
			}
			if(opt_name == ''){
				$("#responseses").html('Option Name cannot be left Blank!!');
				$("#responseses").css({'color':'#ff0000'});
				return false;
			}
			if(opt_error == 1){
				$("#responseses").html('Entered Option Already Exist');
				$("#responseses").css({'color':'#ff0000'});
				return false;
			}
		});
		function checkoptionname(){
			var js_oopt_arr = $("textarea[name='optionname']").val().trim();
			var obj = JSON.parse(js_oopt_arr);
			var opt_error = 0;
			var opt_name = $("input[id='edit_option_name']").val().trim();
			for(var i=0;i<obj.length;i++){
				if(obj[i].toLowerCase() == opt_name.toLowerCase()){
					opt_error = 1
				}
			}
			if(opt_name == ''){
				$("#edit_option_responsive").html('Option Name cannot be left Blank!!');
				$("#edit_option_responsive").css({'color':'#ff0000'});
				return false;
			}
			if(opt_error == 1){
				$("#edit_option_responsive").html('Entered Option Already Exist');
				$("#edit_option_responsive").css({'color':'#ff0000'});
				return false;
			}
		}
		function checkoptvaluesname(){
			var js_oopt_arr = $("textarea[name='attributesname']").val().trim();
			var obj = JSON.parse(js_oopt_arr);
			var opt_error = 0;
			var opt_name = $("input[id='value_name_edit']").val().trim();
			for(var i=0;i<obj.length;i++){
				if(obj[i].toLowerCase() == opt_name.toLowerCase()){
					opt_error = 1
				}
			}
			if(opt_name == ''){
				$("#edit_opt_value_responsive").html('Option Value Name cannot be left Blank!!');
				$("#edit_opt_value_responsive").css({'color':'#ff0000'});
				return false;
			}
			if(opt_error == 1){
				$("#edit_opt_value_responsive").html('Entered Option Value Already Exist');
				$("#edit_opt_value_responsive").css({'color':'#ff0000'});
				return false;
			}
		}
		function fetchoptioncalues(options_id){
			if(options_id > 0){
				$.ajax({
					url : 'ajax_common.php?action=getoptionvalue',
					type : 'post',
					data : {'options_id':options_id},
					success: function(res){
						$('#option_values_textarea').html(res);
					}
				});
			} else {
				$("#ple_choose_responsive").html('Please Select an Option');
				$("#ple_choose_responsive").css({'color':'#ff0000'});
				return false;
			}
		}
		function addoptvaluesname(){
			var selectopt = $("select[name='option_id']").val();
			if(selectopt > 0){
				$("#selectdpdown").html('');
				var js_oopt_arr = $("textarea[name='attributesname']").val().trim();
				var obj = JSON.parse(js_oopt_arr);
				var opt_error = 0;
				var opt_name = $("input[id='value_name']").val().trim();
				for(var i=0;i<obj.length;i++){
					if(obj[i].toLowerCase() == opt_name.toLowerCase()){
						opt_error = 1
					}
				}
				if(opt_name == ''){
					$("#edit_value_responsive").html('Option Value Name cannot be left Blank!!');
					$("#edit_value_responsive").css({'color':'#ff0000'});
					return false;
				}
				if(opt_error == 1){
					$("#edit_value_responsive").html('Entered Option Value Already Exist');
					$("#edit_value_responsive").css({'color':'#ff0000'});
					return false;
				}
			} else {
				$("#selectdpdown").html('Please Select an Option');
				$("#selectdpdown").css({'color':'#ff0000'});
				return false;
			}
		}
		function validateattform(){
			var productname = $("input[name='search_data']").val().trim();
			var selectopt = $("select[name='options_id']").val();
			var selectvalue = $("select[name='values_id']").val();
			if(productname == ''){
				$("#new_products_error").html('Entered Product Name!!');
				$("#new_products_error").css({'color':'#ff0000'});
				return false;
			}
			if(selectopt == '0'){
				$("#new_option_error").html('Please Select an Option!!');
				$("#new_option_error").css({'color':'#ff0000'});
				return false;
			}
		}
		function addvalidation(oID, otype, pID, oname){
			//alert(oID);
			//alert(otype);
			//alert(oname);
			var params = {
				buttons: false,
				loadingHtml: '<span class="fa fa-circle-o-notch fa-spin fa-3x text-primary"></span><span class="h4">Loading</span>',
				title: 'Add Validation to '+oname,
				url: './ajax/products_attributes/modal_add_validation.php?pID='+pID+'&options_id='+oID+'&otype='+otype,
			};
			return eModal.ajax(params);
		}

		$('a[data-toggle="tab"]').click(function (e) {
		e.preventDefault();
		$(this).tab('show');
		});

		$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
			var id = $(e.target).attr("href");
			localStorage.setItem('selectedTab', id)
		});

		var selectedTab = localStorage.getItem('selectedTab');
		if (selectedTab != null) {
			$('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
		}

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