<?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 (!$label){
		$error = LABEL_ERROR_MANDATORY;
	}
	
	if (!isset($error) && $update == 1){
		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 ($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 ($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;
}