<?php	
	if(!isset($_SESSION)) session_start();
	include("loginCheckPoint.php");
	require_once("demosettings.php");
	include_once 'write_log.php';
	require_once 'sqlUtils.php';
	require_once 'parseUtils.php';
        require_once 'allConceptsData.php';
        global $whatsapps_ext;
	$userdetails = getUserDetails();	
	$canSeeAllUsers = getUserPermission(CAN_SHOW_ALL_USER);
	
	$dcid = filter_var($_REQUEST["dcid"] ?? $_REQUEST["docId"] ?? null, FILTER_SANITIZE_NUMBER_INT);
	if(empty($dcid)){
	    die("No docid was noted!");
	}
	
	$freetext = $_REQUEST["freetext"] ?? null;	
	$text = "";
	$spanDom = new DOMDocument();
	$xpathDom = null;
	$port = "2020";
	$directory = getDocMetadataFolder($dcid);
	$usersNotes = $_REQUEST["usersNotes"] ?? null;
	if (!empty($usersNotes) && strlen($usersNotes) > 0){
		$res = sqlQuery($mysqli, "SELECT user_notes FROM files where id=" . $dcid);
		if(!empty($res)){
			$row = $res->fetch_object();
			if(!empty($row)){
    			$user_notes_db = $row->user_notes;
    			$str = $user_notes_db ."<br><b>" . $userdetails['Username'] . "</b>: " . $usersNotes;
    			$str = $mysqli->real_escape_string($str);
    			
    			$query = "UPDATE files
    								   SET user_notes=\"$str\"
    								   WHERE id=" . $dcid;
    			
    			$res = sqlQuery($mysqli, $query);			
			}
		}
		$usersNotes = $str;
	}
	
	$userCondition = $canSeeAllUsers? "" : " AND username='" . $mysqli->real_escape_string($userdetails['Username']) . "'";
	$sql = "SELECT user_notes FROM files where id=" . $dcid . $userCondition;
	$res = sqlQuery($mysqli, $sql);
	if(empty($res)){
		die("User is not authorized to view this document");
	}
	else {
		$row = $res->fetch_object();
	
		$usersNotes = $row->user_notes ? !empty($row) : null;
		
		$res = sqlQuery($mysqli, "SELECT value AS emailid FROM emailid WHERE docId = " . $dcid);
		if ($res && $row = $res->fetch_object())
		$emailid = $row->emailid;
		
		if (!empty($emailid))
		{
		    $whatsapp_fromat = true; //special for "split" format - to orginize them on their own order
		    
			//$res = $mysqli->query("SELECT id, filename FROM files where emailid=$emailid");
			//fix select to include email attachments
			$res = sqlQuery($mysqli, "SELECT files.id, files.filename FROM files, emailid WHERE emailid.value=$emailid AND emailid.docId = files.id UNION SELECT id, filename FROM files WHERE filename LIKE 'email%.txt' AND parentFolderId IN (SELECT id FROM foldertree WHERE parentId = $emailid) ");
			while ($res && $row = $res->fetch_object())
			{
				$filename = $row->filename;
				$type = "Attachment";
				if (isFileNameEmailBody($filename))
				{
					$emailBodyId = $row->id;
					$filename = $type = "HtmlBody";
				}				
				if (isFileNameEmailMessage($filename))
				{
					$filename = $type = "Message";
				}
				$emailFile = array("id" => $row->id, "name" => $filename, "type" => $type);
					
				$ext = pathinfo($filename, PATHINFO_EXTENSION);
				
				if(!in_array($ext, $whatsapps_ext)){
				    $whatsapp_fromat = false;
				}
				
				if ($row->id == $dcid)
				{
					$currentEmailFile = $emailFile;
				}
				else if ($type != "HtmlBody") //html body is the origin of Message, this it shoudn't appear as a separate attachment
					$emailFiles[] = $emailFile;
			}
		}		
	}
	//get tags
	$res = sqlQuery($mysqli, "SELECT Name FROM filetags WHERE DocId = $dcid");
	if ($res)
	{
		while ($row = $res->fetch_object())
			$tags[] = $row->Name;
	}	
	
	//get filename and path
	$filePathName = docIdToFilePath($dcid, $mysqli, true);	
	
	$relatedDocs = getRelatedFiles($mysqli, $dcid);
	
	if(!empty($emailFiles)){
	    $emailFiles = getEmailsFiles($mysqli, $dcid, $relatedDocs);	//currently we don't have a UI for posts/comments - so temporarily ride on the existing email/attachments UI
	}

// 	$zipfilename = $directory . DIRECTORY_SEPARATOR . "Background_$dcid.zip";
// 	$zip = new ZipArchive;
// 	if (file_exists($zipfilename) && $zip->open($zipfilename) === TRUE) {
// 		$digestJson = $zip->getFromName("d_$dcid.txt");
		
// 		$newText = $zip->getFromName("n_$dcid.txt");
// 		$textDir = $zip->getFromName("t_$dcid.txt");
// 		$report = $zip->getFromName("r_$dcid.txt");	    
// 		$menuColorStyle = $zip->getFromName("m_$dcid.txt") ;	 
	    
// 	    //check if zip content was encoded in base64 (obsolete, so this check should be removed soon)
// 	    if ($textDir != "rtl" && $textDir != "ltr")
// 	    {
// 	    	$textDir = base64_decode($textDir);
// 	    	if ($textDir == "rtl" || $textDir == "ltr")
// 	    	{
// 	    		$menuColorStyle = base64_decode($menuColorStyle);
// 	    		$digestJson = base64_decode($digestJson);
// 	    		$newText = base64_decode($newText);
// 	    		$report = base64_decode($report);
// 	    	}
// 	    }
// 	    $zip->close();
// 	} elseif(is_dir("$sharedFolder/metadata")) { //for backward compatibility with older metada folders
// 	    write_to_log("ERROR", "Zip file failed to read:$zipfilename ");
// 	    write_to_log("INFO", "Possibly you forgot to override metadata_path to \$sharedFolder/metadata");
	    
// 	}
		
	
	$a = 1;

function formTextAsHTML($text)
{
    $tmp = str_replace("\n", "<br>", $text);
    return $tmp;
}

function getFirstCDATAChildText($element)
{
    $node = $element->firstChild;
    while ($node != null && $node->nodeType != XML_CDATA_SECTION_NODE) {
        $node = $node->nextSibling;
    }
    if ($node != null) {
        return $node->wholeText;
    }
    return "";
}
  
  ///////////////////////////////////////////////////
  // 
  // Add extra parameters to the document main tab
  //
  ///////////////////////////////////////////////////
  global $dropdownArr;
  global $hideFields, $shouldInsertPhrases;
  $documentParameters = array();
  foreach ($dropdownArr as $k => $v){
    if (($shouldInsertPhrases && $k == "phrases") || in_array($k, array('filetags','emotion')) ||
        (array_key_exists($k, $hideFields) && empty($hideFields[$k]))){
      continue;
    }
  	
  	$sql = "SELECT DISTINCT value from $k WHERE docid=$dcid";
  	$res = sqlQuery($mysqli, $sql);
  	$first = true;
  	while ($res && $row = $res->fetch_object())
  	{
  		if ($first){
  			$first = false;
  			$documentParameters[$v] = $row->value;
  		}else 
  		    $documentParameters[$v] .=  " | " . $row->value;
  	}
  }
  //add duplicate index
  $duplicate = 0;
  $sql = "SELECT duplicatedDocId FROM duplicate_files WHERE id=$dcid";
  $res = sqlQuery($mysqli, $sql); 
  $row = $res->fetch_object();
  if(!empty($row)){
      if ($row->duplicatedDocId > 0)
      	$duplicatedDocId = $row->duplicatedDocId;	
      else
      	$duplicatedDocId = $dcid;	
      $sql = "SELECT COUNT(id) AS c FROM duplicate_files WHERE duplicatedDocId=$duplicatedDocId";
      $res = sqlQuery($mysqli, $sql); 
      $row = $res->fetch_object();
      $duplicate = $row->c;
      if ($duplicate > 0){
          $documentParameters["Duplicated count"] = $duplicate;
      }
  }
  require_once 'parseUtils.php';
  require_once 'settings.php';
  $settings_class =  new Settings($mysqli, $username);
  $allConceptArrDB = $settings_class->getAllConceptsArr();
  $concept_class =  new AllConceptsData($mysqli, $allConceptArrDB, null, $username);

  if(!empty($digestJson)){
      $digestJson =  json_decode($digestJson);
  }
  
  
  
  $response = array();
  $response["menuColorStyle"] = $menuColorStyle ?? null;
  $response["digestJson"] = ($digestJson) ?? null;
  $response["textDir"] = $textDir ?? null;
  $response["newText"] = $newText ?? null;
  $response["report"] = $report ?? null;
  
  //if $whatsapp_format - order it by the order
//   if($whatsapp_fromat){
//       foreach($emailFiles as &$email){
//           $email_name = $email["name"];
//           $id = (int) filter_var($email_name, FILTER_SANITIZE_NUMBER_INT);
//           $email["order_id"] = (int) filter_var($email_name, FILTER_SANITIZE_NUMBER_INT);
//       }
//       usort($emailFiles, function ($item1, $item2) {
//           return $item1['order_id'] <=> $item2['order_id'];
//       });
//   }
  
  $response["emailFiles"] = $emailFiles ?? null;
  $response["relatedDocs"] = $relatedDocs ?? null;
  $response["currentEmailFile"] = $currentEmailFile ?? null;
  $response["usersNotes"] = $usersNotes ?? null;
  $response["tags"] = $tags ?? null;
  $response["fileName"] = $filePathName["fileName"] ?? null;
  $response["filePath"] = $filePathName["filePath"] ?? null;
  $response["DocumentParameters"] = $documentParameters ?? null;
  $response["isOrgText"] = getSystemSettingsProp($mysqli, "isUseOrgText") ?? null;
  $response["currentFlavor"] = AllConceptsData::get_flavor($mysqli);
  
  
  
  
	//lock document if it's not locked
	global $userdetails,$AUTH;
	$AUTH = getGroupsAuth();
	
	if (array_key_exists("canContribute", $AUTH[$userdetails['Group_ID']]['permissions'])){
	    if ($AUTH[$userdetails['Group_ID']]['permissions']["canContribute"] == true){
			  $res = isLockedDoc($mysqli, $dcid,$userdetails["Username"]);
			  if ($res["status"] === false)
			  	setLockDoc($mysqli, $dcid, $userdetails["Username"]);
		}
	}
	
	echo json_encode($response,JSON_UNESCAPED_SLASHES);
 	
 	
 	    
 
 ?>
