<?php
/*------------------------------------------------
 * генератор XML for rozetka.ua         2025-03-07
 * Copyright © FinBoss 2025
 * finboss.ua@gmail.com 
 *
 *
 * License: Commercial open source software (COSS) 
 *------------------------------------------------
 */

@set_time_limit(0);

error_reporting (E_ALL ^ ~E_DEPRECATED);

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;
}

$title = "Генрератор XML для rozetka.ua - выбор категорий и товаров";

include_once($cron_prefix.'rozetka.cfg.php');
	
?>
<!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 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 

	if (is_file('tmp/selected.txt')){
		$saved = json_decode(file_get_contents('tmp/selected.txt'), true);
	}else{
		$saved = array();
	}

	if (isset($_POST['save'])){
		if ($_GET['mode'] == 'show-all'){
			$saved = array();
		}else{
			unset($saved[$_GET['mode']]);
		}
		
		if (isset($_POST['p'])){
			foreach ($_POST['p'] as $id_category => $products){
				foreach ($products as $id_product => $p){

					if (isset($p['checked'])){
						$saved[$id_category][$id_product]['checked'] = 1;
					}
					if (isset($p['name'])){
						$saved[$id_category][$id_product]['name'] = $p['name'];
					}
					if (isset($p['price']) AND (real)$p['price'] != 0){
						$saved[$id_category][$id_product]['price'] = (real)$p['price'];
					}
					if (isset($p['old_price']) AND (real)$p['old_price'] != 0){
						$saved[$id_category][$id_product]['old_price'] = (real)$p['old_price'];
					}
					if (isset($p['category'])){
						$saved[$id_category][$id_product]['category'] = $p['category'];
					}
					if (isset($p['attr'])){
						$saved[$id_category][$id_product]['attr'] = $p['attr'];
					}
				}
			}
		}
		
		file_put_contents('tmp/selected.txt', json_encode($saved));

	}
	
	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){
						$saved[$id_category][$id_product]['category'] = $new_category;
					}
				}
				file_put_contents('tmp/selected.txt', json_encode($saved));
			}
		}
	}
	
// 	if (count($errors) != 0){
// 		echo ('<br/>Ошибки:<br/>');
// 		foreach ($errors as $string){
// 			echo ($string.'<br/>');
// 		}
// 	}
	
	$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'];
	
	// проверка заданной группы покупателей
	$customer_group_id = 0;
	if ($customer_group != ''){
		
		$SQL = "SELECT
					*
				FROM
					{$dbprefix}customer_group_description
				WHERE
					name = ?
					AND
					language_id = ?";
		$result_c = $DB->select($SQL, trim($customer_group), $config_language_id);
		
		if ($result_c){
			$customer_group_id = $result_c[0]['customer_group_id'];
		}else{
			die("Ошибка: не найдена группа покупателей '$customer_group'");
		}
		
	}

?>
<form method="post" name="adminForm">
<center>
<h2>Категории</h2>
<h4>Для выбора товаров из категории щелкните по ее названию <br/> ИЛИ <br/> <a href="?mode=show-all#products">ПОКАЗАТЬ ВСЕ ТОВАРЫ</a></h4>
<table width="70%" border="1" style="border-collapse:collapse;border-color:black;">
<tr>
<th>Категория</th>
<th>Всего товаров в наличии</th>
<th>Выгружается в прайс</th>
</tr>
<?php 

	$checkbox_count = 0;
	
	$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
			ORDER BY 
				c.sort_order, cd.name
			";
	$result = $DB->select($SQL);
	
	$total = $total_in_base = 0;
	$categories_b = array();
	
	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 = ?
				ORDER BY 
					c.sort_order, cd.name
				";
		$result_sub = $DB->select($SQL, $result1['category_id']);
		
		$id_category = $result1['category_id'];
		$name = $result1['name'];
		
		$categories_b[$id_category] = $name;
		
		if (count($result_sub) == 0){

			if (isset($saved[$id_category])){
				foreach ($saved[$id_category] as $id_product => $p){
					if ($p['checked'] == 1){
						$total++;
					}
				}
			}
?>
<tr>
<td align=left><a href="?mode=<?php echo $id_category; ?>#products"><?php echo $name;?></a></td>
<td align="center"><?php echo get_total_products($id_category);?></td>
<td align="center"><?php echo get_in_price_products($id_category);?></td>
</tr>
<?php 
		}else{

?>
<tr>
<td align=left><a href="?mode=<?php echo $id_category; ?>#products"><?php echo $name;?></a></td>
<td align="center"><?php echo get_total_products($id_category);?></td>
<td align="center"><?php echo get_in_price_products($id_category);?></td>
</tr>
<?php 
			
			if (isset($saved[$id_category])){
				foreach ($saved[$id_category] as $id_product => $p){
					if ($p['checked'] == 1){
						$total++;
					}
				}
			}
			
			show_subcat($result_sub, $result1['name']);

		}
	}
?>
<tr>
<td align="right">Всего:</td>
<td align="center"><?php echo $total_in_base; ?></td>
<td align="center"><?php echo $total; ?></td>
</tr>
</table>
<br /><br />
<?php 
if (isset($_GET['mode'])){
	
	if ($_GET['mode'] == 'show-all'){
		show_products(0);
	}else{
		show_products($_GET['mode']);
	}
	
}
?>
</center>
</form>
</body></html>
	
<?php 
//***************************************************************************

// вывод подкатегорий
function show_subcat($result_sub, $parent_name){
	
	global $DB, $dbprefix, $total, $saved;
	global $categories_b, $config_language_id;
	
	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 = ?
				ORDER BY 
					c.sort_order, cd.name
				";
		$result_sub2 = $DB->select($SQL, $result_sub1['category_id']);
		
		$name = $parent_name.'>'.$result_sub1['name'];
		$id_category = $result_sub1['category_id'];
		
		$categories_b[$id_category] = $name;
		
		if (count($result_sub2) == 0){
			
			if (isset($saved[$id_category])){
				foreach ($saved[$id_category] as $id_product => $p){
					if ($p['checked'] == 1){
						$total++;
					}
				}
			}
?>
<tr>
<td align=left><a href="?mode=<?php echo $id_category; ?>#products"><?php echo $name;?></a></td>
<td align="center"><?php echo get_total_products($id_category);?></td>
<td align="center"><?php echo get_in_price_products($id_category);?></td>
</tr>
<?php 
		}else{
?>
<tr>
<td align=left><a href="?mode=<?php echo $id_category; ?>#products"><?php echo $name;?></a></td>
<td align="center"><?php echo get_total_products($id_category);?></td>
<td align="center"><?php echo get_in_price_products($id_category);?></td>
</tr>
<?php 
			
			if (isset($saved[$id_category])){
				foreach ($saved[$id_category] as $id_product => $p){
					if ($p['checked'] == 1){
						$total++;
					}
				}
			}
			
			show_subcat($result_sub2, $name);

		}
	}
}

// запись сообщения
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])){
		echo $cat_ids[$cat_name];
	}else{
		if ($auto_generate_cat_id){
			echo $cat_id;
		}
	}
}

function get_total_products($id_category){
	
	global $DB, $dbprefix, $total_in_base;
	
	$SQL = "SELECT
				count(*) as count
			FROM
				{$dbprefix}product_to_category
			WHERE
				category_id = ?";
	$result = $DB->select($SQL, $id_category);
	if ($result){
		$total_in_base += $result[0]['count'];
		return $result[0]['count'];
	}else{
		return 0;
	}
}

function get_in_price_products($id_category){
	
	global $saved;
	
	if (isset($saved[$id_category])){
		$total_cat = 0;
		foreach ($saved[$id_category] as $id_product => $p){
			if ($p['checked'] == 1){
				$total_cat++;
			}
		}
		return $total_cat;
	}else{
		return '';
	}
}


function show_products($id_category){
	
	global $config_language_id, $DB, $dbprefix, $saved, $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, $saved;
	
	
	if (trim($category_table_textarea) == ''){
?>
		<h1 style="color:red;">Ошибка: не задан параметр 'Категории Розетки'</h1>
<?php 
		return;
	}
	
	// проверка валюты
	$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[] = 'Выберите категорию';
	$category_table_array = explode('/r/n', $category_table_textarea);
	foreach ($category_table_array as $string){
		if (strpos($string, '>') !== false){
			$cat1_array = explode('>', $string);
			$cat1 = array_pop($cat1_array);
			list($cat1_name, $cat1_id) = explode('(', $cat1);
			$category_table[(int)$cat1_id] = $cat1_name;
		}
	}
	
	$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).")"; 
	}
	
	if ($id_category != 0){
	
		$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" value="Сохранить" />
	</td>
</tr>
<?php 
		foreach ($products as $product){
			
			$checked = $name = $rozetka_price = $rozetka_old_price = $atrr_string = '';
			$category = 0;
			if ($id_category != 0){
				if (isset($saved[$id_category][$product['id_product']])){
					
					$p = $saved[$id_category][$product['id_product']];
					
					if (isset($p['checked'])){
						$checked = 'checked';
					}
					if (isset($p['name'])){
						$name = $p['name'];
					}
					if (isset($p['price'])){
						$rozetka_price = $p['price'];
					}
					if (isset($p['old_price'])){
						$rozetka_old_price = $p['old_price'];
					}
					if (isset($p['category'])){
						$category = $p['category'];
					}
					if (isset($p['attr'])){
						$atrr_string = $p['attr'];
					}
					
				}
			}else{
				
				foreach ($saved as $current_cat => $cat_products){
					
					if (isset($cat_products[$product['id_product']])){
						
						$p = $cat_products[$product['id_product']];
					
						if (isset($p['checked'])){
							$checked = 'checked';
						}
						if (isset($p['name'])){
							$name = $p['name'];
						}
						if (isset($p['price'])){
							$rozetka_price = $p['price'];
						}
						if (isset($p['old_price'])){
							$rozetka_old_price = $p['old_price'];
						}
						if (isset($p['category'])){
							$category = $p['category'];
						}
						if (isset($p['attr'])){
							$atrr_string = $p['attr'];
						}
						
						break;
					}
				}
			}
			
			
			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 $rozetka_price; ?>" size="5" /><br/><br/><input type="text" name="p[<?php echo $id_category; ?>][<?php echo $product['id_product'];?>][old_price]" value="<?php echo $rozetka_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" value="Сохранить" />
	</td>
</tr>
</table>	
<?php
	}else{
		echo "Ошибка: В выбранной категории '".$categories_b[$id_category]."' нет товаров для экспорта";
	}

}


function select_category($category_table, $rozetka_category_id, $id_category, $id_product){
	
	if ($rozetka_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 == $rozetka_category_id){
			$selected = 'selected';
		}else{
			$selected = '';
		}
?>
<option value="<?php echo $category_id; ?>" <?php echo $selected; ?>><?php echo $category_name?></option>
<?php 		
	}
?>	
</select>
<?php 	
}