<?php
/*------------------------------------------------
 * Open Cart XML Generator              2019-04-12
 * Copyright © FinBoss 2019
 * finboss.ua@gmail.com 
 *
 *
 * License: Commercial open source software (COSS) 
 *------------------------------------------------
 */

@set_time_limit(0);

error_reporting (0);

$path_parts = pathinfo(__FILE__);				//	используется для установки пути
$cron_prefix = $path_parts['dirname'].'/';		//	используется для установки пути

header('Content-Type: text/html; charset=utf-8');

// подключение библиотек
require_once ($cron_prefix."./lib/DbSimple-i/Generic.php");

if (file_exists($cron_prefix."../config.php")){
	// подключение к базе
	
	include_once ($cron_prefix."../config.php");
	
	//	$DB = DbSimple_Generic::connect("mysqli://".DB_USERNAME.":".DB_PASSWORD."@".DB_HOSTNAME."/".DB_DATABASE);
	
	$parsed = array(
			'scheme' => 'mysqli',
			'host' => DB_HOSTNAME,
			'user' => DB_USERNAME,
			'pass' => DB_PASSWORD,
			'path' => "/".DB_DATABASE,
			'dsn'  => "mysqli://".DB_USERNAME.":".DB_PASSWORD."@".DB_HOSTNAME."/".DB_DATABASE
	);
	$DB = DbSimple_Generic::connect($parsed);
	
	if ($DB->errmsg){
		header('Content-Type: text/html; charset=utf-8');
		echo "Невозможно подключиться к базе данных";
		die();
	}
	
	// Устанавливаем обработчик ошибок.
	$DB->setErrorHandler('databaseErrorHandler');
	
	$DB->query("set character_set_client='utf8'");
	$DB->query("set character_set_results='utf8'");
	$DB->query("set collation_connection='utf8_bin'");
	
	$dbprefix = DB_PREFIX;
	
}else{
	header('Content-Type: text/html; charset=utf-8');
	echo ("Невозможно подключиться к базе данных");
	exit;
}

include_once($cron_prefix.'hotline.cfg.php');

$title = "Генрератор XML - выбор категорий";
	
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" >
<title><?php echo $title?></title>
<script language="javascript" type="text/javascript">
function checkAll( n, fldName ) {
  if (!fldName) {
     fldName = 'cb';
  }
	var f = document.adminForm;
	var c = f.toggle.checked;
	var n2 = 0;
	for (i=0; i < n; i++) {
		cb = eval( 'f.' + fldName + '' + i );
		if (cb) {
			cb.checked = c;
			n2++;
		}
	}
}
</script>
<script language="javascript" type="text/javascript">
function ctrlSelectMenu (elem, evt)
{
	if (!evt)
		evt = event;

	var target = evt.target || evt.srcElement;
	if (target.tagName == 'INPUT' && target.type == 'checkbox') {
		var checked = target.checked;
		var List = document.forms[0];
		for (var i = 0; i < List.length; i++){
			List[i].checked = checked;
		}
	}
}
</script>
</head>
<body style="font-family:Trebuchet MS; font-size: 10pt;" bgcolor="#f5f8fb">

<table width="100%" bgcolor="#416e98">
<tr valign="middle">
<td><span style="font-size:25px; color:#FFF; font-family:Trebuchet MS">OpenCart</span></td>
<td align="right"><span style="font-size:15px; color:#FFF; font-family:Trebuchet MS"><?php echo $title?></span></td>
</tr>
</table>

<?php 

	$cat_ids = array();
	
	$errors = array();

	if (isset($_POST['save'])){
		
		$categories = array();
		if (isset($_POST['category'])){
			foreach ($_POST['category'] as $category_id => $value){
				$categories[] = $category_id;
			}
		}
		
		$saved = array();
		$saved['categories'] = $categories;
	
		file_put_contents('tmp/hotline.txt', json_encode($saved));
		
	}
	
	if (is_file('tmp/selected.txt')){
		$selected = json_decode(file_get_contents('tmp/selected.txt'), true);
	}else{
		$selected = array();
	}
	
	if (isset($_POST['save_products'])){

		unset($selected[$_GET['mode']]);
		
		if (isset($_POST['p'])){
			foreach ($_POST['p'] as $id_category => $products){
				foreach ($products as $id_product => $p){
					
					if (isset($p['checked'])){
						$selected[$id_category][$id_product]['checked'] = 1;
					}
					if (isset($p['name'])){
						$selected[$id_category][$id_product]['name'] = $p['name'];
					}
					if (isset($p['price']) AND (real)$p['price'] != 0){
						$selected[$id_category][$id_product]['price'] = (real)$p['price'];
					}
					if (isset($p['old_price']) AND (real)$p['old_price'] != 0){
						$selected[$id_category][$id_product]['old_price'] = (real)$p['old_price'];
					}
					if (isset($p['category'])){
						$selected[$id_category][$id_product]['category'] = $p['category'];
					}
					if (isset($p['attr'])){
						$selected[$id_category][$id_product]['attr'] = $p['attr'];
					}
				}
			}
		}
		
		file_put_contents('tmp/selected.txt', json_encode($selected));
		
	}
	
	if (isset($_POST['save_cat'])){
		if (isset($_POST['p'])){
			
			if ($_POST['p'][0][0]['category'] != 0){
				
				$new_category = $_POST['p'][0][0]['category'];
				
				foreach ($_POST['p'] as $id_category => $products){
					foreach ($products as $id_product => $p){
						$selected[$id_category][$id_product]['category'] = $new_category;
					}
				}
				file_put_contents('tmp/selected.txt', json_encode($selected));
			}
		}
	}
	
	if (is_file('tmp/hotline.txt')){
		$saved = json_decode(file_get_contents('tmp/hotline.txt'), true);
		$categories = $saved['categories'];
		$auto_generate_cat_id = false;
	}else{
		$categories = $cat_ids = array();
		$auto_generate_cat_id = false;
	}
	
	if (count($errors) != 0){
		echo ('<br/>Ошибки:<br/>');
		foreach ($errors as $string){
			echo ($string.'<br/>');
		}
	}

?>

<form method="post" name="adminForm">
<center>
<h2>Категории</h2>
<?php 
if (isset($_GET['mode'])){
?>	
<h4><a href="set_categories.php">Перейти к выбору категорий</a></h4>
<?php 
}else{
?>
<h4>(отметьте выгружаемые категории товаров)</h4>
<?php 
}
?>
<h4>Для выбора товаров из категории щелкните по ее названию<h4>
<table width="80%" border="0" style="border-collapse:collapse;border-color:black;">

<tr>
<td>
<ul>
<?php 

	$checkbox_count = 0;
	
	$categories_b = array();
	
	$config_language = config_get('config_language');
	
	$SQL = "SELECT 
				* 
			FROM 
				`{$dbprefix}language` 
			WHERE 
				`code` = ?";
	$result = $DB->select($SQL, $config_language);
	
	$config_language_id = $result[0]['language_id'];
	
	// построение таблицы категорий
	$SQL = "SELECT
				c.category_id,
				c.parent_id,
				cd.name
			FROM
				{$dbprefix}category as c
				LEFT JOIN {$dbprefix}category_description as cd ON (cd.category_id = c.category_id AND cd.language_id = $config_language_id)
			WHERE
				c.parent_id = 0
				AND
				c.status = 1
			ORDER BY 
				c.sort_order, cd.name
			";
	$result = $DB->select($SQL);
	
	foreach ($result as $result1){
		
		// наличие подкатегорий
		$SQL = "SELECT
					c.category_id,
					c.parent_id,
					cd.name
				FROM
					{$dbprefix}category as c
					LEFT JOIN {$dbprefix}category_description as cd ON (cd.category_id = c.category_id AND cd.language_id = $config_language_id)
				WHERE
					c.parent_id = ?
					AND
					c.status = 1
				ORDER BY 
					c.sort_order, cd.name
				";
		$result_sub = $DB->select($SQL, $result1['category_id']);
		
		if (count($result_sub) == 0){
			
			$checkbox_count++;
			if (in_array($result1['category_id'], $categories)){
				$checked = ' checked ';
				$cb_img = 'selected.gif';
			}else{
				$checked = '';
				$cb_img = 'unselected.gif';
			}
			
			if (isset($_GET['mode'])){
				$cb = "<img src=\"$cb_img\" style=\"vertical-align:middle\" />";
			}else{
				$cb = "<input type=\"checkbox\" id=\"cb$checkbox_count\" name=\"category[{$result1['category_id']}]\" value=\"1\"  $checked />";
			}
?>
<li><?php echo $cb;?> <a href="?mode=<?php echo $result1['category_id']; ?>#products"><?php echo $result1['name']?></a> (<?php echo $result1['category_id']?>)</li>
<?php
			$categories_b[$result1['category_id']] = $result1['name']." ({$result1['category_id']})";
		
		}else{
			$checkbox_count++;
			if (in_array($result1['category_id'], $categories)){
				$checked = ' checked ';
				$cb_img = 'selected.gif';
			}else{
				$checked = '';
				$cb_img = 'unselected.gif';
			}
			
			if (isset($_GET['mode'])){
				$cb = "<img src=\"$cb_img\" style=\"vertical-align:middle\" />";
			}else{
				$cb = "<input type=\"checkbox\" id=\"cb$checkbox_count\" name=\"category[{$result1['category_id']}]\" value=\"1\"  $checked />";
			}
?>
<li><?php echo $cb;?> <a href="?mode=<?php echo $result1['category_id']; ?>#products"><?php echo $result1['name']?></a> (<?php echo $result1['category_id']?>)</li>
<ul>
<?php 
			$categories_b[$result1['category_id']] = $result1['name']." ({$result1['category_id']})";
			show_subcat($result_sub, $result1['name']);
?>
</ul>
<?php 

		}
	}
	
	asort($categories_b);
	
?>
</ul>
</td>
</tr>
<?php 
if (!isset($_GET['mode'])){
?>
<tr>
	<td align="center">
		<input type="checkbox" name="toggle" class="delete" onclick="checkAll(<?php echo ($checkbox_count+1); ?>)" /> Все выделить/снять выделение
	</td>
</tr>
<tr>
	<td align="center">
		<input type="submit" name="save" value="Сохранить" />
	</td>
</tr>
<?php 
}else{
?>
<tr>
	<td align="center">
<h4><a href="set_categories.php">Перейти к выбору категорий</a></h4>
	</td>
</tr>
<?php 
}
?>
</table>
<br /><br />
<?php 
if (isset($_GET['mode'])){
	show_products($_GET['mode']);
}
?>
</center>
</form>
</body></html>
	
<?php 
//***************************************************************************

// вывод подкатегорий
function show_subcat($result_sub, $parent_name){
	
	global $DB, $dbprefix;
	global $categories, $checkbox_count, $config_language_id;
	global $categories_b;
	
	foreach ($result_sub as $result_sub1){
		
		// наличие подкатегорий
		$SQL = "SELECT
					c.category_id,
					c.parent_id,
					cd.name
				FROM
					{$dbprefix}category as c
					LEFT JOIN {$dbprefix}category_description as cd ON (cd.category_id = c.category_id AND cd.language_id = $config_language_id) 
				WHERE
					c.parent_id = ?
					AND
					c.status = 1
				ORDER BY 
					c.sort_order, cd.name
				";
		$result_sub2 = $DB->select($SQL, $result_sub1['category_id']);
		
		if (count($result_sub2) == 0){
			if (in_array($result_sub1['category_id'], $categories)){
				$checked = ' checked ';
				$cb_img = 'selected.gif';
			}else{
				$checked = '';
				$cb_img = 'unselected.gif';
			}
			$checkbox_count++;
			
			if (isset($_GET['mode'])){
				$cb = "<img src=\"$cb_img\" style=\"vertical-align:middle\" />";
			}else{
				$cb = "<input type=\"checkbox\" id=\"cb$checkbox_count\" name=\"category[{$result_sub1['category_id']}]\" value=\"1\"  $checked />";
			}
?>
<li><?php echo $cb;?> <a href="?mode=<?php echo $result_sub1['category_id']; ?>#products"><?php echo $result_sub1['name']?></a> (<?php echo $result_sub1['category_id']?>)</li>
<?php 
		
			$categories_b[$result_sub1['category_id']] = $parent_name.'>'.$result_sub1['name']." ({$result_sub1['category_id']})";
		
		}else{
			if (in_array($result_sub1['category_id'], $categories)){
				$checked = ' checked ';
			}else{
				$checked = '';
			}
			$checkbox_count++;
			
			if (isset($_GET['mode'])){
				$cb = "<img src=\"$cb_img\" style=\"vertical-align:middle\" />";
			}else{
				$cb = "<input type=\"checkbox\" id=\"cb$checkbox_count\" name=\"category[{$result_sub1['category_id']}]\" value=\"1\"  $checked />";
			}
?>
<li><?php echo $cb;?> <a href="?mode=<?php echo $result_sub1['category_id']; ?>#products"><?php echo $result_sub1['name']?></a> (<?php echo $result_sub1['category_id']?>)</li>
<ul>
<?php 
			$categories_b[$result_sub1['category_id']] = $parent_name.'>'.$result_sub1['name']." ({$result_sub1['category_id']})";
			show_subcat($result_sub2, $parent_name.'>'.$result_sub1['name']);
?>
</ul>
<?php 

		}
		
	}
	
}

// запись сообщения
function write_to_log($message){

	if ($GLOBALS["log_to"] == "file"){
		fwrite($GLOBALS["log_handle"],$message."<br>\r\n");
	}

	echo("<br />".$message);

}

// Обработчик ошибок SQL
function databaseErrorHandler($message, $info)
{
    // Если использовалась @, ничего не делать.
    //if (!error_reporting()) return;
    // Выводим подробную информацию об ошибке.
    echo "SQL Error: $message<br><pre>"; 
    print_r($info);
    echo "</pre>";
    exit();
}

function config_get($key){
	
	global $config, $DB, $dbprefix;
	
	if (isset($config[$key])){
		return $config[$key];
	}else{
		$SQL = "SELECT
					value 
				FROM
					{$dbprefix}setting
				WHERE
					`key` = ?
				"; 
		$result = $DB->select($SQL, $key);
		if ($result){
			$config[$key] = $result[0]['value'];
			return $config[$key];
		}else{
			return false;
		}
	
	}
}

function value($cat_name, $cat_id){
	
	global $cat_ids;
	global $auto_generate_cat_id;
	
	if (isset($cat_ids[$cat_name])){
		if ($cat_ids[$cat_name] != 0){
			echo $cat_ids[$cat_name];
		}
	}else{
		if ($auto_generate_cat_id){
			echo $cat_id;
		}
	}
}


function show_products($id_category){
	
	global $config_language_id, $DB, $dbprefix, $selected, $reduction, $categories_b;
	global $site_protocol_select, $site_url, $category_table_textarea, $round_price_select;
	global $manufacturers_textarea, $category_on_stock_int, $customer_group_id;
	global $categories;
	
	
	// проверка валюты
	$SQL = "SELECT
				*
			FROM
				{$dbprefix}currency
			WHERE
				code = 'UAH'";
	$result_cu = $DB->select($SQL);
	
	if ($result_cu){
		$currency_rate = $result_cu[0]['value'];
	}else{
?>
		<h1 style="color:red;">Ошибка: не найдена валюта с кодом 'UAH'</h1>
<?php 
		return;
	}
	
	switch ($round_price_select){
		
		case 'до копеек':
			$precision = 2;
			break;
			
		case 'до целого':
			$precision = 0;
			break;
			
		case 'до десятков':
			$precision = -1;
			break;
	}
	
	$category_table = array();
	$category_table[0] = 'Выберите категорию';
	foreach ($categories_b as $cat1_id => $string){
		$category_table[(int)$cat1_id] = $string;
	}
	
// 	$manufacturers = array();
// 	if (trim($manufacturers_textarea) != ''){
// 		$manufacturers_array = explode('/r/n', trim($manufacturers_textarea));
// 		foreach ($manufacturers_array as $manufacturer){
// 			if (trim($manufacturer) != ''){
// 				$manufacturers[] = trim($manufacturer);
// 			}
// 		}
// 	}
	
// 	$manufacturers_ids = array();
// 	if (count($manufacturers) == 0){
// 		$manuf = "";
// 	}else{
	
// 		$manufacturers_list = "'".implode("','",$manufacturers)."'";
		
// 		$SQL = "SELECT
// 					manufacturer_id
// 				FROM
// 					{$dbprefix}manufacturer
// 				WHERE
// 					name IN ($manufacturers_list)";
// 		$result_m = $DB->query($SQL);
		
// 		foreach ($result_m as $result_m1){
// 			$manufacturers_ids[] = $result_m1['manufacturer_id'];
// 		}
		
// 		if (count($manufacturers_ids) == 0){
// 			echo "Ошибка: Не найдены заданные в настройках производители";
// 			return;
// 		}
		
// 		$manuf = "AND p.manufacturer_id IN (".implode(',', $manufacturers_ids).")"; 
// 	}

	// проверка движка
	$SQL = "SHOW COLUMNS FROM
	{$dbprefix}product_to_category";
	$result = $DB->select($SQL);
	$found = false;
	foreach ($result as $result1){
		if ($result1['Field'] == 'main_category'){
			$found = true;
			break;
		}
	}
	
	
	if ($id_category != 0){
	
		if ($found){
			
			//ocStore
			
			$SQL = "SELECT
						product_id
					FROM
						{$dbprefix}product_to_category
					WHERE
						category_id = ?
						AND
						main_category = 1";
			$result_cp = $DB->query($SQL, $id_category);
			
		}else{
		
			// opencart
			
			$SQL = "SELECT
						product_id
					FROM
						{$dbprefix}product_to_category
					WHERE
						category_id = ?";
			$result_cp = $DB->query($SQL, $id_category);
		
		}
		
		if (count($result_cp) == 0){
			echo "Ошибка: В выбранной категории '".$categories_b[$id_category]."' нет товаров";
			return;
		}
		
		$cp = array();
		foreach ($result_cp as $result_cp1){
			$cp[] = $result_cp1['product_id'];
		}
		
		$cat = ' AND p.product_id IN ('.implode(',', $cp).') ';
	
	}else{
		$cat = '';
	}
	
	$SQL = "SELECT
				pd.name as name,
				p.image,
				p.model,
				p.product_id as id_product,
				p.price,
				p.quantity
			FROM
				{$dbprefix}product as p
				LEFT JOIN {$dbprefix}product_description as pd ON (p.product_id = pd.product_id)
			WHERE
				pd.language_id = $config_language_id
				$cat
				$manuf
				AND p.status = 1
			ORDER BY
				p.product_id";
	// 				AND p.quantity > 0
	$products = $DB->query($SQL);
?>
<a name="products"></a>
<?php 		
	if ($products){
?>
<h3><?php echo ($id_category==0)?'ВСЕ ТОВАРЫ':$categories_b[$id_category]; ?></h3>
<table width="95%" border="1" style="border-collapse:collapse;border-color:black;">
<tr>
<th rowspan=2>Все&nbsp;выделить<br/>Снять&nbsp;выделение<br/><input type="checkbox" name="toggle" class="delete" onclick="ctrlSelectMenu(this, event)" /></th>
<th rowspan=2 colspan=2>Товар</th>
<th rowspan=2>Остаток</th>
<th rowspan=2>Цена<br/>Старая&nbsp;цена</th>
<th colspan=4>Для&nbsp;ПРОМ</th>
</tr>
<tr>
<th>Название</th>
<th>Цена<br/>Старая&nbsp;цена</th>
<th>Категория</th>
<th>Дополнительные<br/>параметры</th>
</tr>
<?php 
		if ($_GET['mode'] != 'show-all'){
?>
<tr>
<td colspan=7 align=right>Установить всем товарам указанную категорию >>></td>
<td align=center><?php select_category($category_table, 0, 0, 0) ?> </td> 
<td align=center><input type="submit" name="save_cat" value="Вперед!" /></td>
</tr>
<?php 
		}
?>
<tr>
	<td colspan=9 align="center">
		<input type="submit" name="save_products" value="Сохранить" />
	</td>
</tr>
<?php 
		foreach ($products as $product){
			
			$checked = $name = $hotline_price = $hotline_old_price = $atrr_string = '';
			$category = 0;
			if (isset($selected[$id_category][$product['id_product']])){
				
				$p = $selected[$id_category][$product['id_product']];
				
				if (isset($p['checked'])){
					$checked = 'checked';
				}
				if (isset($p['name'])){
					$name = $p['name'];
				}
				if (isset($p['price'])){
					$hotline_price = $p['price'];
				}
				if (isset($p['old_price'])){
					$hotline_old_price = $p['old_price'];
				}
				if (isset($p['category'])){
					$category = $p['category'];
				}
				if (isset($p['attr'])){
					$atrr_string = $p['attr'];
				}
				
			}
			
			if ($product['image'] != ''){
				if (is_file('../image/'.$product['image'])){
					$img_url = $site_protocol_select.'://'.$site_url.'/image/'.$product['image'];
				}else{
					$img_url = 'no-photo.jpg';
				}
			}else{
				$img_url = 'no-photo.jpg';
			}
?>
<tr>
<td align="center" valign="middle"><input type="checkbox" id="p<?php echo $id_category; ?>_<?php echo $product['id_product'];?>" name="p[<?php echo $id_category; ?>][<?php echo $product['id_product'];?>][checked]" value="1" <?php echo $checked?> /><br/>id=<?php echo $product['id_product']; ?></td>
<td align="center" valign="middle"><img width="100" src="<?php echo $img_url; ?>" /></td>
<td align="center" valign="middle"><?php echo "'".$product['model']."' ".$product['name']; ?></td>
<td align="center" valign="middle"><?php echo $product['quantity']; ?></td>
<td align="right" valign="middle"><?php

			$price = $product['price'];
			
			// скидка 
			$SQL = "SELECT
						*
					FROM
						{$dbprefix}product_special
					WHERE
						product_id = ?
					AND
						(date_start = '0000-00-00' OR date_start <= NOW())
						AND
						(date_end = '0000-00-00' OR date_end >= NOW())
						AND
						customer_group_id = ?";
						$result_s = $DB->select($SQL, $product['id_product'], $customer_group_id);
			
			if ($result_s){
				$old_price = $product['price'];
				$price = $result_s[0]['price'];
			}else{
				$price = $product['price'];
				$old_price = 0;
			}
			
			
			if ($old_price == 0){
				echo round($price, $precision);
			}else{
				echo round($price, $precision);
				echo "<br/>";
				echo round($old_price, $precision);
			}
			
			


?></td>
<td align="center" valign="middle"><input type="text" name="p[<?php echo $id_category; ?>][<?php echo $product['id_product'];?>][name]" value="<?php echo $name; ?>" size="25" /><br/><?php echo $name; ?></td>
<td align="center" valign="middle"><input type="text" name="p[<?php echo $id_category; ?>][<?php echo $product['id_product'];?>][price]" value="<?php echo $hotline_price; ?>" size="5" /><br/><br/><input type="text" name="p[<?php echo $id_category; ?>][<?php echo $product['id_product'];?>][old_price]" value="<?php echo $hotline_old_price; ?>" size="5" /></td>
<td align="center" valign="middle"> <?php select_category($category_table, $category, $id_category, $product['id_product']) ?> </td>
<td align="center" valign="middle"><textarea rows=3 name="p[<?php echo $id_category; ?>][<?php echo $product['id_product'];?>][attr]"><?php echo $atrr_string ?></textarea></td>
</tr>	
<?php 			
		}

?>
<tr>
	<td colspan=9 align="center">
		Всего: <?php echo count($products)?>
	</td>
</tr>
<tr>
	<td colspan=9 align="center">
		<input type="submit" name="save_products" value="Сохранить" />
	</td>
</tr>
</table>	
<?php
	}else{
		echo "Ошибка: В выбранной категории '".$categories_b[$id_category]."' нет товаров для экспорта";
	}

}


function select_category($category_table, $hotline_category_id, $id_category, $id_product){
	
	if ($hotline_category_id == 0 AND $id_product != 0){
		?>
<h3 style="color:red;">не выбрана категория</h3>
<?php 		
	}
	
?>
<select name="p[<?php echo $id_category?>][<?php echo $id_product?>][category]" size="1">
<?php 

	foreach ($category_table as $category_id => $category_name){

		if ($category_id == $hotline_category_id){
			$selected = 'selected';
		}else{
			$selected = '';
		}
?>
<option value="<?php echo $category_id; ?>" <?php echo $selected; ?>><?php echo $category_name?></option>
<?php 		
	}
?>	
</select>
<?php 	
}