<?
    // 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 (strncmp($current['url'],"https://search.ebscohost.com/login.aspx", strlen("https://search.ebscohost.com/login.aspx")) == 0) {
        	$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()]); ?>

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

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

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

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

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