<?php
if (isset($_GET['action'])) $action = addslashes(trim(strip_tags(stripslashes(rawurldecode($_GET['action'])))));
else $action = false;

if (isset($_POST['submit'])) {
	if ($_POST['submit'] == 'reload') $update = 0;
}

if ($update) {
	if (isset($_POST['parent_data'])) {
		foreach ($_POST['parent_data'] AS $key => $value){
			if ((!isset($_POST['parent_guidv4']) OR !$_POST['parent_guidv4']) && $value) {
				$parent_guidv4 = $value;
			}
		}
	}
}

if (isset($_POST['level_data'])) {
	foreach ($_POST['level_data'] AS $key => $value){
		$level_data[$key] = $value;
		
		if (isset($value['value_c_active']) && $value['value_c_active']) $level_data[$key]['value_c_active'] = $value['value_c_active'];
		else $level_data[$key]['value_c_active'] = 0;
		if (isset($value['value_c_thumbnails']) && $value['value_c_thumbnails']) $level_data[$key]['value_c_thumbnails'] = $value['value_c_thumbnails'];
		else $level_data[$key]['value_c_thumbnails'] = 0;
		
		if (!isset($url) OR !$url) $url = $value['value_title'];
		
		$level_data[$key]['value_position'] = '';
		if (isset($value['value_position']) && is_array($value['value_position'])){
			$level_data[$key]['value_position'] = implode(',', $value['value_position']);
		}
	}
}

if ($update) {
	
	if ($action != 'quick'){
		if (!$guidv4 OR !$url){
			$error = LABEL_ERROR_MANDATORY;
		}
	}

	if (isset($_POST['date'])) {
		$datetime = DateTime::createFromFormat('Y-m-d\TH:i', $_POST['date']);
		$datetime = $datetime->getTimestamp();
	}
	
	$url = url_slug($url);
	
	$has_class = check_column($module, 'class');
	
	if (!isset($error) && $update == 1){
		if ($action == 'quick'){
			$key = str_replace('quick[', '', str_replace(']', '', addslashes(trim(strip_tags(stripslashes(rawurldecode($_POST['key'])))))));
			$value = trim(stripslashes(nl2br($_POST['quick'][$key])));
			if ($key == 'url'){
				$value = url_slug($_POST['quick'][$key]);
				$sql_tmp = "SELECT url, guidv4 FROM ".$module." WHERE id = :id ";
				$result_tmp = $conn->prepare($sql_tmp);
				$result_tmp->bindValue(':id', $id, PDO::PARAM_INT);
				$result_tmp->execute();
				if ($result_tmp->rowCount()){
					$arr_tmp = $result_tmp->fetch();
					$sql_check = "SELECT id FROM ".$module." WHERE guidv4 != :guidv4 AND url = :url ";
					$result_check = $conn->prepare($sql_check);
					$result_check->bindValue(':guidv4', $arr_tmp['guidv4'], PDO::PARAM_STR);
					$result_check->bindValue(':url', $value, PDO::PARAM_STR);
					$result_check->execute();
					if ($result_check->rowCount()){
						$value = check_url($module, $value);
					}
					$sql = "UPDATE ".$module." SET url = :url, title = IF (BINARY title = :url_old, :url, title) WHERE guidv4 = :guidv4";
					$result = $conn->prepare($sql);
					$result->bindValue(':url', $value);
					$result->bindValue(':url_old', $arr_tmp['url']);
					$result->bindValue(':guidv4', $arr_tmp['guidv4']);
					if ($result->execute()){
						print $value;
					}
				}				
			} else {
				$sql = "UPDATE ".$module." SET ".$key." = :".$key." WHERE id = :id";
				$result = $conn->prepare($sql);
				$result->bindValue(':'.$key, $value);
				$result->bindValue(':id', $id);
				if ($result->execute()){
					print $value;
				}
			}
		} else if ($action == 'edit'){
			$sql_tmp = "SELECT guidv4, url FROM ".$module." WHERE id = :id ";
			$result_tmp = $conn->prepare($sql_tmp);
			$result_tmp->bindValue(':id', $id, PDO::PARAM_INT);
			$result_tmp->execute();
			if ($result_tmp->rowCount()){
				$arr_tmp = $result_tmp->fetch();
				$sql_check = "SELECT id FROM ".$module." WHERE guidv4 != :guidv4 AND url = :url ";
				$result_check = $conn->prepare($sql_check);
				$result_check->bindValue(':guidv4', $arr_tmp['guidv4'], PDO::PARAM_STR);
				$result_check->bindValue(':url', $url, PDO::PARAM_STR);
				$result_check->execute();
				if ($result_check->rowCount()){
					$url = check_url($module, $url);
				}
				foreach ($level_data AS $key => $value){
					$sql_sub = "SELECT * FROM ".$module." WHERE language = :language AND guidv4 = :guidv4 LIMIT 1";
					$result_sub = $conn->prepare($sql_sub);
					$result_sub->bindValue(':language', $value['language'], PDO::PARAM_STR);
					$result_sub->bindValue(':guidv4', $arr_tmp['guidv4'], PDO::PARAM_STR);
					$result_sub->execute();
					if ($result_sub->rowCount()){
						$sql = "UPDATE ".$module." SET 
										datetime = :datetime, 
										sortorder = :sortorder, 
										url = :url ";
						if ($has_class) $sql.= ", class = :class ";
				    for($i = 1; $i <= $count_fields; $i++){
				    	if (isset($value['value_'.$field[$i]])){
					    	$sql.= ", ".$field[$i]." = :".$field[$i]." ";
					    }
				    }
				    if (isset($parent_guidv4) && $parent_guidv4) $sql.= ", parent_guidv4 = :parent_guidv4 ";
				    else $sql.= ", parent_guidv4 = NULL ";
				    $sql.= "WHERE language = :language AND guidv4 = :guidv4 ";
						$result = $conn->prepare($sql);
						
						if ($value['value_title'] === $arr_tmp['url']) $value['value_title'] = $url;
						
						$result->bindValue(':datetime', $datetime, PDO::PARAM_INT);
						$result->bindValue(':sortorder', $sortorder, PDO::PARAM_INT);
						$result->bindValue(':url', $url, PDO::PARAM_STR);
						if ($has_class) $result->bindValue(':class', $class, PDO::PARAM_STR);
						
				    for($i = 1; $i <= $count_fields; $i++){
				    	if (isset($value['value_'.$field[$i]])){
								$result->bindValue(':'.$field[$i], $value['value_'.$field[$i]]);
					    }
				    }
						
				    if (isset($parent_guidv4) && $parent_guidv4) $result->bindValue(':parent_guidv4', $parent_guidv4, PDO::PARAM_STR);
						$result->bindValue(':language', $value['language'], PDO::PARAM_STR);
						$result->bindValue(':guidv4', $arr_tmp['guidv4'], PDO::PARAM_STR);
						$result->execute();
					} else {
						$sql = "INSERT INTO ".$module." SET 
										guidv4 = :guidv4, 
										datetime = :datetime, 
										sortorder = :sortorder, 
										language = :language, 
										url = :url ";
						if ($has_class) $sql.= ", class = :class ";
				    for($i = 1; $i <= $count_fields; $i++){
				    	if (isset($value['value_'.$field[$i]])){
					    	$sql.= ", ".$field[$i]." = :".$field[$i]." ";
					    }
				    }
				    if (isset($parent_guidv4) && $parent_guidv4) $sql.= ", parent_guidv4 = :parent_guidv4 ";
						$result = $conn->prepare($sql);
						
						$result->bindValue(':guidv4', $guidv4, PDO::PARAM_STR);
						$result->bindValue(':datetime', $datetime, PDO::PARAM_INT);
						$result->bindValue(':sortorder', $sortorder, PDO::PARAM_INT);
						$result->bindValue(':language', $value['language'], PDO::PARAM_STR);
						$result->bindValue(':url', $url, PDO::PARAM_STR);
						if ($has_class) $result->bindValue(':class', $class, PDO::PARAM_STR);
				    for($i = 1; $i <= $count_fields; $i++){
				    	if (isset($value['value_'.$field[$i]])){
								$result->bindValue(':'.$field[$i], $value['value_'.$field[$i]]);
					    }
				    }
				    if (isset($parent_guidv4) && $parent_guidv4) $result->bindValue(':parent_guidv4', $parent_guidv4, PDO::PARAM_STR);
						$result->execute();
					}
				}
			} else {
				$error = LABEL_ERROR_MANDATORY;
			}
		} else {
			$sql_tmp = "SELECT id FROM ".$module." WHERE guidv4 = :guidv4 LIMIT 1";
			$result_tmp = $conn->prepare($sql_tmp);
			$result_tmp->bindValue(':guidv4', $guidv4, PDO::PARAM_STR);
			$result_tmp->execute();
			if (!$result_tmp->rowCount()){
				$ii = 0;
				$url = check_url($module, $url);
				foreach ($level_data AS $key => $value){
					if (!$value['value_title']) $value['value_title'] = $url;
					$sql = "INSERT INTO ".$module." SET 
									guidv4 = :guidv4, 
									datetime = :datetime, 
									sortorder = :sortorder, 
									language = :language, 
									url = :url ";
					if ($has_class) $sql.= ", class = :class ";
			    for($i = 1; $i <= $count_fields; $i++){
			    	if (isset($value['value_'.$field[$i]])){
				    	$sql.= ", ".$field[$i]." = :".$field[$i]." ";
				    }
			    }
				   if (isset($parent_guidv4) && $parent_guidv4) $sql.= ", parent_guidv4 = :parent_guidv4 ";
					$result = $conn->prepare($sql);
					
					$result->bindValue(':guidv4', $guidv4, PDO::PARAM_STR);
					$result->bindValue(':datetime', $datetime, PDO::PARAM_INT);
					$result->bindValue(':sortorder', $sortorder, PDO::PARAM_INT);
					$result->bindValue(':language', $value['language'], PDO::PARAM_STR);
					$result->bindValue(':url', $url, PDO::PARAM_STR);
					if ($has_class) $result->bindValue(':class', $class, PDO::PARAM_STR);
			    for($i = 1; $i <= $count_fields; $i++){
			    	if (isset($value['value_'.$field[$i]])){
							$result->bindValue(':'.$field[$i], $value['value_'.$field[$i]]);
				    }
			    }
				   if (isset($parent_guidv4) && $parent_guidv4) $result->bindValue(':parent_guidv4', $parent_guidv4, PDO::PARAM_STR);
					$result->execute();
					if ($ii == 0) $id = $conn->lastInsertId();
					$ii++;
				}
			} else {
				$error = LABEL_ERROR_ID_EXISTS;
			}
		}
		
		
		if (!isset($error)){
			
			if ($module == 'content_levels') {
				include('includes/function/seo.php');
			}
			
			if ($action == 'add'){
		    for($i = 1; $i <= $count_fields; $i++){
		    	unset(${$field[$i]});
		    }
		    unset($update);
		    $url_form = "popup_form.php?module=".$module."&backend_module=".$backend_module."&id=".$id."&action=edit&success";
		  } elseif ($action == 'copy'){
		    $url_form  = "popup_form.php?module=".$module."&backend_module=".$backend_module."&id=".$id."&action=edit&success";
			} else $update_parent = true;
			
			if (isset($url_form )){
		    print "
				<script type='text/javascript'>
				opener.document.forms[0].submit();
				window.open('".$url_form ."', '_self');
				</script>";
			}
		}
	}
}

include('includes/function/load.php');

if ((!isset($_POST['submit']) && isset($id)) OR (isset($_POST['submit']) && $_POST['submit'] != 'reload' && isset($id) && !isset($error))){
	$sql_tmp = "SELECT id, iso, label FROM languages ORDER BY sortorder ASC";
	$result_tmp = $conn->prepare($sql_tmp);
	$result_tmp->execute();
	if ($result_tmp->rowCount()){
		while ($arr_tmp = $result_tmp->fetch()){
			$level_data[$arr_tmp['id']]['language'] = $arr_tmp['iso'];
			$level_data[$arr_tmp['id']]['title'] = id($arr_tmp['label']);
			if ($arr_tmp['iso'] == $language) {
				for($i = 1; $i <= $count_fields; $i++){
					if (isset(${$field[$i]})){
						$level_data[$arr_tmp['id']]['value_'.$field[$i]] = ${$field[$i]};
					} else {
						$level_data[$arr_tmp['id']]['value_'.$field[$i]] = NULL;
					}
		    }
			} else {
				$sql_sub_tmp = "SELECT * FROM ".$module." WHERE language = :language AND BINARY url = :url LIMIT 1";
				$result_sub_tmp = $conn->prepare($sql_sub_tmp);
				$result_sub_tmp->bindValue(':language', $arr_tmp['iso'], PDO::PARAM_STR);
				$result_sub_tmp->bindValue(':url', $url, PDO::PARAM_STR);
				$result_sub_tmp->execute();
				if ($result_sub_tmp->rowCount()){
					$arr_sub_tmp = $result_sub_tmp->fetch();
					for($i = 1; $i <= $count_fields; $i++){
						if (isset($arr_sub_tmp[$field[$i]])){
							$level_data[$arr_tmp['id']]['value_'.$field[$i]] = $arr_sub_tmp[$field[$i]];
						} else {
							$level_data[$arr_tmp['id']]['value_'.$field[$i]] = NULL;
						}
			    }
				} else {
					for($i = 1; $i <= $count_fields; $i++){
						if (isset(${$field[$i]})){
							$level_data[$arr_tmp['id']]['value_'.$field[$i]] = NULL;
						} else {
							$level_data[$arr_tmp['id']]['value_'.$field[$i]] = NULL;
						}
			    }
					$level_data[$arr_tmp['id']]['value_title'] = $url;
					$level_data[$arr_tmp['id']]['value_c_active'] = 1;
					$level_data[$arr_tmp['id']]['value_c_thumbnails'] = 0;
				}
			}
		}
	}
}

if (isset($datetime) && $datetime) $datetime = date('Y-m-d\TH:i', $datetime);
else $datetime = date('Y-m-d\TH:i');

if ($action != 'edit' && (!isset($update) OR !$update) && !isset($sortorder)){
	$sql_tmp = "SELECT sortorder FROM ".$module." ORDER BY sortorder DESC LIMIT 1";
	$result_tmp = $conn->prepare($sql_tmp);
	$result_tmp->execute();
	if ($result_tmp->rowCount()){
		$arr_tmp = $result_tmp->fetch();
		$sortorder = $arr_tmp['sortorder'];
		$sortorder++;
	} else $sortorder = 1;
	
	$result = $conn->prepare("SELECT * FROM ".$module." LIMIT 0");
	if ($result->execute()){
		$count_fields = $result->columnCount();
		$ii = 0;
		for($zz = 0; $zz < $count_fields; $zz++){
			$type = $result->getColumnMeta($zz);
			if ($type['name'] != 'id') {
				$ii++;
				$field[$ii] = $type['name'];
			}
		}
		$count_fields = $ii--;
	}
	
	$sql_tmp = "SELECT id, iso, label FROM languages ORDER BY sortorder ASC";
	$result_tmp = $conn->prepare($sql_tmp);
	$result_tmp->execute();
	if ($result_tmp->rowCount()){
		while ($arr_tmp = $result_tmp->fetch()){
			$level_data[$arr_tmp['id']]['language'] = $arr_tmp['iso'];
			$level_data[$arr_tmp['id']]['title'] = id($arr_tmp['label']);
			for($i = 1; $i <= $count_fields; $i++){
				$level_data[$arr_tmp['id']]['value_'.$field[$i]] = NULL;
	    }
			$level_data[$arr_tmp['id']]['value_c_active'] = 1;
			$level_data[$arr_tmp['id']]['value_c_thumbnails'] = 0;
		}
	}
} elseif ($action == 'copy'){
	$guidv4 = guidv4();
}