<?php
if (isset($_POST['submit'])) {
	if ($_POST['submit'] == 'reload') $multi_update = 0;
}

if ($multi_update) {	
	if (isset($c_levels) && $c_levels){
		$parent_guidv4 = array();
		if (isset($_POST['parent_guidv4']) && is_array($_POST['parent_guidv4'])){
			foreach ($_POST['parent_guidv4'] AS $key => $value){
				$parent_guidv4[] = $value;
			}
			$parent_guidv4 = array_unique($parent_guidv4);
		} else if (isset($_POST['parent_guidv4'])){
			$parent_guidv4[] = addslashes(trim(strip_tags(stripslashes(rawurldecode($_POST['parent_guidv4'])))));
		}
	}
	
	if (isset($parent_guidv4) && is_array($parent_guidv4)) $base_parent_guidv4 = $parent_guidv4;
	else $base_parent_guidv4 = array();
	
	$datetime = time();
	
	$language_foldername = $language;
	if (!isset($_POST['language'])) $language = NULL;
	if (isset($_POST['filename']) && $_POST['filename']) $filename = trim(strip_tags(stripslashes(str_replace("'", "&#39;", $_POST['filename']))));
	
	if (isset($_FILES['upload'])){
		$file_count = count($_FILES['upload']['tmp_name']);
		for ($y = 0; $y < $file_count; $y++){
			if (file_exists($_FILES['upload']['tmp_name'][$y]) && is_uploaded_file($_FILES['upload']['tmp_name'][$y])){
				
				unset($error);
				
				$file_data = $_FILES['upload']['tmp_name'][$y];
				$file_name = $_FILES['upload']['name'][$y];
				$file_type = $_FILES['upload']['type'][$y];
				$filesize = $_FILES['upload']['size'][$y];
				
				$parent_guidv4 = $base_parent_guidv4;

				$upload_path = NULL;
				if (isset($_POST['upload_path'])){
					if (is_array($_POST['upload_path'])){
						if (isset($_POST['upload_path'][$y])) $upload_path = $_POST['upload_path'][$y];
					} else {
						$upload_path = $_POST['upload_path'];
					}
				}
				
				if ($upload_path && substr($upload_path, -1) == '/' && isset($file_name) && $file_name){
					$upload_path .= $file_name;
				}
				
				if (isset($c_levels) && $c_levels && $upload_path){
					$parent_guidv4 = library_multiupload_levels_from_path($conn, $module, $language_foldername, $parent_guidv4, $upload_path);
				}
						
				$extension_tmp = explode(".", $file_name);
				$extension = end($extension_tmp);
				
				$extension_new = mime2ext($file_type, $extension);
				$category = mime2category($file_type);
				
				$is_svg = ($extension_new === 'svg');
				
				if (isset($c_webp) && $c_webp && !$is_svg){
					$extension_old = $extension_new;
					$extension_new = 'webp';
				}
				
				
				if ($category != 'image'){
					$error = LABEL_ERROR_FILE_TYPE;
				}
	
				$file_new = NULL;
				if (isset($filename) && $filename) $file_new = url_slug($filename);
				else if (isset($file_name) && $file_name) $file_new = url_slug(str_replace('.'.$extension, '', $file_name));
				
				$file_new = check_file($module, $file_new, $extension_new);
				
				if (!$file_new){
					$error = LABEL_ERROR_MANDATORY;
				}
				
				
				if (!isset($error) && $multi_update == 1){			
					
					$session_module = NULL;
					if (isset($_POST['session_module']) && $_POST['session_module']){
						$session_module = addslashes(trim(strip_tags(stripslashes($_POST['session_module']))));
					}
					
					if ($session_module != 'gallery'){
						$c_lightbox_watermark = '0';
						$c_thumbnails_watermark = '0';
						$sql_tmp = "SELECT title, value FROM settings_options WHERE title IN ('c_lightbox_watermark', 'c_thumbnails_watermark') AND c_public = '0' ORDER BY id ASC";
						$result_tmp = $conn->prepare($sql_tmp);
						$result_tmp->execute();
						if ($result_tmp->rowCount()){
							while ($arr_tmp = $result_tmp->fetch()){
								if ($arr_tmp['title'] == 'c_lightbox_watermark') $c_lightbox_watermark = ($arr_tmp['value'] == '1') ? '1' : '0';
								if ($arr_tmp['title'] == 'c_thumbnails_watermark') $c_thumbnails_watermark = ($arr_tmp['value'] == '1') ? '1' : '0';
							}
						}
					}
					
					$sql = "INSERT INTO ".$module." SET ";
					
			    for($i = 1; $i <= $count_fields; $i++){
			    	if (isset(${$field[$i]}) OR $field[$i] == 'file') {
				    	if ($i == 1) $sql.= " ".$field[$i]." = :".$field[$i]." ";
				    	else $sql.= ", ".$field[$i]." = :".$field[$i]." ";
				    }
			    }
					
					$result = $conn->prepare($sql);
			    for($i = 1; $i <= $count_fields; $i++){
			  		if (isset(${$field[$i]}) OR $field[$i] == 'file') {
			  			if ($field[$i] == 'file') $result->bindValue(':'.$field[$i], $file_new);
							else $result->bindValue(':'.$field[$i], ${$field[$i]});
						}
					}
					
					
					if ($result->execute()){
						$id = $conn->lastInsertId();
						
						if (isset($c_levels) && $c_levels){
							if (!$upload_path && isset($_POST['c_foldername']) && $_POST['c_foldername']){
								$foldername = NULL;
								if (isset($_POST['foldername']) && $_POST['foldername']){
									$foldername_title = trim(strip_tags(stripslashes(str_replace("'", "&#39;", $_POST['foldername']))));
									$foldername_url = url_slug($foldername_title);
									
									$sql_tmp = "SELECT guidv4 FROM ".$module."_levels WHERE url = :url LIMIT 1";
									$result_tmp = $conn->prepare($sql_tmp);
									$result_tmp->bindValue(':url', $foldername_url, PDO::PARAM_STR);
									$result_tmp->execute();
									if ($result_tmp->rowCount()){
										$arr_tmp = $result_tmp->fetch();
										$parent_guidv4 = array();
										$parent_guidv4[] = $arr_tmp['guidv4'];
									} else {
										
										if (isset($parent_guidv4) && is_array($parent_guidv4)){
											foreach ($parent_guidv4 AS $key => $value){
												$foldername_url = check_url($module.'_levels', $foldername_url);
												$foldername_guidv4 = guidv4();
												
												$foldername_c_delete_folder_content = 0;

												$sql_default = "SELECT c_delete_folder_content FROM ".$module."_levels WHERE guidv4 = :guidv4 LIMIT 1";
												$result_default = $conn->prepare($sql_default);
												$result_default->bindValue(':guidv4', $value, PDO::PARAM_STR);
												$result_default->execute();
												
												if ($result_default->rowCount()){
													$arr_default = $result_default->fetch();
													$foldername_c_delete_folder_content = $arr_default['c_delete_folder_content'];
												}
												
												$sql_sub = "INSERT INTO ".$module."_levels SET 
																		guidv4 = :guidv4, 
																		datetime = :datetime,  
																		language = :language, 
																		url = :url,
																		title = :title, 
																		parent_guidv4 = :parent_guidv4,
																		sortorder = '0',
																		c_active = '1',
																		c_delete_folder_content = :c_delete_folder_content ";
												$result_sub = $conn->prepare($sql_sub);
												
												$result_sub->bindValue(':guidv4', $foldername_guidv4, PDO::PARAM_STR);
												$result_sub->bindValue(':datetime', time(), PDO::PARAM_INT);
												$result_sub->bindValue(':language', $language_foldername, PDO::PARAM_STR);
												$result_sub->bindValue(':url', $foldername_url, PDO::PARAM_STR);
												$result_sub->bindValue(':title', $foldername_title, PDO::PARAM_STR);
												$result_sub->bindValue(':parent_guidv4', $value, PDO::PARAM_STR);
												$result_sub->bindValue(':c_delete_folder_content', $foldername_c_delete_folder_content, PDO::PARAM_STR);
												$result_sub->execute();
												
												$parent_guidv4[$key] = $foldername_guidv4;
											}
										} else {
											$foldername_url = check_url($module.'_levels', $foldername_url);
											$foldername_guidv4 = guidv4();
											$foldername_c_delete_folder_content = 0;

											$sql_default = "SELECT value FROM library_options WHERE title = 'c_delete_folder_content' LIMIT 1";
											$result_default = $conn->prepare($sql_default);
											$result_default->execute();
											
											if ($result_default->rowCount()){
												$arr_default = $result_default->fetch();
												$foldername_c_delete_folder_content = $arr_default['value'];
											}
											
											$sql_sub = "INSERT INTO ".$module."_levels SET 
																	guidv4 = :guidv4, 
																	datetime = :datetime,  
																	language = :language, 
																	url = :url,
																	title = :title, 
																	sortorder = '0',
																	c_active = '1',
																	c_delete_folder_content = :c_delete_folder_content ";
											$result_sub = $conn->prepare($sql_sub);
											
											$result_sub->bindValue(':guidv4', $foldername_guidv4, PDO::PARAM_STR);
											$result_sub->bindValue(':datetime', time(), PDO::PARAM_INT);
											$result_sub->bindValue(':language', $language_foldername, PDO::PARAM_STR);
											$result_sub->bindValue(':url', $foldername_url, PDO::PARAM_STR);
											$result_sub->bindValue(':title', $foldername_title, PDO::PARAM_STR);
											$result_sub->bindValue(':c_delete_folder_content', $foldername_c_delete_folder_content, PDO::PARAM_STR);
											$result_sub->execute();
											
											$parent_guidv4 = array();
											$parent_guidv4[] = $foldername_guidv4;
											
										}
						
									}
									
								}
							}
							
							
							$sql_sub = "DELETE FROM ".$module."_levels_links WHERE id_module = :id ";
							$result_sub = $conn->prepare($sql_sub);
							$result_sub->bindValue(':id', $id, PDO::PARAM_INT);
							$result_sub->execute();
							if (isset($parent_guidv4) && is_array($parent_guidv4)){
								foreach ($parent_guidv4 AS $key => $value){
									$sql_tmp = "INSERT INTO ".$module."_levels_links SET id_module = :id, guidv4 = :guidv4 ";
									$result_tmp = $conn->prepare($sql_tmp);
									$result_tmp->bindValue(':id', $id, PDO::PARAM_INT);
									$result_tmp->bindValue(':guidv4', $value, PDO::PARAM_STR);
									$result_tmp->execute();
								}
							}
						}
						
						
						$file_dir = "../".$module."/";
					  if (!is_dir($file_dir)) mkdir($file_dir);
					  $file_dir .= "original/";
						if (!is_dir($file_dir)) mkdir($file_dir);
						
						
						if (isset($c_webp) && $c_webp && !$is_svg){
							copy($file_data, $file_dir.'tmp_'.$file_new.'.'.$extension_old);
							resize($file_dir.'tmp_'.$file_new.'.'.$extension_old, $file_dir.$file_new);
							chmod($file_dir.$file_new, 0644);
							unlink($file_dir.'tmp_'.$file_new.'.'.$extension_old);
						} else {
							copy($file_data, $file_dir.$file_new);
							chmod($file_dir.$file_new, 0644);
						}
						
						
						
						unset($category);
						
						if ($id){
							$return['id'] = $id;
							$return['upload'] = array();
							$return['upload']['date'] = date("d.m.Y - H:i", $datetime);
							$return['upload']['label'] = LABEL_CLOCK;
							$return['upload']['filesize'] = formatSizeUnits($filesize);
							$return['upload']['dir'] = $file_dir;
							$return['upload']['file'] = $file_new;
							if (isset($c_language) && $c_language){
								$sql_tmp = "SELECT title FROM languages WHERE iso = :iso LIMIT 1";
								$result_tmp = $conn->prepare($sql_tmp);
								$result_tmp->bindValue(':iso', $language, PDO::PARAM_STR);
								$result_tmp->execute();
								if ($result_tmp->rowCount()){
									$arr_tmp = $result_tmp->fetch();
									$return['upload']['language'] = $arr_tmp['title'];
								}
							}
							$return['class'] = "success";
							$return['status'] = LABEL_SUCCESS;
							print json_encode($return);
						}
					}
				} else {
					$return['class'] = "error";
					$return['status'] = LABEL_ERROR;
					print json_encode($return);
				}
			}
		}
	}
}