<?php

/*
Author: Daniel Sobral
23/01/2007

Create a new regulatory region.

*/

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

	//Login Check
	if ( (!isset($_SESSION["login"]))or(!isset($_SESSION["pass"])) ) {
	    print "<strong>you need to <a href=\"login.php\">login</a> as an authorised curator to proceed.</strong>";
	    include ("frames_footer.php");
		return;
	}
  	
	//From a number, creates a Stable ID "REG + 8 digits"
	function create_stable_id($number){
		$digits = 1;
		$tmp = $number;
		while(floor($tmp / 10)>0){
			$digits++;
			$tmp = $tmp / 10;
		}
		$st_id = "REG";
		for($int = 1; $int<=8-$digits; $int++){
			$st_id = $st_id."0";
		}
		$st_id = $st_id.$number;
		return $st_id;
	} 	
	
	//Get the maximum stable_id
	$khoueiry="SELECT MAX(\"STABLE_ID\") AS \"STABLE_ID\" FROM \"PROMOTER\"";
	$stmt = pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
	if($row=pg_fetch_array($stmt)){ 
		//extract the number
		$max_stable_id = substr($row["STABLE_ID"],3);		
		$new_stable_id = create_stable_id($max_stable_id + 1);
	}
	
  	//Start transaction
	pg_query($c, "BEGIN") or die("<strong>ERROR </strong>".pg_last_error($c));
  	
	//Crate a new entity
	$khoueiry="INSERT INTO \"BIO_ENTITY\" (\"BIO_ID\", \"CURATED\" ) values ( nextval('\"S_BIO_ID\"'),'n')";	  	
	pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
	
	$name = "Random Name ".rand(1,100);

	$khoueiry = "INSERT INTO \"MOL_ENTITY\" (\"MOL_ID\", \"NAME\",\"TYPE\") VALUES (currval('\"S_BIO_ID\"'),'".$name."','regulatory_region');";
	pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
		            
   	$khoueiry = "INSERT INTO \"PROMOTER\" (\"STABLE_ID\",\"PRIVATE\", \"PROMOTER_ID\", \"NAME\", \"BEGIN\", \"END\", \"BASE_REG_ID\", \"IS_NATURAL\",\"TYPE\") VALUES ('$new_stable_id','y',currval('\"S_BIO_ID\"'),'$name',-1,-1,currval('\"S_BIO_ID\"'),'y','Unknown Activity');";   	
	pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
	

	//End in ENTRY_ORIGIN	
	$ann="SELECT \"AUTHOR_ID\" from \"AUTHOR\" where \"LOGIN\"='".$_SESSION["login"]."'";
	$sann=pg_query($c,$ann);
	$rann=pg_fetch_array($sann);
	$annotator_id=$rann["AUTHOR_ID"];
	
	$author=$_POST["author"];
	$khoueiry="INSERT INTO \"ENTRY_ORIGIN\"(\"AUTHOR_ID\",\"BIO_ID\",\"ENTRY_DATE\",\"ANNOTATOR_ID\",\"ANNOTATION_DATE\") values ('$annotator_id',currval('\"S_BIO_ID\"'),current_date,'$annotator_id',current_date)";
	pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
	
	//Finish Transaction
	pg_query($c, "COMMIT") or die("<strong>ERROR </strong>".pg_last_error($c));

	$khoueiry = "SELECT CURRVAL('\"S_BIO_ID\"');";
	$stmt=pg_query($c,$khoueiry); 
	$cur_prom_id=pg_fetch_result($stmt,0);	    
	
	//edit the new region, if successfull			
	print '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=reg-region-edit.php?id='.$cur_prom_id.'">'; 	    	
	  	
	include ("frames_footer.php"); 

?> 