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

	function add_document_status ( $doc_id, $status_id )
	{
		error_log ( "== add_document_status ==");
		error_log ( " doc_id : " .$doc_id."   status_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))
			{
				error_log ( " row[0] : " .$row[0]."   row[1] : " .$row[1] );
				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 )
	{
		error_log ( "=== create_document ===" );

		$pdo = getPDO ();

		$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

		$doc_master_id = $data['doc_master_id'];

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

			$s0 = $pdo->prepare ( $sql );
			$s0->bindParam ( ':name', $data['name'] );
			if ( $s0->execute () )
			{
				$d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );
				$doc_master_id = $d0[0]['id'];
			}
			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']);

		$valid_until_date = $data['valid_until_date'];

		if ( $valid_until_date == '' )
		 	$valid_until_date = '2999-12-31';

		 error_log ( "valid_until_date : ".$valid_until_date );
		
		error_log ( "Extension : " .$path_parts['extension'] );


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

		$fileField 		= ($path_parts['extension'] == "pdf")? "file" 			: "sourcefile";
		$realFileField 	= ($path_parts['extension'] == "pdf")? "realfilename" 	: "sourcerealfilename";

		$sql = "insert into document (
					doc_master_id,
					folder,
					creation_date,
					revision,
					label,
					uploadedby,
					comment,
					type,
					".$fileField.",
					".$realFileField.",
					valid_until_date,
					extern_link ) 
				values ( 
					:doc_master_id,
					:folder, 
					to_timestamp(:create_date||to_char(now(),'HH24MISS'),'YYYY-MM-DDHH24MISS'), 
					:revision, 
					:label, 
					:uploadedby, 
					:comment, 
					:type, 
					:prefix || currval(pg_get_serial_sequence('document', 'id')) || '.' || :suffix, 
					:realfilename, 
					to_timestamp(:valid_until_date||'235959','YYYY-MM-DDHH24MISS'), 
					:extern_link ) returning id, ".$fileField.";";
		// error_log ( "sql : " .$sql );

		$s0 = $pdo->prepare ( $sql );
		$s0->bindParam ( ':doc_master_id',		$doc_master_id 				);
		$s0->bindParam ( ':prefix',		 		$data['type'] 				);
		$s0->bindParam ( ':suffix',		 		$path_parts['extension'] 	);
		$s0->bindParam ( ':folder', 			$folder 					);
		$s0->bindParam ( ':create_date', 		$data['create_date'] 		);
		$s0->bindParam ( ':revision', 			$data['revision'] 			);
		$s0->bindParam ( ':label', 				$data['label'] 				);
		$s0->bindParam ( ':uploadedby', 		$data['uploaded_by'] 		);
		$s0->bindParam ( ':comment', 			$data['comment'] 			);
		$s0->bindParam ( ':type', 				$path_parts['extension'] 	);
		$s0->bindParam ( ':realfilename', 		$data['file_name_source'] 	);
		$s0->bindParam ( ':valid_until_date', 	$valid_until_date 			);
		$s0->bindParam ( ':extern_link', 		$data['extern_link'] 		);

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

		if ( $s0->execute () )
		{
			$d0 = $s0->fetchAll ( PDO::FETCH_ASSOC ); 

			$doc_id 	= $d0[0]['id'];
			$filename 	= $d0[0][$fileField];
		}
		else
		{
			error_log("Error SQL {$sql}");
		}


		//create document_link
		if($doc_id != -1)
		{
			$sql = "insert into document_link(type,ext_id,doc_id) values(:type, :ext_id,:doc_id);";

			$s0 = $pdo->prepare ( $sql );
			$s0->bindParam ( ':type', 	$data['type'] 	);
			$s0->bindParam ( ':ext_id', $data['ext_id'] );
			$s0->bindParam ( ':doc_id', $doc_id 		);


			if ( $s0->execute () )
			{
				if ( !is_dir($fullFolder) )
				{
					mkdir($fullFolder, 0777, true);
				}

				rename( $data['upload_folder'].'/'.$data['file_name'], $fullFolder.'/'.$filename);

				error_log ( "New document : " );
				error_log ( " Copy from : ".$fullFolder.'/'.$filename );
				error_log ( "        to : ".$GLOBALS["onlyoffice_temp_folder"] . "/".$filename );

    			copy ( $fullFolder.'/'.$filename, $GLOBALS["onlyoffice_temp_folder"] . "/".$filename );
			}
			else
				error_log("Error SQL {$sql}");

			$data['doc_id'] = $doc_id;
			add_document_status ( $doc_id, $data['status_id'] );
		}

		$taglist = $data['bquaad_tag'];

		$sql = "delete from quaadtag_doc_link where id_doclink in(select id from document_link where doc_id=:doc_id);";
		$s0 = $pdo->prepare ( $sql );
		$s0->bindParam ( ':doc_id', $doc_id );
		if ( $s0->execute () == false ) 
			error_log("Error SQL {$sql}");

		if ( $taglist != '' )
		{
			$tok = strtok($taglist, ",");

			while($tok !== false) 
			{
		 		$tagid = $tok;
		 		$sql ="insert into quaadtag_doc_link(id_doclink,id_quaadtag) values((select id from document_link where doc_id=:doc_id),:tagid);";
			 	$tok = strtok(",");

			 	$s0 = $pdo->prepare ( $sql );
			 	$s0->bindParam ( ':doc_id', $doc_id 	);
			 	$s0->bindParam ( ':tagid', 	$tagid 		);
			 	if ( $s0->execute () == false );
			 		error_log("Error SQL {$sql}");
		 	}
		}

		return $doc_id;
	}

	function add_document ( &$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'] 			= $_POST[$rowId.'_revision'];
 		$doc_data['create_date'] 		= $_POST[$rowId.'_create_date'];
 		$doc_data['status_id']	 		= $_POST[$rowId.'_status_id'];
 		$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['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"];
 		$doc_data['bquaad_tag'] 		=  $_POST[$rowId.'_bquaad_tag'];

 		$rowId = create_document($doc_data);

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

		return "inserted";
 	}


	function add_version ( &$rowId )
	{
		error_log ( "=== add_version ===" );

 		$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_DRAFT_ID;
 		$doc_data['upload_folder'] 		= $GLOBALS["upload_folder"];
 		$doc_data['document_storage'] 	= $GLOBALS["document_storage"];
		$doc_data['bquaad_tag'] 		= $_POST[$rowId.'_bquaad_tag'];

		error_log ( " doc_id : " .$doc_data['documentparent'] );

		//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;";

		error_log ( "sql : " .$sql );

		$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();

	 	$create_date 		= pg_escape_string($conn, $_POST[$rowId.'_create_date']);
	 	$valid_until_date 	= pg_escape_string($conn, $_POST[$rowId.'_valid_until_date']);
	 	// $createdatecondition =  "creation_date = case when (to_char(creation_date,'DD/MM/YYYY') = '{$create_date}') then creation_date else to_timestamp('{$create_date}'||to_char(now(),'HH24MISS'),'DD/MM/YYYYHH24MISS') end";
	 	$createdatecondition =  "creation_date = case when (to_char(creation_date,'YYYY-MM-DD') = '{$create_date}') then creation_date else to_timestamp('{$create_date}'||to_char(now(),'HH24MISS'),'YYYY-MM-DDHH24MISS') end";
	 	if($valid_until_date == '')
	 		$valid_until_date = "valid_until_date = to_timestamp('29991231235959','YYYYMMDDHH24MISS')";
	 	else
	 	{
		 	// $valid_until_date = "valid_until_date = to_timestamp('{$valid_until_date}235959','DD/MM/YYYYHH24MISS')";
		 	$valid_until_date = "valid_until_date = to_timestamp('{$valid_until_date}235959','YYYY-MM-DDHH24MISS')";
	 	}

	 	$name 			= pg_escape_string($conn, $_POST[$rowId.'_name']);
	 	$label 			= pg_escape_string($conn, $_POST[$rowId.'_label']);
	 	$comment 		= pg_escape_string($conn, $_POST[$rowId.'_comment']);
	 	$status_id 		= pg_escape_string($conn, $_POST[$rowId.'_status_id']);
	 	$extern_link 	= pg_escape_string($conn, $_POST[$rowId.'_extern_link']);
	 	$taglist 		= pg_escape_string($conn, $_POST[$rowId.'_bquaad_tag']);

	 	$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}', extern_link = '{$extern_link}', {$createdatecondition},{$valid_until_date} where id = {$rowId};";
	 	$sql .= "delete from quaadtag_doc_link where id_doclink in(select id from document_link where doc_id={$rowId});";
	 	if($taglist != '')
	 	{
			$tok = strtok($taglist, ",");

			while($tok !== false) 
			{
				$tagid = $tok;
				$sql.="insert into quaadtag_doc_link(id_doclink,id_quaadtag) values((select id from document_link where doc_id={$rowId}),{$tagid});";
				$tok = strtok(",");
			}
	 	}

	 	pg_query($conn, $sql);

	 	add_document_status ( $rowId, $status_id );
	 	
	 	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++ )
	{
		$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":
				error_log ( " inserted..." );
				if($_POST[$newrowId.'_documentmode'] == 'newdocument')
				{
					$action = add_document($newrowId);
				}
				else
				{
					$action = add_version($newrowId);
				}
				break;

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

   			case "updated":
   				error_log ( " 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;
?>