<?php
use Orchard\Service\Encryption\EncryptionManager;

$this->placeholder('itemDiv')->set('
<div class="msg-qs-app">
    <h2>Quick Search Results</h2>

    <a id="whatsnew">What\'s new?</a>

    <div id="quickSearchNotes">
        <ul>
            <li>Results are now sorted by relevance like a google search, instead of sorted alphabetically.</li>
            <li>Words no longer need to be consecutive, or in order: "house welcome" will find "Welcome To The Monkey House"</li>
            <li>The Search: "talk" will find "talking", "talker", and "talks", but not "stalker".</li>
            <li>You can click the "Filter By" links to narrow down your search, then click the X to remove the filter</li>
            <li>
                <span class="msg-alert">
                    Please note that recent changes to labels may not show up in search results for up to five minutes.
                </span>
            </li>
        </ul>
    </div>

</div>');

if ($this->totalHits > 0) {
    echo($this->paginationpanel(
        '/quicksearch/label/',
        $this->currentPage,
        $this->hitsPerPage,
        ceil($this->totalHits / $this->hitsPerPage),
        $theQueryString = http_build_query($this->currentSafeQueryVars),
        $this->totalHits
    ));
}
?>

<!-- DISPLAY RESULTS -->
<div class="container-fluid">
    <div class="row">

        <?php if ($this->totalHits == 0): ?>
            <!-- DISPLAY NO RESULTS -->
            <div class="no-results-msg">
                <div class="no-results">
                    <p>
                        You searched for <strong>"<?=$this->currentSafeQueryVars['varSearchString']?>"</strong> and there
                        were no results.  Searches are only looking in the following fields:
                    </p>
                    <ul>
                        <li>Label Name</li>
                        <li>Subaccount Name</li>
                        <li>Label ID</li>
                        <li>Subaccount ID</li>
                    </ul>
                    <p>
                        Note that the following words are ignored by labels quicksearch:
                        <em>a, an, and, are, as, at, be, but, by, for, if, in, into, is, it, no, not, of, on, or, such,
                            that, the, their, then, there, these, they, this, to, was, will, with</em>
                    </p>
                </div>

                <div id="quickSearchModify">
                    <h4>Modify your search: </h4>
                    <form action="/quicksearch/label" method="get">
                        <input type="hidden" name="srchSubmit" value="1"/>
                        <input type="text" name="varSearchString" class="quickSearchField" id="smartSearch"
                               value="<?=$this->currentSafeQueryVars['varSearchString']?>" />
                        <input type="submit" name="srchSubmit" value="search"/>
                    </form>
                </div>

            </div>

        <?php else: /* if there are results: */ ?>

        <!-- @todo add css class for labelFacets to match releaseFacets -->
        <div class="results-facets col-sm-2">
            <h3>Filter by:</h3>

            <?php
            // Print Selected Facets above Unselected facets
            foreach ($this->facetNamesSelectedGroup as $facetName => $facetDisplay) {
                echo $this->partial(
                    'quicksearch/partials/facetlist.phtml',
                    array(
                        'facetName' => $facetName,
                        'facetDisplay' => $facetDisplay,
                        'facets' => $this->facets,
                    )
                );
            }
            foreach ($this->facetNamesUnselectedGroup as $facetName => $facetDisplay) {
                echo $this->partial(
                    'quicksearch/partials/facetlist.phtml',
                    array(
                        'facetName' => $facetName,
                        'facetDisplay' => $facetDisplay,
                        'facets' => $this->facets,
                    )
                );
            }
            ?>

        </div>
        <!-- @todo add css class for labelResults to match releaseResults -->
        <div id="labelResults" class="col-sm-10">
            <br>
            <div>You searched For: "<strong><?=$this->currentSafeQueryVars['varSearchString']?></strong>"</div>
            <br>
            <div class="row">
                <div class="panelHeader">
                    <h3>Search results for "<?=$this->currentSafeQueryVars['varSearchString']?>" - <?=$this->totalHits;?> results</h3>
                </div>
                    <div class="panelContent">
                        <table class="label-search-results data">
                            <thead>
                                <tr>
                                    <th>Label Type</th>
                                    <th>Label Name</th>
                                    <th>ID</th>
                                    <th>Contact</th>
                                    <th>Relationship Manager</th>
                                    <th>Status</th>
                                    <?php
                                    $migratedToAbacus = array_values(array_column($this->searchResults, 'migrated_to_abacus'));
                                    if (in_array('1', $migratedToAbacus)) {
                                    ?>
                                        <th>View in Application</th>
                                    <?php } else { ?>
                                        <th>Login</th> 
                                    <?php } ?>
                                </tr>
                            </thead>
                            <tbody>

                <?php
                // ALW impersonation setup
                // this is very bad but we have no other impersonation method currently in place
                $config = Zend_Registry::get("configuration");
                $sessionId = session_id();
                # encrypt the session id
                $auth0Config = yaml_parse_file(APPLICATION_PATH . '/configs/auth0.yml');
                $encryptionManager = new EncryptionManager();
                $sid = $encryptionManager->encryptWithCustomKey($sessionId, $auth0Config['client_id']);
                $memcached = Zend_Registry::get('memcached');
                $memcached->remove($sessionId);
                $memcached->save($_SESSION, $sessionId);
                $alwLoginUrl = $config->workstation_login_url;

                $rowStyle = " alt";
                foreach ($this->searchResults as $result) {
                    $rowStyle       = empty($rowStyle) ? " alt" : "";
                    // Use the label id if no label name is present
                    $displayName    = isset($result["highlight_fields"]["label_name"]) ? $result["highlight_fields"]["label_name"] : $result["label_id"];
                    $displayType    = isset($result["label_type"]) ? $result["label_type"] : "Uncategorized Vendor";
                    $showAlwLogin   = false;
                    $displayContact = "";
                    $displayLogin   = "";
                    $displayManager = isset($result["client_manager"]) ? $result["client_manager"] : "";
                    if ($result["label_status"] == "deletion") {
                        $displayName = "<strike>" . $displayName . "</strike>";
                    }

                    if (isset($result["label_contact_login"])) {
                        $showAlwLogin = true;
                        $displayContact = !empty($result['label_contact_name']) ? $result['label_contact_name'] : '';
                        $displayLogin = "\$('form[name=\\'login" . $result["label_contact_id"] . "\\']').submit()";
                    }
                    ?>
                            <tr class="labelResult<?=$rowStyle?>">
                            <?php if ($showAlwLogin) { ?>
                                    <form name="login<?=$result["label_contact_id"]?>" action="<?=$alwLoginUrl?>" target="_blank" method="post">
                                        <input type="hidden" name="username" value="<?=$result["label_contact_login"]?>">
                                        <input type="hidden" name="session_id" value="<?=$sessionId?>">
                                    </form>
                            <?php } ?>
                                    <td><?=$displayType?></td>
                            <?php if ($displayType == "Subaccount") { ?>
                                    <td>
                                        <div class="sub-label-name">
                                            <div><?=$result["parent_label"]?></div>
                                            <a href="/subaccount/viewsubaccount/subaccount_id/<?=$result["label_id"]?>"><?=$displayName?></a>
                                        </div>
                                    </td>
                            <?php } else { ?>
                                    <td><a href="/cont_mgmt/view_vendor.php?vendor_id=<?=$result["label_id"]?>"><?=$displayName?></a></td>
                            <?php } ?>
                                    <td><?=$result["label_id"]?></td>
                                    <td><?=$displayContact?></td>
                                    <td><?=$displayManager?></td>
                                    <td><?=$result["label_status"]?></td>
                            <?php if ($showAlwLogin) { ?>
                                    <td>
                                        <?php
                                        $isImpersonateResolvable = !empty($result['master_vend_contact_id'])
                                            && (!isset($result['canImpersonateResolvable']) || $result['canImpersonateResolvable']);
                                        $wsImpTooltipMsg = isset($result['wsImpTooltipMsg']) ? $result['wsImpTooltipMsg'] : 'Impersonation unavailable for this contact.';
                                        if ($result['migrated_to_abacus'] == 1) {
                                            echo $this->partial("/quicksearch/_applications.phtml", array(
                                                'labelResults' => $result,
                                                'sessionId' => $sid,
                                                'workstationURL' => $config->workstation_url,
                                                'canImpersonate' => $this->canImpersonate,
                                                'canShowLegacyLogin' => $this->canShowLegacyLogin,
                                                'canImpersonateResolvable' => $isImpersonateResolvable,
                                                'wsImpTooltipMsg' => $wsImpTooltipMsg
                                            ));
                                        } else {
                                        ?>
                                            <?php if ($this->canImpersonate) { ?>
                                            <a class="hide" href="<?php echo $config->workstation_url; ?>#sid=<?php echo $sid; ?>&username=<?php echo urlencode($result["label_contact_login"]); ?>&vend_contact_id=<?php echo $result["master_vend_contact_id"]; ?>" target="_blank"><img src="/images/login_shortcut_icon.jpg" alt="Workstation login"> Workstation Login</a>
                                            <?php if ($isImpersonateResolvable) { ?>
                                            <a class="label-search-link-short" href="<?php echo $config->workstation_url; ?>?impersonate=alw:<?php echo $result["master_vend_contact_id"]; ?>" target="_blank"><img src="/images/login_shortcut_icon.jpg" alt="Workstation impersonation"> Workstation Impersonate</a>
                                            <?php } else { ?>
                                            <span class="label-search-link-short help-tooltip" style="position:relative;display:inline-block;color:#999;cursor:not-allowed;"><img src="/images/login_shortcut_icon.jpg" alt="Workstation impersonation" style="opacity:0.5;filter:grayscale(1);"> Workstation Impersonate<span class="tooltiptext" style="width:350px;margin-left:-175px;"><?php echo $wsImpTooltipMsg; ?></span></span>
                                            <?php } ?>
                                            <?php } elseif ($this->canShowLegacyLogin) { ?>
                                            <a href="<?php echo $config->workstation_url; ?>#sid=<?php echo $sid; ?>&username=<?php echo urlencode($result["label_contact_login"]); ?>&vend_contact_id=<?php echo $result["master_vend_contact_id"]; ?>" target="_blank"><img src="/images/login_shortcut_icon.jpg" alt="Login as Admin"> Login as Admin</a>
                                            <?php } ?>
                                        <?php
                                        }
                                        ?>
                                    </td>
                            <?php } else { ?>
                                    <td></td>
                            <?php } ?>
                            </tr>

                <?php } ?>
                            </tbody>
                        </table>
                    </div>

                <?php endif; /* end check for results */ ?>

            </div><!-- /.row -->
        </div><!-- labelResults -->
    </div>
</div>

<?php
/* Pagination Panel for Below Content */
if ($this->totalHits > 0) {
    echo($this->paginationpanel(
        '/quicksearch/label/',
        $this->currentPage,
        $this->hitsPerPage,
        ceil($this->totalHits / $this->hitsPerPage),
        $theQueryString = http_build_query($this->currentSafeQueryVars),
        $this->totalHits
    ));
}
?>
