<?php
	require_once('../../autoload.php');

	function add_document_status ( $doc_id, $status_id )
	{
		$conn = get_dbconnection();

		$sql = "select id,status_id from documentstatus where doc_id = {$doc_id} order by begdate desc limit 1;";

		if($query = pg_query($conn, $sql))
		{
			$sql2 ='';
			if($row = pg_fetch_row($query))
			{
				// if($row[1] != $data['status_id'])
				if($row[1] != $status_id)
				{
					$sql2 .= "update documentstatus set enddate = now() where id = {$row[0]};";
					$sql2 .= "insert into documentstatus(doc_id,begdate,status_id) values({$doc_id},now(), {$status_id});";
				}
			}
			else
			{
				$sql2 .= "insert into documentstatus(doc_id,begdate,status_id) values( {$doc_id},now(), {$status_id});";
			}
			pg_query($conn, $sql2);
		}
	}
	
	function create_document( $data )
	{
		$conn = get_dbconnection();

		$data['name'] = pg_escape_string ($conn,  $data['name']);
		$doc_master_id = $data['doc_master_id'];

		if($doc_master_id == '-1')
		{
			//create document master
			$sql = "insert into document_master(name) values('{$data['name']}') returning id";

			if ($query = pg_query($conn, $sql))
			{
				$row = pg_fetch_row($query);
				$doc_master_id = $row[0];
			}else{
				error_log("Error SQL {$sql}");
			}
		}else{
			//update document master
			$sql = "update document_master set name= '{$data['name']}' where id = {$doc_master_id};";
			pg_query($conn, $sql);
		}

		if($doc_master_id == -1)
			return -1;

		$data['label'] = pg_escape_string ($conn,  $data['label']);
		$data['comment'] = pg_escape_string ($conn,  $data['comment']);
		$data['uploaded_by'] = pg_escape_string ($conn,  $data['uploaded_by']);
		$data['file_name_source'] = pg_escape_string ($conn,  $data['file_name_source']);
		$path_parts = pathinfo($data['file_name']);


		//create document
		// $folder = $data['document_storage'].'/'.$data['type'];
		$folder 	= $data['type'];
		$fullFolder = $data['document_storage'] . '/' . $folder;

		$sql = "insert into document(doc_master_id,file,folder,creation_date,revision,label,uploadedby,comment,type,realfilename) values({$doc_master_id}";
		$sql .= ",'{$data['type']}_'||currval(pg_get_serial_sequence('document', 'id'))||'.{$path_parts['extension']}'";
		$sql .= ",'{$folder}'";
		$sql .= ",now()";
		$sql .= ",'{$data['revision']}'";
		$sql .= ",'{$data['label']}'";
		$sql .= ",'{$data['uploaded_by']}'";
		$sql .= ",'{$data['comment']}'";
		$sql .= ",'{$path_parts['extension']}'";
		$sql .= ",'{$data['file_name_source']}') returning id,file;";

		$doc_id = -1;
		$filename = '';

		if ($query = pg_query($conn, $sql))
		{
			$row = pg_fetch_row($query);
			$doc_id = $row[0];
			$filename = $row[1];
		}else{
			error_log("Error SQL {$sql}");
		}

		//create document_link
		if($doc_id != -1)
		{
			$sql = "insert into document_link(type,ext_id,doc_id) values('{$data['type']}','{$data['ext_id']}','{$doc_id}');";

			if (pg_query($conn, $sql))
			{
				if ( !is_dir ( $fullFolder ) )
				{
					mkdir ( $fullFolder, 0777, true );
				}

				if ( !rename ( $data['upload_folder'].'/'.$data['file_name'], $fullFolder.'/'.$filename ) )
				{
					error_log ( "Unable to rename : " . $data['upload_folder'].'/'.$data['file_name'] . "  to : " . $fullFolder.'/'.$filename );
				}

				unlink($data['upload_folder'].'/'.$data['file_name']);
			}else{
				error_log("Error SQL {$sql}");
			}
			$data['doc_id'] = $doc_id;
			add_document_status($doc_id,$data['status_id']);
		}
		return $doc_id;
	}

	function add_document ( &$rowId )
 	{
 		error_log ( "add_document..." );
 		error_log ( " document_storage : " .$GLOBALS["document_storage"] );

			$doc_data = array();
	 		$doc_data['type'] = $_POST[$rowId.'_document_type'];
	 		$doc_data['ext_id'] = $_POST[$rowId.'_ext_id'];
	 		$doc_data['name'] = $_POST[$rowId.'_name'];
	 		$doc_data['label'] = $_POST[$rowId.'_label'];
	 		$doc_data['comment'] = $_POST[$rowId.'_comment'];
	 		$doc_data['uploaded_by'] = $_POST[$rowId.'_uploaded_by'];
	 		$doc_data['revision'] = $_POST[$rowId.'_revision'];
	 		$doc_data['create_date'] = $_POST[$rowId.'_create_date'];
	 		$doc_data['file_name'] = $_POST[$rowId.'_devicedocumentfile_s_0'];
	 		$doc_data['file_name_source'] = $_POST[$rowId.'_devicedocumentfile_r_0'];
	 		$doc_data['status_id'] = STATUS_ACTIF_ID;
	 		$doc_data['doc_master_id'] = '-1';
	 		$doc_data['upload_folder'] = $GLOBALS["upload_folder"];
	 		$doc_data['document_storage'] = $GLOBALS["document_storage"];

	 		$count = $_POST[$rowId.'_devicedocumentfile_count'];
	 		$initialRowid = $rowId;
	 		for($i = 0; $i < $count;$i++)
	 		{
				$doc_data['file_name'] = $_POST[$initialRowid.'_devicedocumentfile_s_'.$i];
				$doc_data['file_name_source'] = $_POST[$initialRowid.'_devicedocumentfile_r_'.$i];
				$rowId = create_document($doc_data);
	 		}

	 		if($rowId == -1)
	  			return "invalid";

 			return "inserted";
 	}


	function add_version ( &$rowId )
	{
 		$doc_data = array();
 		$doc_data['type'] 				= $_POST[$rowId.'_document_type'];
 		$doc_data['ext_id'] 			= $_POST[$rowId.'_ext_id'];
 		// $doc_data['name'] 				= $_POST[$rowId.'_name'];
 		$doc_data['label'] 				= $_POST[$rowId.'_label'];
 		$doc_data['comment'] 			= $_POST[$rowId.'_comment'];
 		$doc_data['uploaded_by'] 		= $_POST[$rowId.'_uploaded_by'];
 		$doc_data['revision'] 			= '99';
 		$doc_data['create_date'] 		= $_POST[$rowId.'_create_date'];
		$doc_data['valid_until_date'] 	= $_POST[$rowId.'_valid_until_date'];
  		$doc_data['extern_link'] 		= $_POST[$rowId.'_extern_link'];
 		$doc_data['file_name'] 			= $_POST[$rowId.'_devicedocumentfile_s_0'];
		$doc_data['file_name_source'] 	= $_POST[$rowId.'_devicedocumentfile_r_0'];
		$doc_data['documentparent'] 	= $_POST[$rowId.'_documentparent'];
 		$doc_data['status_id'] 			= STATUS_ACTIF_ID;
 		$doc_data['upload_folder'] 		= $GLOBALS["upload_folder"];
 		$doc_data['document_storage'] 	= $GLOBALS["document_storage"];
		$doc_data['bquaad_tag'] 		= $_POST[$rowId.'_bquaad_tag'];

		//cloture version documentparent
		//add_document_status
		$sql = "select d1.revision,d1.doc_master_id from document as d1, document as d2 where d2.id = {$doc_data['documentparent']} and d1.doc_master_id = d2.doc_master_id order by d1.revision desc limit 1;";
		$conn = get_dbconnection();

		if($query = pg_query($conn, $sql))
		{
			$row = pg_fetch_row($query);
			$doc_data['revision'] = $row[0] + 1;
			$doc_data['doc_master_id'] = $row[1];
		}
		else
		{
			error_log("Error SQL {$sql}");
		}
		
		add_document_status($doc_data['documentparent'],STATUS_OBSOLETE_ID);
 		$rowId = create_document($doc_data);

 		if($rowId == -1)
 	 		return "invalid";

  		return "inserted";
 	}


 	function update_row ( &$rowId )
 	{
   		$conn = get_dbconnection();
	 	$name = pg_escape_string($conn, $_POST[$rowId.'_name']);
	 	$label = pg_escape_string($conn, $_POST[$rowId.'_label']);
	 	$comment = pg_escape_string($conn, $_POST[$rowId.'_comment']);

	 	$sql = "update document_master set name = '{$name}' from document where document_master.id = document.doc_master_id and document.id = {$rowId};";
	 	$sql .= "update document set label = '{$label}', comment = '{$comment}' where id = {$rowId};";

	 	pg_query($conn, $sql);
	 	return "updated";
 	}

	// $dump=var_export($_POST,true);
	
		
	// echo "<data>";
	
	$action = 'unknown';
	$rowId 	= -1;
	
	$ids 	= explode(",",$_POST["ids"]);

	//for each row
	for($i=0; $i < sizeof($ids); $i++)
	{
		error_log ( "id[".$i."] : " .$ids[$i] );

		$rowId = $ids[$i]; //id or row which was updated
 		$newrowId = $rowId;

		//$newId = $rowId; //will be used for insert operation

		$mode 	= $_POST[$rowId."_!nativeeditor_status"]; //get request mode
		
		switch ( $mode )
		{
			case "inserted":
				if($_POST[$newrowId.'_documentmode'] == 'newdocument')
				{
					$action = add_document($newrowId);
				}
				else
				{
					$action = add_version($newrowId);
				}
				break;

			case "deleted":
				$action = delete_row($newrowId);
				break;

   			case "updated":
				$action = update_row($newrowId);
				break;

			default:
				break;
		}
				
		// echo "<action type='".$action."' sid='".$rowId."' tid='".$newrowId."'/>";
	}

	// echo "</data>";


	header('Content-type: application/json');

	$arr = array (
			"type"          => $action,
			"sid"			=> $rowId,
			"tid"			=> $newrowId
	);
	
	$result = json_encode ( $arr );

	echo $result;
?>