<?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 (isset($multi_update) && $multi_update){
	include($module."_multiupload_do.php");
} else if ($update) {

	if (isset($c_levels) && $c_levels){
		$parent_guidv4 = array();
		if (isset($_POST['parent_guidv4']) && $_POST['parent_guidv4']){
			foreach ($_POST['parent_guidv4'] AS $key => $value){
				$parent_guidv4[] = $value;
			}
			$parent_guidv4 = array_unique($parent_guidv4);
		}
	}

	if (isset($_POST['date'])) {
		$datetime = DateTime::createFromFormat('Y-m-d\TH:i', $_POST['date']);
		$datetime = $datetime->getTimestamp();
	}
	
  if (isset($link) && $link){
  	$linkstart = substr($link, 0, 1);
  	if ($linkstart != "/"){
			$linkstarts = substr($link, 0, 8);
			$linkstart = substr($link, 0, 7);
			if ($linkstarts != "https://"){
				if ($linkstart != "http://" AND $linkstart != "mailto:") $link = "http://".$link;
			}
		}
		if ($link == "http://" OR $link == "https://") unset($link);
	}
	
	if (isset($_POST['file_old']) && $_POST['file_old']){
		$file_old = stripcslashes(str_replace("'", "&#39;", str_replace("<br />","",str_replace("<br>","\n", $_POST['file_old']))));
	} else {
		$error = LABEL_ERROR_MANDATORY;
	}
	
	
	if(isset($_FILES['upload']) && file_exists($_FILES['upload']['tmp_name']) && is_uploaded_file($_FILES['upload']['tmp_name'])) {
		
		if (isset($_POST['filename']) && $_POST['filename']) $filename = trim(strip_tags(stripslashes(str_replace("'", "&#39;", $_POST['filename']))));
		
		$file_data = $_FILES['upload']['tmp_name'];
		$file_name = $_FILES['upload']['name'];
		$file_type = $_FILES['upload']['type'];
		$filesize = $_FILES['upload']['size'];
				
		$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;
		}
		
		if (!isset($file)){
			if (isset($filename) && $filename) $file_new = url_slug($filename).".".$extension_new;
			else if (isset($file_name) && $file_name) $file_new = url_slug(str_replace('.'.$extension, '', $file_name)).".".$extension_new;
		} else $file_new = url_slug($file).".".$extension_new;
	} else {
		$extension_tmp = explode(".", $file_old);
		$extension = end($extension_tmp);
		$file_new = url_slug($file).".".$extension;
	}
	
	
	$sql_tmp = "SELECT id FROM ".$module." WHERE file = :file AND id != :id LIMIT 1";
	$result_tmp = $conn->prepare($sql_tmp);
	$result_tmp->bindValue(':file', $file_new, PDO::PARAM_STR);
	$result_tmp->bindValue(':id', $id, PDO::PARAM_INT);
	$result_tmp->execute();
	if ($result_tmp->rowCount()){
		$error = LABEL_ERROR_ID_EXISTS;
		$file = $file_old;
	}
	
	
	if (!isset($error) && $update == 1){
		$c_lightbox_watermark_old = NULL;
		$c_thumbnails_watermark_old = NULL;
		
		$sql_tmp = "SELECT c_thumbnails_watermark, c_lightbox_watermark FROM ".$module." WHERE id = :id LIMIT 1";
		$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();
			$c_lightbox_watermark_old = ($arr_tmp['c_lightbox_watermark'] == '1') ? true : false;
			$c_thumbnails_watermark_old = ($arr_tmp['c_thumbnails_watermark'] == '1') ? true : false;
		}
		
		$sql = "UPDATE ".$module." SET ";
    for($i = 1; $i <= $count_fields; $i++){
    	if (isset(${$field[$i]})){
	    	if ($i == 1) $sql.= " ".$field[$i]." = :".$field[$i]." ";
	    	else $sql.= ", ".$field[$i]." = :".$field[$i]." ";
	    }
    }
    $sql.= " WHERE id = :id";
		
		$result = $conn->prepare($sql);
    for($i = 1; $i <= $count_fields; $i++){
  		if (isset(${$field[$i]})){
			  if ($field[$i] == 'file') $result->bindValue(':'.$field[$i], $file_new);
				else $result->bindValue(':'.$field[$i], ${$field[$i]});
			}
		}
		$result->bindValue(':id', $id);
		
		if ($result->execute()){
			
			if (isset($c_levels) && $c_levels){
				$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);
			if (!is_dir($file_dir."original/")) mkdir($file_dir."original/");
			
			
			$thumb_data = array();
			$lightbox_data = array();
			$sql_sub = "SELECT title FROM backend_modules GROUP BY title";
			$result_sub = $conn->query($sql_sub);
			while ($arr_sub = $result_sub->fetch()){
				if (check_table($arr_sub['title'].'_options')){
					$sql_tmp = "SELECT id FROM ".$arr_sub['title']."_options WHERE title = 'c_images' AND value = '1' ";
					$result_tmp = $conn->prepare($sql_tmp);
					$result_tmp->execute();
					if ($result_tmp->rowCount()){
						
						$thumb_module = $arr_sub['title'];
						
						$sql = "SELECT id, title, value FROM ".$thumb_module."_options WHERE title LIKE 'lightbox_%' ORDER BY id ASC";
						$result = $conn->prepare($sql);
						$result->execute();
						if ($result->rowCount()){
							while ($arr = $result->fetch()){
								if ($arr['title'] == 'lightbox_width' && $arr['value']) $lightbox_data[$thumb_module]['width'] = intval($arr['value']);
								else if ($arr['title'] == 'lightbox_width') $lightbox_data[$thumb_module]['width'] = NULL;
								else if ($arr['title'] == 'lightbox_height' && $arr['value']) $lightbox_data[$thumb_module]['height'] = intval($arr['value']);
								else if ($arr['title'] == 'lightbox_height') $lightbox_data[$thumb_module]['height'] = NULL;
							}
						}
						
						$sql = "SELECT id, title, value FROM ".$thumb_module."_options WHERE title LIKE 'image_width_%' OR title LIKE 'image_height_%' ORDER BY id ASC";
						$result = $conn->prepare($sql);
						$result->execute();
						if ($result->rowCount()){
							while ($arr = $result->fetch()){
								$key = str_replace('image_width_', '', str_replace('image_height_', '', $arr['title']));
								if (str_starts_with($arr['title'], 'image_width_') && $arr['value']) $thumb_data[$thumb_module][$key]['width'] = intval($arr['value']);
								else if (str_starts_with($arr['title'], 'image_width_')) $thumb_data[$thumb_module][$key]['width'] = NULL;
								else if (str_starts_with($arr['title'], 'image_height_') && $arr['value']) $thumb_data[$thumb_module][$key]['height'] = intval($arr['value']);
								else if (str_starts_with($arr['title'], 'image_height_')) $thumb_data[$thumb_module][$key]['height'] = NULL;
							}
						}
					}
					
				}
			}
			
			
			if ($file_old != $file_new){
				rename($file_dir."original/".$file_old, $file_dir."original/".$file_new);
				
				if (isset($lightbox_data) && is_array($lightbox_data)){
					foreach ($lightbox_data AS $lightbox_module => $resolution){
						$module_dir = $file_dir.$lightbox_module."/";
						if (is_file($module_dir.'lightbox/'.$file_old)){
							rename($module_dir.'lightbox/'.$file_old, $module_dir.'lightbox/'.$file_new);
						}				
					}
				}
				
				if (isset($thumb_data) && is_array($thumb_data)){
					foreach ($thumb_data AS $thumb_module => $resolutions_data){
						$module_dir = $file_dir.$thumb_module."/";
						foreach ($resolutions_data AS $thumb => $resolution){
							if (is_file($module_dir.'thumb'.$thumb.'/'.$file_old)){
								rename($module_dir.'thumb'.$thumb.'/'.$file_old, $module_dir.'thumb'.$thumb.'/'.$file_new);
							}
						}						
					}
				}
			}
			
			
			$c_lightbox_watermark = (isset($c_lightbox_watermark) && $c_lightbox_watermark == '1');
			$c_thumbnails_watermark = (isset($c_thumbnails_watermark) && $c_thumbnails_watermark == '1');
			
			if(isset($_FILES['upload']) && file_exists($_FILES['upload']['tmp_name']) && is_uploaded_file($_FILES['upload']['tmp_name'])) {
				if (is_file($file_dir."original/".$file_new)) unlink($file_dir."original/".$file_new);
				
				if (isset($c_webp) && $c_webp && !$is_svg){
					copy($file_data, $file_dir.'original/tmp_'.$file_new.'.'.$extension_old);
					resize($file_dir.'original/tmp_'.$file_new.'.'.$extension_old, $file_dir.'original/'.$file_new);
					chmod($file_dir.'original/'.$file_new, 0644);
					unlink($file_dir.'original/tmp_'.$file_new.'.'.$extension_old);
				} else {
					copy($file_data, $file_dir."original/".$file_new);
					chmod($file_dir."original/".$file_new, 0644);
				}
				
				if (isset($lightbox_data) && is_array($lightbox_data)){
					foreach ($lightbox_data AS $lightbox_module => $resolution){
						$module_dir = $file_dir.$lightbox_module."/";
						$width = NULL;
						$height = NULL;
						if (isset($resolution['width']) && $resolution['width']) $width = $resolution['width'];
						if (isset($resolution['height']) && $resolution['height']) $height = $resolution['height'];
						if (!is_dir($module_dir.'lightbox/')) mkdir($module_dir.'lightbox/');
						resize($file_dir.'original/'.$file_new, $module_dir.'lightbox/'.$file_new, $width, $height, $c_lightbox_watermark);
						chmod($module_dir.'lightbox/'.$file_new, 0644);
					}
				}
				
				if (isset($thumb_data) && is_array($thumb_data)){
					foreach ($thumb_data AS $thumb_module => $resolutions_data){
						$module_dir = $file_dir.$thumb_module."/";
						foreach ($resolutions_data AS $thumb => $resolution){
							$width = NULL;
							$height = NULL;
							if (isset($resolution['width']) && $resolution['width']) $width = $resolution['width'];
							if (isset($resolution['height']) && $resolution['height']) $height = $resolution['height'];
							if (!is_dir($module_dir.'thumb'.$thumb.'/')) mkdir($module_dir.'thumb'.$thumb.'/');
							resize($file_dir.'original/'.$file_new, $module_dir.'thumb'.$thumb.'/'.$file_new, $width, $height, $c_thumbnails_watermark);
							chmod($module_dir.'thumb'.$thumb.'/'.$file_new, 0644);
						}						
					}
				}
			} else {
				if (is_file($file_dir."original/".$file_new)){
					
					if (isset($lightbox_data) && is_array($lightbox_data)){
						foreach ($lightbox_data AS $lightbox_module => $resolution){
							$module_dir = $file_dir.$lightbox_module."/";
							if (!is_file($module_dir.'lightbox/'.$file_new) OR $c_lightbox_watermark != $c_lightbox_watermark_old){
								$width = NULL;
								$height = NULL;
								if (isset($resolution['width']) && $resolution['width']) $width = $resolution['width'];
								if (isset($resolution['height']) && $resolution['height']) $height = $resolution['height'];
								if (!is_dir($module_dir.'lightbox/')) mkdir($module_dir.'lightbox/');
								resize($file_dir.'original/'.$file_new, $module_dir.'lightbox/'.$file_new, $width, $height, $c_lightbox_watermark);
								chmod($module_dir.'lightbox/'.$file_new, 0644);
							}
						}
					}
				
					if (isset($thumb_data) && is_array($thumb_data)){
						foreach ($thumb_data AS $thumb_module => $resolutions_data){
							$module_dir = $file_dir.$thumb_module."/";
							foreach ($resolutions_data AS $thumb => $resolution){
								if (!is_file($module_dir.'thumb'.$thumb.'/'.$file_new) OR $c_thumbnails_watermark != $c_thumbnails_watermark_old){
									$width = NULL;
									$height = NULL;
									if (isset($resolution['width']) && $resolution['width']) $width = $resolution['width'];
									if (isset($resolution['height']) && $resolution['height']) $height = $resolution['height'];
									if (!is_dir($module_dir.'thumb'.$thumb.'/')) mkdir($module_dir.'thumb'.$thumb.'/');
									resize($file_dir.'original/'.$file_new, $module_dir.'thumb'.$thumb.'/'.$file_new, $width, $height, $c_thumbnails_watermark);
									chmod($module_dir.'thumb'.$thumb.'/'.$file_new, 0644);
								}
							}
						}
					}
				}
			}
			
			$update_parent = true;
		}
	}
}


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

if ((!isset($_POST['submit']) && isset($id)) OR (isset($_POST['submit']) && $_POST['submit'] != 'reload' && isset($id) && !isset($error))){	
	if (isset($c_levels) && $c_levels){
		$sql_tmp = "SELECT guidv4 FROM ".$module."_levels_links WHERE id_module = :id ORDER BY id";
		$result_tmp = $conn->prepare($sql_tmp);
		$result_tmp->bindValue(':id', $id, PDO::PARAM_INT);
		$result_tmp->execute();
		if ($result_tmp->rowCount()){
			$parent_guidv4 = array();
			while($arr_tmp = $result_tmp->fetch()){
				$parent_guidv4[] = $arr_tmp['guidv4'];
			}
		}
	}
	
}

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