<?php
    // Set up convenience variables:
    $account = $this->auth()->getManager();
    $user = $account->isLoggedIn();
    $openUrl = $this->openUrl($this->driver, 'holdings');
    $openUrlActive = $openUrl->isActive();
    // Account for replace_other_urls setting
    $urls = $this->record($this->driver)->getLinkDetails($openUrlActive);
    $data = $this->driver->getRawData();
    $title = $this->driver->getMainTitle() ;
    $u = array();
    if (isset ($data['voevzlink'])) {
                        $u[] = array('url' => $data['voevzlink'][0], 'desc' => "Volltext");
    }

    foreach ($urls as $current)   {
        if (strncmp($current['url'],"https://bibb-dspace.bibb.de/handle", strlen("https://bibb-dspace.bibb.de/handle")) == 0)   continue;

        if (strncmp($current['url'],"https://bibb-dspace.bibb.de/jspui/handle", strlen("https://bibb-dspace.bibb.de/jspui/handle")) == 0)   continue;

        if (strncmp($current['url'],"https://bibb-dspace.bibb.de/rest/bitstreams", strlen("https://bibb-dspace.bibb.de/rest/bitstreams")) == 0) {
                if (isset ($data['voevzlink'])) continue;
        	if (($start = strrpos($current['url'], "(")) !== false)  { 
			$u[] = array('url' => trim(substr($current['url'],0, $start -1)),  'desc' => substr($current['url'],$start+1, strrpos($current['url'],")") - $start -1) );
                //	$u[] = array('url' => $current['url'],  'desc' => substr($current['url'],$start+1, strrpos($current['url'],")") - $start -1) );
		   } else {
			$u[] = array('url' => $current['url'], 'desc' => "Volltext");
		}
                continue;
        }

	if (strncmp($current['url'],"www.bibb.de/", strlen("www.bibb.de/")) == 0) { 
		$u[] = array('url' => "https://" .$current['url'], 'desc' => "Volltext"); 
		continue; 
	}

	if (strncmp($current['url'],"urn:nbn:de:", strlen("urn:nbn:de:")) == 0) {
        	// $u[] = array('url' => 'https://nbn-resolving.org/' .urlencode($current['url']), 
        	//	     'desc' => "URN"); 
		continue; 
        }
        if (strncmp(strtolower($current['url']),"doi:", strlen("doi:")) == 0)  {
		// if (($start = strrpos($current['url'], "(")) !== false) $current['url'] = trim(substr($current['url'],0, $start));
                // if (($start = strrpos($current['url'], "[")) !== false) $current['url'] = trim(substr($current['url'],0, $start));
                // $u[] = array('url'  => "https://doi.org/" .urlencode(trim(substr($current['url'], strlen("doi:")))),
                //             'desc' => "DOI" );
		continue;
        }

        if(strncmp(strtolower($current['url']),"http://dx.doi.org/", strlen("http://dx.doi.org/")) == 0){ 
                // if (($start = strrpos($current['url'], "(")) !== false) $current['url'] = trim(substr($current['url'],0, $start));
                // if (($start = strrpos($current['url'], "[")) !== false) $current['url'] = trim(substr($current['url'],0, $start));
		// $u[] = array('url'  => "https://doi.org/" .urlencode(trim(substr($current['url'], strlen("http://dx.doi.org/")))),
                //             'desc' => "DOI");
		continue;
	}

        if (($start = strrpos($current['url'], "(")) !== false) {
                $u[] = array('desc' => substr($current['url'],$start+1, strrpos($current['url'],")") - $start -1) ,
                             'url'  => trim(substr($current['url'],0, $start)));
		continue;
        }
        if (($start = strrpos($current['url'], "[")) !== false) {
                $u[] = array('desc' => substr($current['url'],$start+1, strrpos($current['url'],"])") - $start -1) ,
                             'url'  => trim(substr($current['url'],0, $start)));
		continue;
        }
        if (strncmp($current['url'],"http://dispatch.opac.d-nb.de/", strlen("http://dispatch.opac.d-nb.de/")) == 0) {
        	$u[] =array('url' => $current['url'] = "https://zdb-katalog.de/list.xhtml?t=" .urlencode("\"" .$title ."\"")  ."&key=tit",
        		    'desc'  => $current['desc'] = "\"" .$title ."\" in der ZDB"); 
		continue;
    	}	

	// RKE: Änderung wegen Datenbankzugang zu EBSCO 
   	$LoginRequired = false ; 
       //  if (((strpos($current['url'],"search.ebscohost.com/login.aspx") !== false) || (strpos($current['url'], "econtent.hogrefe.com"))) !== false || strpos($current['url'],"research.ebsco.com/linkprocessor/") !== false || strlen($accessRestrictions[0]) > 0) 
	if ((strncmp($current['url'],"https://search.ebscohost.com/login.aspx", strlen("https://search.ebscohost.com/login.aspx")) == 0) ||
	    (strpos($current['url'],"search.ebscohost.com/login.aspx") === true))	   
	{
        	$u[] = array('url' =>  trim($this->proxyUrl($current['url'])),
 			     'desc' => $current['desc']) ;
        	$LoginRequired = true ; 
		continue; 
	}
	// RKE: Änderung wegen Datenbankzugang zu EBSCO

	$u[] = array('url' => $current['url'] ,
		     'desc' => $current['desc']);

    }
    $urls = $u; 
    $offlineMode = $this->ils()->getOfflineMode();
    try {
        $holdings = $this->driver->getRealTimeHoldings();
    } catch (\VuFind\Exception\ILS $e) {
        $holdings = ['holdings' => []];
        $offlineMode = 'ils-offline';
    }
    // Set page title.
    $this->headTitle($this->translate('Holdings') . ': ' . $this->driver->getBreadcrumb());
?>

<?=$this->context($this)->renderInContext('librarycards/selectcard.phtml', ['user' => $this->auth()->isLoggedIn()]); ?>

<?php if (!empty($holdings['blocks'])):?>
	<div id="account-block-msg" class="alert alert-danger">
    		<?=$this->transEsc('account_block_options_missing', ['%%details%%' => implode('; ', $holdings['blocks'])]) ?>
  	</div>
<?php endif; ?>

<?=($offlineMode == "ils-offline") ? $this->render('Helpers/ils-offline.phtml', ['offlineModeMsg' => 'ils_offline_holdings_message']) : ''?>
<?php if (($this->ils()->getHoldsMode() == 'driver' && !empty($holdings['holdings'])) || $this->ils()->getTitleHoldsMode() == 'driver'): ?>
	<?php if ($account->loginEnabled() && $offlineMode != 'ils-offline'): ?>
    		<?php if (!$user): ?>
      			<div class="alert alert-info">
        			<a href="<?=$this->recordLinker($this->results)->getTabUrl($this->driver, 'Holdings')?>?login=true&amp;catalogLogin=true" data-lightbox><?=$this->transEsc("hold_login")?></a>
      			</div>
		   <?php elseif (!$user->cat_username): ?>
      			<div class="alert alert-info">
        			<?=$this->translate("hold_profile_html", ['%%url%%' => $this->recordLinker($this->results)->getTabUrl($this->driver, 'Holdings') . '?catalogLogin=true'])?>
      			</div>
		<?php endif; ?>
	<?php endif; ?>
<?php endif; ?>
<?php $holdingTitleHold = $this->driver->tryMethod('getRealTimeTitleHold'); if (!empty($holdingTitleHold)): ?>
  	<a class="placehold" data-lightbox title="<?=$this->transEsc('request_place_text')?>" href="<?=$this->recordLinker($this->results)->getRequestUrl($holdingTitleHold)?>"><i class="fa fa-flag" aria-hidden="true"></i>&nbsp;<?=$this->transEsc('title_hold_place')?></a>
<?php endif; ?>
<?php if (!empty($urls) || $openUrlActive): ?>
	<h3><?=$this->transEsc("Internet")?></h3>
  	<?php if (!empty($urls)): ?>
    		<?php foreach ($urls as $current): ?>
	 		<?php // RKE: Änderung wegen Datenbankzugang zu EBSCO ?>
   	 		<?php if (($LoginRequired == true) && ! $account->isLoggedIn()) : ?>
            			<?=$this->escapeHtml($current['desc'])?></a> &nbsp; &nbsp;
    			<?php endif; ?>
			<?php // ENDE RKE: Änderung wegen Datenbankzugang zu EBSCO ?>
    		<?php endforeach; ?>
  	<?php endif; ?>
  	<?php if ($openUrlActive): ?><?=$openUrl->renderTemplate()?><?php endif; ?>
<?php endif; ?>
<?php foreach ($holdings['holdings'] as $holding): ?>
	<h3>
  		<?php $locationText = $this->transEsc('location_' . $holding['location'], [], $holding['location']); ?>
  		<?php // RKE: Ergänzung wegen eBooks: Darstellung des Status aus Koha ?>
  		<?php $eBook = false; if (strcmp(strtolower($holding['location']), 'ebook') == 0) $eBook = true ; ?>
  
  		<?php if (isset($holding['locationhref']) && $holding['locationhref']): ?>
    			<a href="<?=$holding['locationhref']?>" target="_blank"><?=$locationText?></a>
 	  	  <?php else: ?>
    			<?=$locationText?>
 		<?php endif; ?>
	</h3>
	<table class="table table-striped" summary="<?=$this->transEsc('holdings_details_from', ['%%location%%' => $this->transEsc($holding['location'])]) ?>">
  	<?php $callNos = $this->tab->getUniqueCallNumbers($holding['items']); if (!empty($callNos)): ?>
  	<tr>
    		<th><?=$this->transEsc("Call Number")?>: </th>
    		<td width="50%">
      			<?php foreach ($callNos as $callNo): ?>
        			<?php if ($this->callnumberHandler): ?>
          				<a href="<?=$this->url('alphabrowse-home') ?>?source=<?=$this->escapeHtmlAttr($this->callnumberHandler) ?>&amp;from=<?=$this->escapeHtmlAttr($callNo) ?>"><?=$this->escapeHtml($callNo)?></a>
        		          <?php else: ?>
          				<?=$this->escapeHtml($callNo)?>
        			<?php endif; ?>
        			<br />
      			<?php endforeach; ?>
    		</td>
	</tr>
 	<?php endif; ?>
	<?php if (isset($holding['textfields'])): foreach ($holding['textfields'] as $textFieldName => $textFields): ?>
    		<?php //RKE: Mantis 187 ?>
    		<?php if (strcmp($textFieldname == "holdings_notes") == 0)  continue; ?>
    		<?php //RKE: ENDE Mantis 187 ?>
    		<tr>
      		<?php // Translation for summary is a special case for backwards-compatibility ?>
      			<th><?=$textFieldName == 'summary' ? $this->transEsc("Volume Holdings") : $this->transEsc(ucfirst($textFieldName))?>:</th>
      			<td>
        			<?php foreach ($textFields as $current): ?>
          				<?=$this->escapeHtml($current)?><br/>
        			<?php endforeach; ?>
      			</td>
    		</tr>
  	<?php endforeach; endif; ?>
  	<?php foreach ($holding['items'] as $row): ?>
    		<?php  // AJAX Check record?
      			$check = isset($row['check']) && $row['check'];
      			$checkStorageRetrievalRequest = isset($row['checkStorageRetrievalRequest']) && $row['checkStorageRetrievalRequest'];
      			$checkILLRequest = isset($row['checkILLRequest']) && $row['checkILLRequest'];
    		?>
    		<?php if (isset($row['barcode']) && $row['barcode'] != "") : ?>
      			<tr vocab="http://schema.org/" typeof="Offer">
        			<th><?=$this->transEsc("Copy")?> <?=$this->escapeHtml($row['number'])?></th>
        			<td>
          				<?php if (!$eBook && $row['reserve'] == "Y"): ?>
            					<link property="availability" href="http://schema.org/InStoreOnly" />
            					<?=$this->transEsc("On Reserve - Ask at Circulation Desk")?><br />
          				<?php endif; ?>
          				<?php if (isset($row['use_unknown_message']) && $row['use_unknown_message']): ?>
            					<span class="text-muted"><?=$this->transEsc("status_unknown_message")?></span>
          				  <?php else: ?>
            					<?php if (!$eBook && $row['availability']): ?>
              					<?php /* Begin Available Items (Holds) */ ?>

	     					<?php if (!$eBook && isset($row['enumchron']) && $row['enumchron']): ?>
                      					<?=$row['enumchron'] .": "?>
              					<?php endif;?>

              					<span class="text-success"><?=$this->transEsc("Available")?><link property="availability" href="http://schema.org/InStock" /></span>
              					<?php if (isset($row['link']) && $row['link']): ?>
                					<a class="<?=$check ? 'checkRequest ' : ''?>placehold" <?php if (!empty($row['linkLightbox'])): ?>data-lightbox <?php endif; ?>href="<?=$this->recordLinker($this->results)->getRequestUrl($row['link'])?>"><i class="fa fa-flag" aria-hidden="true"></i>&nbsp;<?=$this->transEsc($check ? "Check Hold" : "Place a Hold")?></a>
              					<?php endif; ?>
              					<?php if (isset($row['storageRetrievalRequestLink']) && $row['storageRetrievalRequestLink']): ?>
                					<a class="<?=$checkStorageRetrievalRequest ? 'checkStorageRetrievalRequest ' : ''?> placeStorageRetrievalRequest" data-lightbox href="<?=$this->recordLinker($this->results)->getRequestUrl($row['storageRetrievalRequestLink'])?>"><i class="fa fa-flag" aria-hidden="true"></i>&nbsp;<?=$this->transEsc($checkStorageRetrievalRequest ? "storage_retrieval_request_check_text" : "storage_retrieval_request_place_text")?></a>
              					<?php endif; ?>
              					<?php if (isset($row['ILLRequestLink']) && $row['ILLRequestLink']): ?>
                					<a class="<?=$checkILLRequest ? 'checkILLRequest ' : ''?>placeILLRequest" data-lightbox href="<?=$this->recordLinker($this->results)->getRequestUrl($row['ILLRequestLink'])?>"><i class="fa fa-flag" aria-hidden="true"></i>&nbsp;<?=$this->transEsc($checkILLRequest ? "ill_request_check_text" : "ill_request_place_text")?></a>
              					<?php endif; ?>
            			<?php else: ?>
             			   	<?php /* Begin Unavailable Items (Recalls) */ ?>
	     				<?php // RKE start: check if enmuchron is set ?>
	      				<?php if (isset($row['enumchron']) && $row['enumchron']): ?>
	              				<?=$row['enumchron'] .": "?>
	      				<?php endif;?>
	      				<?php // RKE end ?>
	     				<?php if (!$eBook) : ?>
	      					<span class="text-danger"><?=$this->transEsc($row['status'])?><link property="availability" href="http://schema.org/OutOfStock" /></span>
	      					<?php if (isset($row['returnDate']) && $row['returnDate']): ?>&ndash; <span class="small"><?=$this->escapeHtml($row['returnDate'])?></span><?php endif; ?>
              					<?php if (isset($row['duedate']) && $row['duedate']): ?>
                					&ndash; <span class="small"><?=$this->transEsc("Due")?>: <?=$this->escapeHtml($row['duedate'])?></span>
              					<?php endif; ?>
              					<?php if (isset($row['requests_placed']) && $row['requests_placed'] > 0): ?>
                					<span><?=$this->transEsc("Requests")?>: <?=$this->escapeHtml($row['requests_placed'])?></span>
              					<?php endif; ?>
	      					<?php if ($row['reserve'] != "X"): ?>
                  					<?php if (!$block && isset($row['link']) && $row['link']): ?>
                          					<a class="<?=$check ? 'checkRequest' : ''?> placehold" <?php if (!empty($row['linkLightbox'])): ?>data-lightbox <?php endif; ?>href="<?=$this->recordLinker($this->results)->getRequestUrl($row['link'])?>"><i class="fa fa-flag" aria-hidden="true"></i>&nbsp;<?=$this->transEsc($check ? "Check Recall" : "Recall This")?></a>
		  					<?php endif; ?>
						<?php endif ; ?>
              				<?php endif; ?>
            			<?php endif; ?>
            			<?php if (isset($row['item_notes'])): ?>
              				<div class="item-notes">
                				<b><?=$this->transEsc("Item Notes")?>:</b>
                				<ul>
                					<?php foreach ($row['item_notes'] as $item_note): ?>
                    						<li><?=$this->escapeHtml($item_note) ?></li>
                  					<?php endforeach; ?>
                				</ul>
              				</div>
            			<?php endif; ?>
          		<?php endif; ?>
          		<?php /* Embed item structured data: library, barcode, call number */ ?>
          		<?php if ($row['location']): ?>
            			<meta property="seller" content="<?=$this->escapeHtmlAttr($row['location'])?>" />
          		<?php endif; ?>
          		<?php if ($row['barcode']): ?>
            			<meta property="serialNumber" content="<?=$this->escapeHtmlAttr($row['barcode'])?>" />
          		<?php endif; ?>
          		<?php if ($row['callnumber']): ?>
            			<meta property="sku" content="<?=$this->escapeHtmlAttr($row['callnumber'])?>" />
          		<?php endif; ?>
         		<?php /* Declare that the item is to be borrowed, not for sale */ ?>
            			<link property="businessFunction" href="http://purl.org/goodrelations/v1#LeaseOut" />
            		<link property="itemOffered" href="#record" />
        	</td>
      </tr>
    <?php endif; ?>
  <?php endforeach; ?>
<?php if (!empty($holding['purchase_history'])): ?>
	<tr>
      		<th><?=$this->transEsc("Most Recent Received Issues")?>:</th>
      		<td>
        		<?php foreach ($holding['purchase_history'] as $current): ?>
          			<?=$this->escapeHtml($current['issue'])?><br/>
        		<?php endforeach; ?>
      		</td>
    	</tr>
<?php endif; ?>
</table>
<?php endforeach; ?>

<?php $history = $this->driver->getRealTimeHistory(); ?>
<?php if (is_array($history) && !empty($history)): ?>
	<h3><?=$this->transEsc("Most Recent Received Issues")?></h3>
		<table class="table table-striped">
  			<?php foreach ($history as $row): ?>
 				<tr><td><?=$this->escapeHtml($row['issue'])?></td></tr>
  			<?php endforeach; ?>
		</table>
<?php endif; ?>
