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

@set_time_limit(0);

error_reporting (0);

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 - выбор категорий";
	
?>
<!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>
</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;
			}
		}
		
		foreach ($_POST['cat_ids'] as $category_name => $value){
			$cat_ids[$category_name] = (int)$value;
			if ((int)$value == 0){
				//$errors[] = "Для категории '$category_name' не задан id";
			}
		}
		
		$saved = array();
		$saved['categories'] = $categories;
		$saved['cat_ids'] = $cat_ids;
	
		file_put_contents('prom.txt', json_encode($saved));
		
	}
	
	if (is_file('prom.txt')){
		$saved = json_decode(file_get_contents('prom.txt'), true);
		$categories = $saved['categories'];
		$cat_ids = $saved['cat_ids'];
		$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>
<h4>(отметьте выгружаемые категории товаров)</h4>
<table width="80%" border="0" style="border-collapse:collapse;border-color:black;">

<tr>
<td>
<ul>
<?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);
	
	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']);
		
		if (count($result_sub) == 0){
			$checkbox_count++;
			if (in_array($result1['category_id'], $categories)){
				$checked = ' checked ';
			}else{
				$checked = '';
			}
?>
<li><input type="checkbox" id="cb<?php echo $checkbox_count; ?>" name="category[<?php echo $result1['category_id']?>]" value="1" <?php echo $checked?> /> <?php echo $result1['name']?> <input type="text" name="cat_ids[<?php echo $result1['name']?>]" value="<?php value($result1['name'], $result1['category_id']); ?>" size="5" /> (<?php echo $result1['category_id']?>)</li>
<?php
		}else{
			$checkbox_count++;
			if (in_array($result1['category_id'], $categories)){
				$checked = ' checked ';
			}else{
				$checked = '';
			}
?>
<li><input type="checkbox" id="cb<?php echo $checkbox_count; ?>" name="category[<?php echo $result1['category_id']?>]" value="1" <?php echo $checked?> /> <?php echo $result1['name']?> <input type="text" name="cat_ids[<?php echo $result1['name']?>]" value="<?php value($result1['name'], $result1['category_id']); ?>" size="5" /> (<?php echo $result1['category_id']?>)</li>
<ul>
<?php 
			show_subcat($result_sub, $result1['name']);
?>
</ul>
<?php 

		}
	}
?>
</ul>
</td>
</tr>
<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>
</table>
</center>
</form>
</body></html>
	
<?php 
//***************************************************************************

// вывод подкатегорий
function show_subcat($result_sub, $parent_name){
	
	global $DB, $dbprefix;
	global $categories, $checkbox_count, $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']);
		
		if (count($result_sub2) == 0){
			if (in_array($result_sub1['category_id'], $categories)){
				$checked = ' checked ';
			}else{
				$checked = '';
			}
			$checkbox_count++;
?>
<li><input type="checkbox" id="cb<?php echo $checkbox_count; ?>" name="category[<?php echo $result_sub1['category_id']?>]" value="1" <?php echo $checked?> /> <?php echo $result_sub1['name']?> <input type="text" name="cat_ids[<?php echo $parent_name.'|'.$result_sub1['name']?>]" value="<?php value($parent_name.'|'.$result_sub1['name'], $result_sub1['category_id']); ?>" size="5" /> (<?php echo $result_sub1['category_id']?>)</li>
<?php 
		}else{
			if (in_array($result_sub1['category_id'], $categories)){
				$checked = ' checked ';
			}else{
				$checked = '';
			}
			$checkbox_count++;
?>
<li><input type="checkbox" id="cb<?php echo $checkbox_count; ?>" name="category[<?php echo $result_sub1['category_id']?>]" value="1" <?php echo $checked?> /> <?php echo $result_sub1['name']?> <input type="text" name="cat_ids[<?php echo $parent_name.'|'.$result_sub1['name']?>]" value="<?php value($parent_name.'|'.$result_sub1['name'], $result_sub1['category_id']); ?>" size="5" /> (<?php echo $result_sub1['category_id']?>)</li>
<ul>
<?php 
			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;
		}
	}
}