<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')) { require_once('../../../'.$_REQUEST['tenant'].'/config.php'); }
if(file_exists('/config.php')) { require_once('/config.php'); }

function highlightWords($text) {
    $word = $_REQUEST['searchString'];
    return preg_replace('#' . preg_quote($word) . '#i', '<span class="yellow">\\0</span>', $text);
}

function checkMatch($str) {
    $pattern = $_REQUEST['searchString'];
    return (preg_match("/{$pattern}/i", $str)) ? 1 : 0;
}

switch($_REQUEST['FCN']) {
    default:
        break;

    case "search":
        // MDB tab structure
        $tabStart = '
        <ul class="nav nav-tabs mb-3" id="myTab" role="tablist">
            <li class="nav-item" role="presentation">
                <a data-mdb-tab-init class="nav-link active" id="live-tab" href="#live" role="tab" aria-controls="live" aria-selected="true">Live</a>
            </li>
            <li class="nav-item" role="presentation">
                <a data-mdb-tab-init class="nav-link" id="archive-tab" href="#archive" role="tab" aria-controls="archive" aria-selected="false" >Archive</a >
            </li>
        </ul>

        <div class="tab-content" id="searchTabs">';

        // Live assets query
        $checkAssetLive = mysqli_query($GLOBALS['con'], "SELECT `desc`,`itemnumber`, `locnumber`, `clientnumber`, `plantnumber`, `serialnumber`, `manf`, `model` 
            FROM `itemdetails` 
            WHERE (`desc` LIKE '%".$_REQUEST['searchString']."%' 
            OR `plantnumber` LIKE '%".$_REQUEST['searchString']."%' 
            OR `serialnumber` LIKE '%".$_REQUEST['searchString']."%' 
            OR `manf` LIKE '%".$_REQUEST['searchString']."%' 
            OR `model` LIKE '%".$_REQUEST['searchString']."%') 
            AND `statuslive` = '1'") 
            or die($e = mysqli_error($GLOBALS['con']));

        $liveCount = mysqli_num_rows($checkAssetLive);
        $liveReturn = '';

        // Live Assets Tab
        if ($liveCount == 0) {
            $liveReturn .= '<div class="tab-pane fade show active" id="live" role="tabpanel" aria-labelledby="live-tab">
                <h3>Live Assets</h3>
                <p>No Live assets matching this query.</p>
            </div>';
        } else {
            $liveReturn .= '<div class="tab-pane fade show active" id="live" role="tabpanel" aria-labelledby="live-tab">
                <h3>Live Assets <small>('.$liveCount.')</small></h3>
                <table id="liveAssetTable" class="table table-striped table-hover w-100">
                    <thead>
                        <tr>
                            <th>Client Name</th>
                            <th>Location</th>
                            <th>Description</th>
                            <th>Plant Number</th>
                            <th>Serial Number</th>
                            <th>Model</th>
                            <th>Manufacturer</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>';
            while ($liveAssets = mysqli_fetch_array($checkAssetLive)) {
                if (checkMatch($liveAssets['desc']) == 1 || checkMatch($liveAssets['plantnumber']) == 1 || 
                    checkMatch($liveAssets['serialnumber']) == 1 || checkMatch($liveAssets['model']) == 1 || checkMatch($liveAssets['manf']) == 1) {
                    $liveReturn .= '<tr>
                        <td>'.highlightWords(getClientName($liveAssets['clientnumber'])).'</td>
                        <td>'.highlightWords(getLocation($liveAssets['locnumber'])).'</td>
                        <td>'.highlightWords($liveAssets['desc']).'</td>
                        <td>'.highlightWords($liveAssets['plantnumber']).'</td>
                        <td>'.highlightWords($liveAssets['serialnumber']).'</td>
                        <td>'.highlightWords($liveAssets['model']).'</td>
                        <td>'.highlightWords($liveAssets['manf']).'</td>
                        <td>
                            <a href="?t=includes/master&p=client.php&clientnumber='.$liveAssets['clientnumber'].'&view=asset&search='.$_REQUEST['searchString'].'" 
                               class="btn btn-secondary me-2" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View Schedule">
                               <i class="fad fa-th-list"></i></a>

                            <a href="?t=includes/master&p=asset.php&view=edit_attached&data='.$liveAssets['clientnumber'].'|'.$liveAssets['locnumber'].'|'.$liveAssets['itemnumber'].'" 
                               class="btn btn-secondary me-2" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Item Details">
                               <i class="fad fa-info-circle"></i></a>
                        </td>
                    </tr>';
                }
            }
            $liveReturn .= '</tbody></table></div>';
        }

        // Archived Assets Query
        $archiveReturn = '';
        $checkAssetArchive = mysqli_query($GLOBALS['con'], "SELECT `desc`, `itemnumber`, `locnumber`, `clientnumber`, `plantnumber`, `serialnumber`, `manf`, `model` 
            FROM `itemdetails` 
            WHERE (`desc` LIKE '%".$_REQUEST['searchString']."%' 
            OR `plantnumber` LIKE '%".$_REQUEST['searchString']."%' 
            OR `serialnumber` LIKE '%".$_REQUEST['searchString']."%' 
            OR `manf` LIKE '%".$_REQUEST['searchString']."%' 
            OR `model` LIKE '%".$_REQUEST['searchString']."%') 
            AND `statuslive` = '0'") 
            or die($e = mysqli_error($GLOBALS['con']));

        $archiveCount = mysqli_num_rows($checkAssetArchive);
        $totalAssetCount = $liveCount + $archiveCount;

        $clientMatches = [];
        if ($liveCount > 0) {
            mysqli_data_seek($checkAssetLive, 0);
            while ($asset = mysqli_fetch_assoc($checkAssetLive)) {
                $clientMatches[$asset['clientnumber']] = true;
            }
            mysqli_data_seek($checkAssetLive, 0);
        }
        if ($archiveCount > 0) {
            while ($asset = mysqli_fetch_assoc($checkAssetArchive)) {
                $clientMatches[$asset['clientnumber']] = true;
            }
            mysqli_data_seek($checkAssetArchive, 0);
        }

        $clientCount = count($clientMatches);
        $assetLabel = $totalAssetCount === 1 ? 'asset' : 'assets';
        $clientLabel = $clientCount === 1 ? 'client' : 'clients';
        $header = '
        <div class="row g-3 mt-2 mb-4">
            <div class="col-12">
                <h4 class="mb-1">Results for <strong>'.htmlspecialchars($_REQUEST['searchString']).'</strong></h4>
                <p class="text-muted mb-0">'.$totalAssetCount.' '.$assetLabel.' found across '.$clientCount.' '.$clientLabel.'.</p>
            </div>
            <div class="col-12 col-md-4">
                <div class="bg-light rounded-3 p-3 h-100 d-flex align-items-center">
                    <i class="fad fa-cubes fa-2x text-primary me-3"></i>
                    <div><strong class="h4 mb-0 d-block">'.$totalAssetCount.'</strong><span class="text-muted">Total assets</span></div>
                </div>
            </div>
            <div class="col-12 col-md-4">
                <div class="bg-light rounded-3 p-3 h-100 d-flex align-items-center">
                    <i class="fad fa-building fa-2x text-primary me-3"></i>
                    <div><strong class="h4 mb-0 d-block">'.$clientCount.'</strong><span class="text-muted">Affected clients</span></div>
                </div>
            </div>
            <div class="col-6 col-md-2">
                <div class="bg-light rounded-3 p-3 h-100">
                    <strong class="h4 mb-0 d-block text-success">'.$liveCount.'</strong><span class="text-muted">Live</span>
                </div>
            </div>
            <div class="col-6 col-md-2">
                <div class="bg-light rounded-3 p-3 h-100">
                    <strong class="h4 mb-0 d-block text-secondary">'.$archiveCount.'</strong><span class="text-muted">Archived</span>
                </div>
            </div>
        </div>';

        // Archived Assets Tab
        if ($archiveCount == 0) {
            $archiveReturn = '<div class="tab-pane fade" id="archive" role="tabpanel" aria-labelledby="archive-tab">
                <h3>Archived Assets</h3>
                <p>No archived assets matching this query.</p>
            </div>';
        } else {
            $archiveReturn = '<div class="tab-pane fade" id="archive" role="tabpanel" aria-labelledby="archive-tab">
                <h3>Archived Assets <small>('.$archiveCount.')</small></h3>
                <table id="archiveAssetTable" class="table table-striped table-hover w-100">
                    <thead>
                        <tr>
                            <th>Client Name</th>
                            <th>Location</th>
                            <th>Description</th>
                            <th>Plantnumber</th>
                            <th>Serialnumber</th>
                            <th>Model</th>
                            <th>Manufacturer</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>';
            while ($archiveAssets = mysqli_fetch_array($checkAssetArchive)) {
                if (checkMatch($archiveAssets['desc']) == 1 || checkMatch($archiveAssets['plantnumber']) == 1 || 
                    checkMatch($archiveAssets['serialnumber']) == 1 || checkMatch($archiveAssets['model']) == 1 || checkMatch($archiveAssets['manf']) == 1) {
                    $archiveReturn .= '<tr>
                        <td>'.highlightWords(getClientName($archiveAssets['clientnumber'])).'</td>
                        <td>'.highlightWords(getLocation($archiveAssets['locnumber'])).'</td>
                        <td>'.highlightWords($archiveAssets['desc']).'</td>
                        <td>'.highlightWords($archiveAssets['plantnumber']).'</td>
                        <td>'.highlightWords($archiveAssets['serialnumber']).'</td>
                        <td>'.highlightWords($archiveAssets['model']).'</td>
                        <td>'.highlightWords($archiveAssets['manf']).'</td>
                        <td>
                            <a href="?t=includes/master&p=client.php&clientnumber='.$archiveAssets['clientnumber'].'&view=asset&search='.$_REQUEST['searchString'].'" 
                               class="btn btn-secondary me-2 waves-effect waves-light" data-mdb-toggle="tooltip" title="View Schedule">
                               <i class="fad fa-th-list"></i></a>

                            <a href="?t=includes/master&p=asset.php&view=edit_attached&data='.$archiveAssets['clientnumber'].'|'.$archiveAssets['locnumber'].'|'.$archiveAssets['itemnumber'].'" 
                               class="btn btn-secondary me-2 waves-effect waves-light" data-mdb-toggle="tooltip" title="Item Details">
                               <i class="fad fa-info-circle"></i></a>
                        </td>
                    </tr>';
                }
            }
            $archiveReturn .= '</tbody></table></div>';
        }

        $tabEnd = '</div><script>const triggerTabList = [].slice.call(document.querySelectorAll(\'#myTab a\'));
triggerTabList.forEach((triggerEl) => {
  const tabTrigger = new mdb.Tab(triggerEl);

  triggerEl.addEventListener(\'click\', (event) => {
    event.preventDefault();
    tabTrigger.show();
  });
});
const element = document.querySelector(\'.tooltip\');
const instance = new mdb.Tooltip(element)
</script>'; // End tab content
        echo $header . $tabStart . $liveReturn . $archiveReturn . $tabEnd;
        break;
}
