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

$template_source_to_save = false;
$template_source = NULL;


if ($update) {
	
	if ($action != 'quick'){
		if (!$label){
			$error = LABEL_ERROR_MANDATORY;
		}

		if (!isset($error) &&	isset($_POST['template_source']) &&	isset($_POST['template_source_path']) && isset($path) && $path) {
			$template_source_path = template_normalize_path($_POST['template_source_path']);
			$current_path = template_normalize_path($path);

			if ($template_source_path === $current_path) {
				$template_source_to_save = true;
				$template_source = str_replace("\r\n", "\n", $_POST['template_source']);

				$resolved_template_path = template_resolve_path($path);

				if (!$resolved_template_path) {
					$resolved_template_path = template_resolve_writable_path($path);
				}
				
				if (!$resolved_template_path) {
					$error = 'Der Template-Pfad ist ungültig.';
				} elseif (file_exists($resolved_template_path) && !is_writable($resolved_template_path)) {
					$error = 'Die Template-Datei ist nicht beschreibbar.';
				} else {
					$template_validate_error = NULL;
				
					if (!template_validate_php_source($template_source, $template_validate_error)) {
						$error = $template_validate_error;
					}
				}
			}
		}
	}
	
	if ($action == 'add' OR $action == 'copy'){
		$sql_check = "SELECT id FROM ".$module." WHERE id = :id ";
		$result_check = $conn->prepare($sql_check);
		$result_check->bindValue(':id', $_POST['id'], PDO::PARAM_INT);
		$result_check->execute();
		if ($result_check->rowCount()){
			$error = LABEL_ERROR_ID_EXISTS;
		}
	}
	
	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])));
			$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 (isset($_POST['group_start'])) {
				$group_start = str_replace("\r\n", "\n", $_POST['group_start']);
			}
			
			if (isset($_POST['group_end'])) {
				$group_end = str_replace("\r\n", "\n", $_POST['group_end']);
			}
			
			if (isset($_POST['row_start'])) {
				$row_start = str_replace("\r\n", "\n", $_POST['row_start']);
			}
			
			if (isset($_POST['row_end'])) {
				$row_end = str_replace("\r\n", "\n", $_POST['row_end']);
			}
			
			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]." ";
		    }
	    }
    	$sql.= ", id = :post_id ";
			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]});
				}
			}
    	$result->bindValue(':post_id', $_POST['id'], PDO::PARAM_INT);
			if ($action == 'edit') $result->bindValue(':id', $id);
			
			if ($result->execute()){
				if ($action != 'edit') $id = $conn->lastInsertId();
				
				if ($template_source_to_save && $template_source !== NULL) {
					$template_save_error = NULL;
				
					if (!template_save_source($path, $template_source, $template_save_error)) {
						$error = $template_save_error;
					}
				}
				
				
				if (!isset($error)) {
				
					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";
					} elseif ($_POST['id'] != $id) {
				    $url_form = "popup_form.php?module=".$module."&backend_module=".$backend_module."&id=".$_POST['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 ($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;
}