<?php

/**
 * this view creates hitlist with SOLR query
 * <br/><br/>
 * @author Gabriele Droege, Sybille Buers, Patricia Kelbert (BGBM, GGBN/DNA Bank Network) <contact@dnabank-network.org>
 * @version 1.0
 * @package View
 * @var $this SearchController
 * @var $model SearchForm
 * @var $shownAttributes an array of the attributes of the record, that should be shown
 * @var $keyForLink the attribute name, that will be clickable
 * @var $form SearchForm containing all field values
 * @var $response SolrObject containing the matching units from the search
 * @var $recordFilters the attributes that will be used to find record(s) e.g. unitID
 * @var $requestString request sent to SOLR server
 * @copyright Copyright © 2011 DNA Bank Network https://www.dnabank-network.org
 * <br/>The contents of this file are subject to the Mozilla Public License Version 1.1
 * @filesource
 * @license https://www.mozilla.org/MPL/ MPL
 */
use yii\helpers\Html;
use yii\helpers\Url;

use yii\web\View;
use app\models\SearchForm;
use kartik\widgets\ActiveForm;


use app\controllers\SearchController;
use common\models\CreateFormManager;
use yii\bootstrap\Modal;
use yii\widgets\Pjax;
use yii\web\Request;
use common\models\AccountForm;
use common\models\CartForm;
use kartik\form\ActiveField;

?>

<script type="text/javascript">

        $(document).ready(function(){
                   $(".dropDownLabel" ).change(function(){
                           
//                         alert(this.value+"  "+$( this ).attr("id2"));
                           var $chosen=$(this).value;
                                // hide all input fields...
                                $(".hasSelectableLabel_".concat($( $(this) ).attr("id2"))).hide();
                                $(".hasSelectableLabel_".concat($( $(this) ).attr("id2"))).val("");
                                // ... and show the chosen one
                                $("#SearchForm_".concat($chosen)).show();
                           event.preventDefault();
                           return false;                           
                        });

                   $('form').submit(function(e){
                       var filled=false;
                       $("form input[type=text]").each(function(){
                               var input=$(this);
                               if ($.trim( input.val()).length >0)
                                       filled=true;
                       });
                       

                       $("form select").each(function(){
                               var input=$(this);
                               if ($.trim(input.val()).length >0 && input.val() != "---" && $(this).attr("name").indexOf("Search")>-1){
                                       filled=true;
                               }
                               });

                       $("form input[type=radio]:checked").each(function(){
                               var input=$(this);
                               if ($.trim(input.val()).length >0 && input.val() != "include"){
                                       filled=true;
                               }
                               });
                       
                     if(!filled){
                                   alert("Fill at least one value ");
                                   return false;
                        }
                   else{
                       var emptyinputs = $(this).find('input').filter(function(){
                           return !$.trim($(this).val()).length;  // get all empty fields
                       }).prop('disabled',true);  
                       var emptyinputs = $(this).find('select').filter(function(){
                           return ($(this).val()) == ('---');  // get all empty fields
                       }).prop('disabled',true);  
                       <?php $_GET=[];?>
                   }
                   });
                 });
</script>

<?php if(isset($contentleft)) echo '"<div class="left-column">'.$contentleft.'</div>'; ?>
<?php if(isset($contentright)) echo '"<div class="right-column">'.$contentright.'</div>'; ?>

<!-- Start // used only if Login frame is activated in params.php -->
<div class="right-column">
<?php
if (Yii::$app->params ['useLogin'] && ( in_array ( Yii::$app->request->userIP, Yii::$app->params ['authorizedIPs'] ) || in_array("all", Yii::$app->params['authorizedIPs'] ))) {
	
	if (! \Yii::$app->user->isGuest) {
		// Get the predefined user settings from the database and pass them to javascript
		$settings=Yii::$app->user->identity->getUserSettings ();
		$page = $settings['default_hits_per_page'];
		$order = $settings['default_sort'];
		$asc = $settings['order'];
		$this->registerJs ( "var ops = " . json_encode ( $page ) . "; var or = " . json_encode ( $order ) . "; var asc = " . json_encode ( $asc ) . ";", View::POS_HEAD, 'my-options' );
		
		Yii::$app->session ['search'] = Yii::$app->request->url;
		Yii::$app->session ['records'] = $item_count;
		
		// Create a Pjax widget which does not change the url.
		// It contains two buttons one which saves the search and one which saves it by setting the
		// subscription boolean to true.
		Pjax::begin ( [ 
				'enablePushState' => false 
		] );
		?>
<div class="upper">
    <br />Subscribe to this search and get notified by email if new records
                        are added to the database.
                <?= Html::a("Subscribe", ['account/subscribe'], ['class' => 'btn btn-primary','data-pjax'=>'w1','timeout'=>'100000'])?>
        </div>
  <div class="lower">
                Save your search parameters without subscription
                <?= Html::a("Save search", ['account/save'], ['class' => 'btn btn-primary','data-pjax'=>'w1','timeout'=>'100000'])?>
        </div>


<?php
		
Pjax::end ();
		echo "<hr/>";
		Pjax::begin ( [ 
				'id' => 'shoppingCartContent',
				'enablePushState' => false 
		] );
		?>
				There are <?= $shoppingCart?> samples in your basket. <br /> <span
    class="hidden"><?= Html::a('View Basket', ['cart/addedlist'],['class' => 'btn btn-primary', 'id' => 'cartButton','timeout'=>'100000']);?></span>
<?php Pjax::end();?>
				<?= Html::button('Add to basket', ['class' => 'btn btn-primary', 'id' => 'addButton', 'title'=>'Add your selected samples to your basket']);?>
				<?= Html::a('View Basket', ['cart/cart'],['class' => 'btn btn-primary', 'name' => 'cart-button'])?>
					<?php
	} else {
		echo '<div class="right-column">'.Html::a('Log in',['site/login']).' to save your search parameters or to access the sample request system</div>';
		$this->registerJs ( "var ops = 25; var or = 0 ; var asc = 'asc';", View::POS_HEAD, 'my-options' );
	}
}
else 
	$this->registerJs ( "var ops = 25; var or = 0; var asc = 'asc';", View::POS_HEAD, 'my-options' );
	
echo "</div>";
// END // used only if Login frame is activated in params.php

$contentLeft = "";
$contentRight = "";
// $model = new SearchForm ();
// Yii::info ( "listView" );
$elements = $model->getParameters ();
function createFilters($doc, $recordFilters) {
	$docFilters = [ 
			'unitID' => $doc->unitID,
			'collectioncode' => $doc->collectioncode,
			'institutioncode' => $doc->institutioncode,
			'guid' => $doc->guid,
		//	'trick17ID' => $doc->trick17ID,
			'kindofunit' => $doc->sampletype 
	];
	$i = 1;
	return $docFilters;
}
function createRecordActionUrl($docFilters) {
	// Yii::info ( $docFilters );
	$docCP = array_slice ( $docFilters, 0, 4 );
	$nurl = Url::to ( array_merge ( [ 
			'search/record' 
	], $docCP ) );
	return $nurl;
}

$nl = "<br/>";

echo '<div class="jumbotron"><h2>';
echo $model->previewTitle;
		
echo '</h2></div> <div class="container">';
echo "<div class='big'>";
if (isset ( $response ))
	if ($response != null && $item_count) {
		if ($item_count >= Yii::$app->params['maxLines'])
			echo $item_count . " (or more) record";
		else
			echo $item_count . " record";
		if ($item_count > 1) {
			echo "s";
		}
		echo " found";
		if ($item_count >= Yii::$app->params['maxLines'])
			echo " -- The display is limited to ".Yii::$app->params['maxLines']." records.";
	} else
		echo "No records found.";

echo "</div><br/>Your search: <br/>";

$form = ActiveForm::begin ( [ 
		'method' => 'get',
		'action' => $submitURL,
		'enableClientValidation' => true,
		'validateOnSubmit' => true 
] );

$label = false;
$placeholder = true;
$cssClassSearchFields = 'complete_field searchfields';

CreateFormManager::prepareUpdateFormFields($form, $model, $elements, $this, $filters, $cssClassSearchFields, $selectionLists, $label, $placeholder);

$notUsedFields = [];
$notUsedElements = [];

echo '<div class="row">';

echo "<div class='col-lg-2'>";
echo Html::submitButton ( $model->refineSearchButtonLabel, [ 
		'class' => 'btn btn-primary' 
] );
echo "&nbsp;";
echo "</div><div class='col-lg-2'>";

$headerTitle = "Add search field";
$headerClass = "btn btn-primary";
$itemContent = $this->render ( '@common/views/search/searchFieldSelection', [
				'hideable_fields' => $model->getCompleteListFields (),
				'hidden_elements' => $model->getCompleteList ()
				], true );

CreateFormManager::AddAccordion($headerTitle, $headerClass, $itemContent);

echo "</div><div class='col-lg-2'>";
echo Html::button ( $model->newSearchButtonLabel, array (
		'onclick' => 'js:document.location.href="' . Yii::$app->getUrlManager ()->createUrl ( [ 
				'search/index' 
		] ) . '"',
		'class' => 'btn btn-primary' 
) );
echo "</div></div>";
$searchPage = Yii::$app->getUrlManager ()->createUrl ( [ 
		'search/index' 
] );

ActiveForm::end ();
?>
<!--- PARAM EINBAUEN START -->
</div>
<div class="left-column-inline">

</div>
<div class="right-colum"></div>
<div class="container">
<!--- PARAM EINBAUEN ENDE -->
<?php
$nameExtended = [ ];  // WFO Special
$content_array = array (
		"value" => array (),
		"url" => array (),
		"isocountrycode" => array (),
		"unitID" => array (),
		"institutioncode" => array (),
		"collectioncode" => array (),
	//	"trick17ID" => array (),
	//	"kindofunit" => array (),
		"country" => array (),
		"collectors" => array (),
		"collectornumber" => array (),
		"gatheringyear" => array (),
	    "gatheringdate" => array (),
	//	"indexHerbarorium" => array (),
		"locality" => array (),
		"multimedia" => [],
		"guid"=>[]
);
// "associatedID" => []
if (isset ( $response ))
	foreach ( $response as $doc ) {
		if ($doc->fullScientificName == "") {
			if ($doc->familyName != "") {
				$value = $doc->familyName;
			} else {
				if ($doc->orderName != "") {
					$value = $doc->orderName;
				} else {
					if ($doc->className != "") {
						$value = $doc->className;
					} else {
						if ($doc->phylumName != "") {
							$value = $doc->phylumName;
						} else {
							if ($doc->kingdomName != "") {
								$value = $doc->kingdomName;
							} else
								$value = "no identification";
						}
					}
				}
			}
			array_push ( $content_array ["value"], $value );
		} else {
			$value = $doc->fullScientificName;
			array_push ( $content_array ["value"], $value );
		}
		$names = $doc->fullScientificName_nc;
		if (! empty ( $names ))
			foreach ( $names as $n ) {
				if ((strpos ( $n, "N/A" )) === false)
					array_push ( $nameExtended, $n );
			}
		asort ( $nameExtended );
		// if (is_array ( $doc ['upperUnitIDs'] )) {
		// array_push ( $content_array["associatedID"],implode($doc ['upperUnitIDs'],", "));
		// }
		// else array_push ( $content_array["associatedID"],"nothing");
		$filters = createFilters ( $doc, $recordFilters );
		$url = createRecordActionUrl ( $filters );
		array_push ( $content_array ["url"], $url );
		array_push ( $content_array ["isocountrycode"], $doc->isocountrycode );
        array_push ( $content_array ["locality"], $doc->locality );
        array_push ( $content_array ["gatheringdate"], $doc->gatheringdate );
		array_push ( $content_array ["unitID"], $doc->unitID );
	//	array_push ( $content_array ["trick17ID"], $doc->trick17ID );
		array_push ( $content_array ["institutioncode"], $doc->institutioncode );
		array_push ( $content_array ["collectioncode"], $doc->collectioncode );
		array_push ( $content_array ["guid"], $doc->guid );
	//	array_push ( $content_array ["kindofunit"], $doc->sampletype );
		array_push ( $content_array ["country"], $doc->country );
		array_push ( $content_array ["collectors"], $doc->collectors );
		
		$cn = $doc->collectornumbers_nc;
		if (sizeof ( $cn ) > 0) {
			$f = false;
			foreach ( $cn as $c ) {
				if ((strpos ( $c, "N/A" )) === false && (strpos ( $c, "s.n." )) === false) {
					array_push ( $content_array ["collectornumber"], $c );
					$f = true;
				}
			}
			if (! $f)
				array_push ( $content_array ["collectornumber"], "s.n." );
		} else
			array_push ( $content_array ["collectornumber"], $doc->collectornumber );
			// array_push ( $content_array ["collectornumber"], $doc->collectornumber );
		array_push ( $content_array ["gatheringyear"], $doc->gatheringyear );
	//	array_push ( $content_array ["indexHerbarorium"], $doc->indexHerbarorium );
		$imgF = false;
		$imgFilled = false;
		
		if ($doc->hasImage) { 
			if ( $doc->multimediaurl ) { 
				foreach ( $doc->multimediaurl as $murl ) {
					if ($murl != "N/A") {
						if (! $imgFilled) {
							if (strpos ( $murl, "http" ) === FALSE) {
								if (sizeof ( $doc->multimediaurl ) > 1)
									continue;
								else {
									$murl = "https://" . $murl;
									
									array_push ( $content_array ["multimedia"], "<a href='" . $murl . "' target='_blank'>yes</a>" );
									$imgF = true;
									$imgFilled = true;
								}
							} else {
								array_push ( $content_array ["multimedia"], "<a href='" . $murl . "' target='_blank'>yes</a>" );
								$imgF = true;
								$imgFilled = true;
							}
						}
					}
				}
			}
		}
		if (! $imgF)
			array_push ( $content_array ["multimedia"], "no" );
	}
if (isset ( $response )) {
	echo "<span class='info'><hr/>Click on a Scientific name to see the specimen's full details</span>";
	if (! empty ( $nameExtended ) && isset ( $filters ['fullScientificName'] ))
		echo "<br/>The query has been extended to the names " . implode ( ", ", array_unique ( $nameExtended ) ) . "<br/>";
	$form = ActiveForm::begin ( [ 
			'id' => 'form',
			'type' => ActiveForm::TYPE_INLINE,
			'enableAjaxValidation' => true,
			'enableClientScript' => true,
			'validateOnSubmit' => true,
			'validateOnType' => false,
			'validateOnChange' => false,
			'validationUrl' => [ 
					'multiunits/add' 
			] 
	] );
	echo "<table id='myTable3' class='table tablesorter table-striped table-bordered datatable'>
                <thead>
                <tr>
                             <th>Scientific name</th>
                              <th>Country</th>
                              <th>Observation Date</th>
                       		 <th>Observed by</th>";
                               //<th title='Collector number'>Col. no.</th>";
                       		//  <th title='Gathering year'>Year</th>
                     //  echo "<th title='Index Herbariorum code'>IH</th>
                      // 		 <th>Subcollection</th>
                       //         <th>Specimen ID</th>
                   /*	echo	"<th>Image</th>
                               		 <th>Institution code</th>
                           	<th>Collection code</th>
                               		
                                <th>Type</th> */
	// if (! Yii::$app->user->isGuest) {
	// echo "<th>Selected</th> ";
	// }
	echo "      
                </tr>
                        </thead>
                        <tbody>";
	
	for($i = 0; $i <= sizeof ( $content_array ["value"] ) - 1; $i ++) {
		echo "<tr>";
		$val = preg_replace ( '*\/*', 'SLASH', $content_array ["unitID"] [$i] . "---" . $content_array ["collectioncode"] [$i] . "---" . $content_array ["institutioncode"] [$i] );
		// Yii::info("VAL : ".$val);
		$val = str_replace ( "(", "PARO", $val );
		$val = str_replace ( ")", "PARF", $val );
		$val = str_replace ( ":", "DBLPT", $val );
		// Yii::info("VAL2 : ".$val);
		echo "<td><a href=\"" . $content_array ["url"] [$i] . "\">" . $content_array ["value"] [$i] . "</a></td>";
		echo "<td title='" . $content_array ["locality"] [$i] . "'>" . $content_array ["country"] [$i] . "</td>";
		// if (isset ( $content_array ["trick17ID"] [$i] ) && $content_array ["trick17ID"] [$i] != $content_array ["unitID"] [$i])
		// echo "<td>" . $content_array ["unitID"] [$i] . " (" . $content_array ["trick17ID"] [$i] . ")</td>";
		// else
        echo "<td>" . $content_array ["gatheringdate"] [$i] . "</td>";
		echo "<td>" . $content_array ["collectors"] [$i] . "</td>";
	//	echo "<td>" . $content_array ["collectornumber"] [$i] . "</td>";
	//	echo "<td>" . $content_array ["gatheringyear"] [$i] . "</td>";
		
	//	echo "<td>" . $content_array ["indexHerbarorium"] [$i] . "</td>";
	//	echo "<td>" . $content_array ["collectioncode"] [$i] . "</td>";
	//	echo "<td>" . $content_array ["unitID"] [$i] . "</td>";
	//	echo "<td>" . $content_array ["multimedia"] [$i] . "</td>";
		echo "</tr>";
	}
	echo "</tbody></table>";
	if ($item_count >10)
	echo "<div id='jumpdiv'><span id='jump'>Go to page</span> <input type='text' id='jumper'/></div><br/><br/><br/>";
	
	ActiveForm::end ();

}

/**
 * This function checks whether a sample is available for order.
 * 
 * @param unknown $line
 *        	an array containing the information on the sample
 * @return boolean true, if the sample can be ordered; false if it is missing, consumed or blocked.
 */
function isAvailable($line) {
	// sample missing or consumed
	if ($line ["disposition_clean"] === 'missing' || $line ['disposition_clean'] === 'consumed') {
		return false;
	} // sample still blocked
elseif (strtotime ( $line ['blockedUntil'] ) - time () > 0) {
		return false;
	} elseif ($line ['blocked'] == 'yes' or $line ['blocked'] == 'Yes') {
		return false;
	} else {
		return true;
	}
}
function handleCoordinates($filters,$key,$param, $selectionLists, $this, $model, $form, $selectedValue) {
	try {
		$latitudeFrom = $filters ['latitudeFrom'];
	} catch ( Exception $e ) {
		$latitudeFrom = NULL;
	}
	try {
		$latitudeTo = $filters ['latitudeTo'];
	} catch ( Exception $e ) {
		$latitudeTo = NULL;
	}
	try {
		$longitudeFrom = $filters ['longitudeFrom'];
	} catch ( Exception $e ) {
		$longitudeFrom = NULL;
	}
	try {
		$longitudeTo = $filters ['longitudeTo'];
	} catch ( Exception $e ) {
		$longitudeTo = NULL;
	}
	$hide_option = "";
	$hide_button = "<img src=\"" . Yii::$app->request->baseUrl . "/images/close.png \" parent_name=\"" . $key . "\" class=\"hide_button\" alt=\"close\"/>";
	$htmlOpts = [ 
			"name" => $param ['config'] ['name'],
			"attribute1" => "latitudeFrom",
			"attribute2" => "latitudeTo",
			"attribute3" => "longitudeFrom",
			"attribute4" => "longitudeTo",
			"attribute1value" => $latitudeFrom,
			"attribute2value" => $latitudeTo,
			"attribute3value" => $longitudeFrom,
			"attribute4value" => $longitudeTo,
			'type' => \kartik\field\FieldRange::INPUT_TEXT 
	];
	echo "<div class='complete_field searchfields' id='" . $key . "_area' " . $hide_option . ">";
	CreateFormManager::createField ( $this, $model, $form, $key, $param, $selectionLists, $htmlOpts, $selectedValue, $hide_option, $hide_button );
	echo $hide_button;
	echo "</div>";
}
function handleGatheringyear($filters,$key, $param, $selectionLists, $this, $model, $form, $selectedValue) {
	try {
		$collectionYearFrom = $filters ['collectionYearFrom'];
	} catch ( Exception $e ) {
		$collectionYearFrom = NULL;
	}
	try {
		$collectionYearTo = $filters ['collectionYearTo'];
	} catch ( Exception $e ) {
		$collectionYearTo = NULL;
	}
	$hide_option = "";
	$hide_button = "<img src=\"" . Yii::$app->request->baseUrl . "/images/close.png \" parent_name=\"" . $key . "\" class=\"hide_button\" alt=\"close\"/>";
	$htmlOpts = [ 
			"name" => $param ['config'] ['name'],
			"attribute1" => "collectionYearFrom",
			"attribute2" => "collectionYearTo",
			"attribute1value" => $collectionYearFrom,
			"attribute2value" => $collectionYearTo,
			"type" => \kartik\field\FieldRange::INPUT_TEXT 
	];
	echo "<div class='complete_field searchfields' id='" . $key . "_area' " . $hide_option . ">";
	CreateFormManager::createField ( $this, $model, $form, $key, $param, $selectionLists, $htmlOpts, $selectedValue, $hide_option, $hide_button );
	echo $hide_button;
	echo "</div>";
}
?>
<script>
                $(document).ready(function() {

                    //pageLength registered above
          			pageLength = ops;
          			order = or;
          			asc = asc;
                    //After form submit the invisible button in the pjax widget showing the shopping cart
              		//is triggerd manually.
              		$('#addButton').click(function(){
              			$("#form").submit();
              			$("#cartButton").click();
              		    });

          		    
                      var oTable =$('#myTable3').DataTable( {
                      	"autoWidth": false,
                         "pageLength": pageLength,
                          "order": [[order, asc]],
                         "oLanguage": {
                             "sSearch": "Filter records:",
                           },
                           "paging":true,
                           
                         } );
                $("[name='latitudeFrom']").each(function() {
                   var input=$(this);
               if ($.trim(input.attr("placeholder")).length >0)
                       if($.isNumeric(input.attr("placeholder"))){
                       input.val(input.attr("placeholder"));
                       }
               });
               $("[name='latitudeTo']").each(function() {
                   var input=$(this);
                       if ($.trim(input.attr("placeholder")).length >0)
                               if($.isNumeric(input.attr("placeholder"))){
                               input.val(input.attr("placeholder"));
                               }
                       });
               $("[name='longitudeTo']").each(function() {
                   var input=$(this);
                       if ($.trim(input.attr("placeholder")).length >0)
                               if($.isNumeric(input.attr("placeholder"))){
                            input.val(input.attr("placeholder"));
                               }
                       });
               $("[name='longitudeFrom']").each(function() {
                   var input=$(this);
                       if ($.trim(input.attr("placeholder")).length >0)
                               if($.isNumeric(input.attr("placeholder"))){
                                input.val(input.attr("placeholder"));
                               }
                       });  

               $(document).on( "click", '#jump',function(event) {
                    var target = $(event.target);
                    var page=0;
                    try{page=parseInt($("#jumper").val()-1) || 0;
                    }catch(e){page=0;}
                    var info = oTable.page.info();
                    if(page < 0)
                            page=0;
                    if(page>parseInt(info.pages))
                            page=parseInt(info.pages);
                    $("#jumper").val(page+1);
                    oTable.page(page).draw( false );
               });

               //After form submit the invisible button in the pjax widget showing the shopping cart
               //is triggerd manually.
               $('#addButton').click(function(){
                       $("#form").submit();
                       $("#cartButton").click();
                   });

               <?php if(!empty($radioB)):?>
               <?php foreach($radioB as $k=>$v):?>
               $("[name='SearchForm[<?php echo $k?>]']").each(function() {
					if($(this).val()=='<?php echo $v?>')
						$(this).prop("checked", true);
                   });
               <?php endforeach;?>
               <?php endif;?>

               $("#help").on('click', function(e)  {
            	    window.open('https://wiki.ggbn.org/ggbn/GGBN_Data_Portal_Explanations','_blank');
            	        });
           });
   
</script>
</div>