<?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($_POST['images_data'])) {
	$images_data = [];
	foreach ($_POST['images_data'] AS $key => $value){
		if ($key == 'link'){
		  if (isset($value) && $value){
		  	$linkstart = substr($value, 0, 1);
		  	if ($linkstart != "/"){
					$linkstarts = substr($value, 0, 8);
					$linkstart = substr($value, 0, 7);
					if ($linkstarts != "https://"){
						if ($linkstart != "http://" AND $linkstart != "mailto:") $value = "http://".$value;
					}
				}
				if ($value == "http://" OR $value == "https://") $value = "";
			}
		}
		$images_data[$key] = $value;
		$images_data[$key] = $value;
    $images_data[$key]['c_enlarge'] = $value['c_enlarge'] ?? 0;
	}
	$images_data = media_duplicates($images_data);
}

if (isset($_POST['images_data_ph'])) {
	foreach ($_POST['images_data_ph'] AS $key => $value){
		$images_data_ph[$key] = $value;
	}
	$images_data_ph = media_duplicates($images_data_ph);
}

if (isset($_POST['files_data'])) {
	foreach ($_POST['files_data'] AS $key => $value){
		$files_data[$key] = $value;
	}
	$files_data = media_duplicates($files_data);
}

if (isset($_POST['links_data'])) {
	foreach ($_POST['links_data'] AS $key => $value){
		$links_data[$key] = $value;
	}
}

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 ($action != 'quick'){
		if (!$title OR ($c_languages AND !$language) OR ((isset($c_templates) && $c_templates) AND !$id_template)){
			$error = LABEL_ERROR_MANDATORY;
		}
	}

	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($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 == 'parent_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($value)){
					$sql_tmp = "INSERT INTO ".$level_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();
					$sql_tmp = "SELECT title FROM ".$module."_levels WHERE guidv4 = :guidv4 ";
					$result_tmp = $conn->prepare($sql_tmp);
					$result_tmp->bindValue(':guidv4', $value, PDO::PARAM_STR);
					$result_tmp->execute();
					if ($result_tmp->rowCount()){
						$arr_tmp = $result_tmp->fetch();
						print $arr_tmp['title'];
					}
				}
			} 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 = "UPDATE ".$module." SET ";
			} else {
				$sql = "INSERT INTO ".$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]." ";
		    }
	    }
			if ($action == 'edit') $sql.= " WHERE id = :id";
			
			$result = $conn->prepare($sql);
	    for($i = 1; $i <= $count_fields; $i++){
	  		if (isset(${$field[$i]})){
					$result->bindValue(':'.$field[$i], ${$field[$i]});
				}
			}
			if ($action == 'edit') $result->bindValue(':id', $id);
			
			if ($result->execute()){
				if ($action != 'edit') $id = $conn->lastInsertId();
				
				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();
						}
					}
				}
				
				if (isset($c_images) && $c_images){
					include('includes/function/images.php');
				}
				if (isset($c_files) && $c_files){
					include('includes/function/files.php');
				}
				if (isset($c_links) && $c_links){
					include('includes/function/links.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) || (!empty($update_parent))) {
					include('includes/function/reload.php');
				}
			}
		}
	}
}


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($c_images) && $c_images){
		$sql_tmp = "SELECT id_media, sortorder, title, alt, photographer, text, source, copyright, link, linktext, r_position_inside, r_position_outside, c_enlarge 
								FROM ".$module."_images WHERE id_module = :id ORDER BY sortorder";
		$result_tmp = $conn->prepare($sql_tmp);
		$result_tmp->bindValue(':id', $id, PDO::PARAM_INT);
		$result_tmp->execute();
		if ($result_tmp->rowCount()){
			$images_data = array();
			while($arr_tmp = $result_tmp->fetch()){
				$images_data[$arr_tmp['id_media']] = $arr_tmp;
				$sql_ph = "SELECT title, alt, photographer, text, source, copyright, link, linktext FROM images WHERE id = :id LIMIT 1";
				$result_ph = $conn->prepare($sql_ph);
				$result_ph->bindValue(':id', $arr_tmp['id_media'], PDO::PARAM_INT);
				$result_ph->execute();
				if ($result_ph->rowCount()){
					$arr_ph = $result_ph->fetch();
					$images_data_ph[$arr_tmp['id_media']] = $arr_ph;
				}
			}
		}
	}
	
	if (isset($c_files) && $c_files){
		$sql_tmp = "SELECT id_media, sortorder, text FROM ".$module."_files WHERE id_module = :id ORDER BY sortorder";
		$result_tmp = $conn->prepare($sql_tmp);
		$result_tmp->bindValue(':id', $id, PDO::PARAM_INT);
		$result_tmp->execute();
		if ($result_tmp->rowCount()){
			$files_data = array();
			while($arr_tmp = $result_tmp->fetch()){
				$files_data[$arr_tmp['id_media']] = $arr_tmp;
			}
		}
	}
	
	if (isset($c_links) && $c_links){
		$sql_tmp = "SELECT sortorder, link, linktext FROM ".$module."_links WHERE id_module = :id ORDER BY sortorder";
		$result_tmp = $conn->prepare($sql_tmp);
		$result_tmp->bindValue(':id', $id, PDO::PARAM_INT);
		$result_tmp->execute();
		if ($result_tmp->rowCount()){
			$links_data = array();
			while($arr_tmp = $result_tmp->fetch()){
				$links_data[$arr_tmp['sortorder']] = $arr_tmp;
			}
		}
	}
}

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