<?php
  // Set page title.
  $this->headTitle($this->translate('Advanced Search'));

  // Disable top search box -- this page has a special layout.
  $this->layout()->searchbox = false;

  // Set up breadcrumbs:
  $this->layout()->breadcrumbs = '<li>';
  $lastSearchLink = $this->searchMemory()->getLastSearchLink($this->transEsc('Search'));
  $this->layout()->breadcrumbs .= !empty($lastSearchLink)
    ? $lastSearchLink : $this->transEsc('Search');
  $this->layout()->breadcrumbs .= '</li> <li class="active">' . $this->transEsc('Advanced') . '</li>';

  // Set up saved search details:
  if (isset($this->saved) && is_object($this->saved)) {
    $searchDetails = $this->saved->getParams()->getQuery();
    if ($searchDetails instanceof \VuFindSearch\Query\Query) {
        // Not an advanced query -- ignore it.
        $searchDetails = $groups = false;
    } else {
        $groups = $searchDetails->getQueries();
    }
    $hasDefaultsApplied = $this->saved->getParams()->hasDefaultsApplied();
    $searchFilters = $this->saved->getParams()->getFilterList();
    $hiddenFilters = $this->saved->getParams()->getHiddenFilters();
  } else {
    $hasDefaultsApplied = $searchDetails = $searchFilters = $groups = false;
    $hiddenFilters = $this->searchtabs()->getHiddenFilters($this->searchClassId, true);
  }

  // Step 1: Load the javascript
  $this->headScript()->appendFile(
    isset($this->advancedSearchJsOverride) ? $this->advancedSearchJsOverride : 'advanced_search.js'
  );
  // Step 2: Build the page
  $this->headScript()->appendScript(
    $this->partial(
      isset($this->buildPageOverride) ? $this->buildPageOverride : 'search/advanced/build_page.phtml',
      ['options' => $this->options, 'searchDetails' => $searchDetails]
    )
  );

  // Collect previous search queries
  $setSearchGroups = [];
  $setGroupCount = 0;
  $setQueries = [];
  if (isset($searchDetails) && is_object($searchDetails)) {
    foreach ($searchDetails->getQueries() as $group=>$searchGroup) {
      $setSearchGroups[$group] = $searchGroup->isNegated() ? 'NOT' : $searchGroup->getOperator();
      if ($setGroupCount < $group) {
        $setGroupCount = $group;
      }
      if (!isset($setQueries[$group])) {
        $setQueries[$group] = [];
      }
      foreach ($searchGroup->getQueries() as $search) {
        $setQueries[$group][] = $search;
      }
    }
  }
?>

<?=$this->flashmessages()?>
<div role="search">
  <form name="searchForm" id="advSearchForm" method="get" action="<?=$this->url($this->options->getSearchAction())?>">
    <?php foreach ($hiddenFilters as $key => $filter): ?>
      <?php foreach ($filter as $value): ?>
        <input type="hidden" name="hiddenFilters[]" value="<?=$this->escapeHtmlAttr($key) . ':' . $this->escapeHtmlAttr($value)?>" />
      <?php endforeach; ?>
    <?php endforeach; ?>
    <div class="<?=$this->layoutClass('mainbody')?>">
      <?php $lastSort = $this->searchMemory()->getLastSort($this->searchClassId); ?>
      <?php if (!empty($lastSort)): ?>
        <input type="hidden" name="sort" value="<?=$this->escapeHtmlAttr($lastSort)?>" />
      <?php endif; ?>
      <div class="clearfix">
        <h2 class="pull-left flip"><?=$this->transEsc('Advanced Search')?></h2>
        <div id="groupJoin" class="form-inline pull-right flip">
          <label for="groupJoinOptions"><?=$this->transEsc("search_match")?>:</label>
          <select id="groupJoinOptions" name="join" class="form-control">
            <option value="AND"<?php if($searchDetails && $searchDetails->getOperator()=='ALL'):?> selected<?endif?>><?= $this->transEsc('group_AND') ?></option>
            <option value="OR"<?php if($searchDetails && $searchDetails->getOperator()=='OR'):?> selected<?endif?>><?= $this->transEsc('group_OR') ?></option>
          </select>
        </div>
      </div>
        <div class="advanced-and-buttons">
      <span id="groupPlaceHolder" class="hidden">
        <i class="fa fa-plus-circle" aria-hidden="true"></i>
        <a href="#" onClick="addGroup();return false"><?= $this->transEsc('add_search_group') ?></a>
      </span>
      <?php /* fallback to a fixed set of search groups/fields if JavaScript is turned off */ ?>
      <div class="no-js">
        <?php if(!empty($this->formOverride)): ?>
          <?=$this->formOverride ?>
        <?php else: ?>
          <?php for($group=0 ; $group<3 || $group<=$setGroupCount ; $group++): ?>
            <?php if($group == 0): ?>
              <div id="new_group_template">
            <?php endif; ?>
            <div id="group<?=$group ?>" class="adv-group">
              <div class="adv-group-terms">
                <label class="adv-group-label"><?=$this->transEsc("adv_search_label")?>:</label>
                <?php for($search=0 ; $search<3 || (isset($setQueries[$group]) && $search<count($setQueries[$group])) ; $search++): ?>
                  <?php if($group == 0 && $search == 0): ?>
                    <div id="new_search_template">
                  <?php endif; ?>
                  <div id="search<?=$group.'_'.$search ?>" class="adv-search">
                    <input name="lookfor<?=$group ?>[]" id="search_lookfor<?=$group.'_'.$search ?>" class="adv-term-input form-control" type="text"<?php if(isset($setQueries[$group][$search])):?> value="<?=$this->escapeHtml($setQueries[$group][$search]->getString())?>"<?endif;?>>
                    <select class="adv-term-type form-control" name="type<?=$group ?>[]">
                      <?php foreach ($this->options->getAdvancedHandlers() as $searchVal => $searchDesc): ?>
                        <option value="<?=$this->escapeHtml($searchVal)?>"<?php if(isset($setQueries[$group][$search]) && $searchVal == $setQueries[$group][$search]->getHandler()):?> selected<?endif;?>><?=$this->transEsc($searchDesc)?></option>
                      <?php endforeach; ?>
                    </select>
                    <a href="#" class="adv-term-remove hidden"></a>
                  </div>
                  <?php if($group == 0 && $search == 0): ?>
                      </div>
                    <span class="float-left">
                      <i class="fa fa-plus-circle search_place_holder hidden" aria-hidden="true"></i>
                      <a href="#" class="add_search_link hidden"><?=$this->transEsc("add_search")?></a>
                    </span>
                  <?php endif; ?>
                <?php endfor; ?>
              </div>
              <div class="adv-group-match">
                <label class="search_bool"><?=$this->transEsc("search_match")?>:&nbsp;</label>
                <select name="bool<?=$group ?>[]" id="search_bool<?=$group ?>" class="form-control">
                  <option value="AND"<?php if(isset($setSearchGroups[$group]) && 'AND' == $setSearchGroups[$group]):?> selected<?endif;?>><?=$this->transEsc("search_AND")?></option>
                  <option value="OR"<?php if(isset($setSearchGroups[$group]) && 'OR' == $setSearchGroups[$group]):?> selected<?endif;?>><?=$this->transEsc("search_OR")?></option>
                  <option value="NOT"<?php if(isset($setSearchGroups[$group]) && 'NOT' == $setSearchGroups[$group]):?> selected<?endif;?>><?=$this->transEsc("search_NOT")?></option>
                </select>
              </div>
              <a href="#" class="adv-group-close hidden"><i class="fa fa-close"></i> <?=$this->transEsc("del_search")?></a>
            </div>
            <?php if($group == 0): ?>
              </div>
            <?php endif; ?>
          <?php endfor; ?>
        <?php endif; ?>
      </div>
      <div class="adv-submit">
        <input class="clear-btn btn btn-default" type="button" value="<?= $this->transEsc('Clear')?>">
	<span style="padding-left: 17em; vertical-align:baseline;"> </span>
                    <input type="checkbox" <?=$isSelected ? 'checked="checked"' : '' ?>name='filter' value='(format:"Electronic resource" OR  medium:"Electronic resource")'  /> <?=$this->transEsc('Filter_electronic_resource')?>
        <input class="btn btn-primary" type="submit" value="<?= $this->transEsc('Find')?>">
      </div>
        </div>
      <?php if (isset($this->extraAdvancedControls)): ?>
        <div class="clearfix">
          <?=$this->extraAdvancedControls ?>
        </div>
        <div class="adv-submit">
          <input class="clear-btn btn btn-default" type="button" value="<?= $this->transEsc('Clear')?>">
          <input class="btn btn-primary" type="submit" value="<?= $this->transEsc('Find')?>">
        </div>
      <?php endif; ?>
    </div>

    <div class="<?=$this->layoutClass('sidebar')?>">
      <?php if ($hasDefaultsApplied): ?>
        <input type="hidden" name="dfApplied" value="1" />
      <?php endif ?>
      <?php if (!empty($searchFilters)): ?>
        <h4><?=$this->transEsc("adv_search_filters")?></h4>
        <div class="facet-group">
          <label class="checkbox">
            <input type="checkbox" checked="checked" class="checkbox-select-all"/>
            <?=$this->transEsc("adv_search_select_all")?>
          </label>
        </div>
        <?php foreach ($searchFilters as $field => $data): ?>
          <div class="facet-group">
            <div class="title"><?=$this->transEsc($field)?></div>
            <?php foreach ($data as $value): ?>
              <label class="facet checkbox"><input class="checkbox-select-item" type="checkbox" checked="checked" name="filter[]" value='<?=$this->escapeHtmlAttr($value['field'])?>:"<?=$this->escapeHtmlAttr($value['value'])?>"' /> <?=$this->escapeHtml($value['displayText'])?></label>
            <?php endforeach; ?>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
      <h4><?=$this->transEsc("Help")?></h4>
      <div class="facet-group">
        <a class="facet help-link" data-lightbox href="<?=$this->url('help-home')?>?topic=advsearch&amp;_=<?=time() ?>"><?=$this->transEsc("Help with Advanced Search")?></a>
        <a class="facet help-link" data-lightbox href="<?=$this->url('help-home')?>?topic=search&amp;_=<?=time() ?>"><?=$this->transEsc("Search Tips")?></a>
      </div>
    </div>
  </form>
</div>
