<?php

include ("frames_header.php"); 
include ("connection.php");

	if ( (!isset($_SESSION["login"]))or(!isset($_SESSION["pass"])) ) {
	    print "<center><strong>you need to <a href=\"login.php\">login</a> as an authorised curator to proceed.</strong>";
	    print '</center></body></html>';
		return;
	}

	echo '';

    $id=$_POST["ID"];
    $begin = $_POST["BEGIN"];
	$old_begin = $_POST["old_begin"];
	if(is_numeric($begin) && $begin!=0){	  
  	    
  	    $size=0;
  	    $khoueiry = "SELECT \"LENGTH\" FROM \"SEQUENCE\" WHERE \"MOL_ID\"=$id;";
  	    $stmt = pg_query($c,$khoueiry);
		if($row=pg_fetch_array($stmt)){
		  $size=$row["LENGTH"];
		}
  	    
  	    pg_query($c,"BEGIN") or die("<strong>ERROR </strong>".pg_last_error($c));

		//0 does not exist!
		$add=0;
		if(($begin<0) && ($begin+$length>=0)){ $add = 1; }  	      	    
		$khoueiry = "UPDATE \"PROMOTER\" SET \"BEGIN\"=$begin, \"END\"=".($begin+$size+$add)." WHERE \"PROMOTER_ID\"=$id;";
		pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
		
		
		$shift = $begin - $old_begin;
		if($old_begin>0 && $begin<0) { $shift++; } 
		if($old_begin<0 && $begin>0) { $shift--; } 
		
		//update all motif_coords for this promoter...
		$motif_coords = (array)null;		
		$khoueiry = "SELECT * FROM \"MOTIF_COORD\" WHERE \"PROMOTER_ID\"=$id";
		$stmt = pg_query($c,$khoueiry);
		while($row=pg_fetch_array($stmt)){
			$motif_coords[] = $row;
		}
		
		foreach ($motif_coords as $mot_coord){
			$nbegin = $mot_coord["BEGIN"]+$shift;
			if($mot_coord["BEGIN"]<0 && $nbegin>0) { $nbegin++; }
			if($mot_coord["BEGIN"]>0 && $nbegin<0) { $nbegin--; }
			
			$nend = $mot_coord["STOP"]+$shift;
			if($mot_coord["STOP"]<0 && $nend>0) { $nend++; }			
			if($mot_coord["STOP"]>0 && $nend<0) { $nend--; }
			
			$khoueiry = "UPDATE \"MOTIF_COORD\" SET \"BEGIN\"=".$nbegin.", \"STOP\"=".$nend." WHERE \"MOTIF_COORD_ID\"=".$mot_coord["MOTIF_COORD_ID"];
			pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
		}
	  			  		
		$test="SELECT \"IS_ADMIN\" from \"AUTHOR\" where \"LOGIN\"='".$_SESSION["login"]."'";
		$stest=pg_query($c,$test);
		$rtest=pg_fetch_array($stest);
		if ($rtest["IS_ADMIN"]=='y'){
	    	$khoueiry = "update \"ENTRY_ORIGIN\" set \"CURATOR_ID\"=".$_SESSION['curationauthor'].", \"CURATION_DATE\"=now() where \"BIO_ID\"='$id'";	  
		} else {
	    	$khoueiry = "update \"ENTRY_ORIGIN\" set \"ANNOTATOR_ID\"=".$_SESSION['curationauthor'].", \"ANNOTATION_DATE\"=now() where \"BIO_ID\"='$id'";		  
		}
		pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));

  	    pg_query($c,"COMMIT") or die("<strong>ERROR </strong>".pg_last_error($c));
	  			
		echo "<SCRIPT LANGUAGE=\"JavaScript\"> javascript:opener.location.reload(); self.close(); </script>";
	} else {
	  echo "<p>Non-numeric or incorrect coordinates</p>";
	}

include ("frames_footer.php"); 

?>
