<div id="main">
<?php
// side bar
require('F_mainsidebar.php');
?>
<!--MAIN PART-->
<div id="mainpartwrapper">
<div id="mainpart">
<?php
require('F_searchmenu.php');
?>
<div id="content-menu">				
		
<!--### IFRAME PART-->
<?php

// for SIMPLE SEARCH we only need to retrieve: fl=id, meta_*, text, th1


function process_post(){
	$q;
	if(isset($_POST)){	
		if(! empty($_POST['word'])){
			$multiword = preg_replace('/\s/','+', $_POST['word']);
			$q = $_POST['searchin']."%3A%22".urlencode($multiword)."%22";
			if(isset($_POST['cur_corpus'])){
				if($_POST['cur_corpus']!='full'){
					//echo "seen a corpus<br>";
					$q = $q."+AND+".$_SESSION['corpora'][$_POST['cur_corpus']]['query'];
				}
			}
		}
		else{		
			echo "Please indicate a search term!";
		}
		
	}
	return $q;
}

function runMyFunction($querystring, $s_server) {

	// jSON URL which should be requested
	$json_url = $s_server.'select?q='.$querystring.'&rows=500&wt=json';
	//$json_url = 'http://samos.sfs.uni-tuebingen.de:8080/solr/final/select?q='.$querystring.'&rows=500&wt=json';
	//pilot: $json_url = 'http://samos.sfs.uni-tuebingen.de:8080/solr/pilot/select?q='.$querystring.'&rows=500&wt=json';
	//$json_url = 'http://samos.sfs.uni-tuebingen.de:8080/solr/texts/select?q=meta_test_level_cefr%3AC1&fl=text_de&wt=json';

	$username = 'merlin';  // authentication
	$password = 'merlin23';  // authentication

	// Initializing curl
	$ch = curl_init( $json_url );

	// Configuring curl options
	$options = array(
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_USERPWD => $username . ":" . $password,  // authentication
	CURLOPT_HTTPHEADER => array('Content-type: application/json') 
	);

	// Setting curl options
	curl_setopt_array( $ch, $options );

	// Getting results
	$result = curl_exec($ch); // Getting jSON result string

	$jtest = json_decode($result, true);
	return $jtest;
}

//$q_tmp = process_post();
//echo "QUERY:".$q_tmp;

$json_results = runMyFunction(process_post(),$solr_server);
//echo $json_results['response']['docs'][1]['text'][0];

// the json result will always have (docs array) -- 
// "responseHeader":{}, 
// "response":{
//    ...,
//    "docs":[
//      {"id": "123", "_author_id":"234", ..., "text": ["blblbl"], }, 
//      {...}, 
//      {...}, ...

?>

<?php
	echo '<form class="inline" action="index.php" method="post">';
	echo '<input type="hidden" name="curscr" value="F_simplesearch.php">';
	echo '<button type="submit" name="new" value="">'.$trans['back_simple'][$_SESSION['lang']].'</button>';
	echo '</form>';
	
	if($json_results){
	$docs = $json_results['response']['docs'];
		if(! empty($_POST['word'])){
		
			$kwic = array();
			
			echo "<h4>".$trans['search_res_w'][$_SESSION['lang']]." '".$_POST['word']."'";
			if($_POST['cur_corpus']=="full"){
				echo " ".$trans['in'][$_SESSION['lang']]." ".$trans['full2'][$_SESSION['lang']];
			}
			else{
				echo " ".$trans['in'][$_SESSION['lang']]." ".$trans['corpus'][$_SESSION['lang']]." '".$_SESSION['corpora'][$_POST['cur_corpus']]['name']."'";
			}
			
			foreach($docs as $k => $v){
				// each $v is a doc entry
				//$v[$_POST['searchin']] e.g. is "text": ["blablabla"] or "th1": ["blablabla"]
				$doc_entry = $v;
				
				$id = $v['_author_id'];
				if(array_key_exists("th1",$v)){
					$current_th = $v['th1'][0];
				}
				else{
					$current_th = "EMPTY";
				}
				if(array_key_exists("th2",$v)){
					$current_th2 = $v['th2'][0];
				}
				else{
					$current_th2 = "EMPTY";
				}
				$current_ltext = $v['text'][0];
				$stretch = preg_replace('/(;|,|\.|:|\))/',' $1', $v[$_POST['searchin']][0]); // separate punctuation from words
				$stretch = preg_replace('/\\n/', ' ', $stretch); // replace newlines by space

				$words = explode(" ", $stretch); // creates an array of words
				$one = 0;
				foreach($words as $k => $v){
					if($v == $_POST["word"] || $v == strtolower($_POST["word"]) || strtolower($v) == $_POST["word"]){
						$one = 1;
						if($k >=4 && sizeof($words) > $k+4){  // search word has a context of at least four words to left and right
							$kwic_tmp = implode(" ", array($words[$k-4], $words[$k-3], $words[$k-2], $words[$k-1], "<span style='color:#0097d0; font-weight: bold;'>".$words[$k]."</span>", $words[$k+1], $words[$k+2], $words[$k+3], $words[$k+4]));
							
							$kwic[] = "<tr><td width='400px'><form name='showtext".$id."' action='index.php' method='post'><input type='hidden' name='curscr' value='F_showtext_metadata.php'><input type='hidden' name='searchin' value='".$_POST['searchin']."'><input type='hidden' name='th1'".' value="'.htmlspecialchars($current_th).'"'."><input type='hidden' name='th2'".' value="'.htmlspecialchars($current_th2).'"'."><input type='hidden' name='text'".' value="'.htmlspecialchars($current_ltext).'"'."><input type='hidden' name='author_id' value='".$id."'></form><a href='#' onclick='document.forms[".'"showtext'.$id.'"'."].submit();'>".$kwic_tmp."</a></td>
							
							<td width='250px'><form action='index.php' method='post'><input type='hidden' name='curscr' value='F_showtext_metadata.php'><button type='submit' name='metadata' value=".base64_encode(serialize($doc_entry)).'>'.$trans['view_metadata'][$_SESSION['lang']]."</button></form></td></tr>";
							
						}
						else if ($k < 4){ // less than four words of context to the left
							
							$kwic_tmp = implode(" ", array("---", "---","---", "---", "<span style='color:#0097d0; font-weight: bold;'>".$words[$k]."</span>", $words[$k+1], $words[$k+2], $words[$k+3], $words[$k+4]));
								
							$kwic[] = "<tr><td width='400px'><form name='showtext".$id."' action='index.php' method='post'><input type='hidden' name='curscr' value='F_showtext_metadata.php'><input type='hidden' name='searchin' value='".$_POST['searchin']."'><input type='hidden' name='th1'".' value="'.htmlspecialchars($current_th).'"'."><input type='hidden' name='th2'".' value="'.htmlspecialchars($current_th2).'"'."><input type='hidden' name='text'".' value="'.htmlspecialchars($current_ltext).'"'."><input type='hidden' name='author_id' value='".$id."'></form><a href='#' onclick='document.forms[".'"showtext'.$id.'"'."].submit();'>".$kwic_tmp."</a></td><td width='250px'><form action='index.php' method='post'><input type='hidden' name='curscr' value='F_showtext_metadata.php'><button type='submit' name='metadata' value=".base64_encode(serialize($doc_entry)).'>'.$trans['view_metadata'][$_SESSION['lang']]."</button></form></td></tr>";

						}
						else if($k >=4 && sizeof($words) <= $k+4){ // less than four words of context to the right
							//echo "small right<br>";
							$kwic_tmp = implode(" ", array($words[$k-4], $words[$k-3], $words[$k-2], $words[$k-1], "<span style='color:#0097d0; font-weight: bold;'>".$words[$k]."</span>", "---", "---","---", "---"));

							$kwic[] = "<tr><td width='400px'><form name='showtext".$id."' action='index.php' method='post'><input type='hidden' name='curscr' value='F_showtext_metadata.php'><input type='hidden' name='searchin' value='".$_POST['searchin']."'><input type='hidden' name='th1'".' value="'.htmlspecialchars($current_th).'"'."><input type='hidden' name='th2'".' value="'.htmlspecialchars($current_th2).'"'."><input type='hidden' name='text'".' value="'.htmlspecialchars($current_ltext).'"'."><input type='hidden' name='author_id' value='".$id."'></form><a href='#' onclick='document.forms[".'"showtext'.$id.'"'."].submit();'>".$kwic_tmp."</a></td><td width='250px'><form action='index.php' method='post'><input type='hidden' name='curscr' value='F_showtext_metadata.php'><button type='submit' name='metadata' value=".base64_encode(serialize($doc_entry)).'>'.$trans['view_metadata'][$_SESSION['lang']]."</button></form></td></tr>";
						}
						else{
							// check also for "OUT_OF_BOUND" on mix of left and right side
							echo "here<br>".$v."<br>";
						}
					}
					else{
						//echo "in Else ".$v."<br>";
					}
				}
				if(!$one){
					//echo "<br>No ".$_POST['word']." found in text: ". $stretch;
				}
			}
	
			echo "<h4>".count($kwic)." ".$trans['nb_hits'][$_SESSION['lang']]." ".$trans['in2'][$_SESSION['lang']]." ".count($docs)." ".$trans['docs'][$_SESSION['lang']]."</h4><br>";
			include 'F_paging_kwic.php';

		}
		else {
			
			// check this!
			echo "failed";
		}
		
	}
	else{
			echo "no results found";
	}

?>
<!--### IFRAME PART END-->  
</div>		  
</div>
</div>
<!--MAIN PART END-->
</div>