<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<ul class="dropdown-menu search-results animated fadeIn no-mtop display-block" id="top_search_dropdown">
    <?php
    $total = 0;
    
    $this->load->helper('staff_helper');
    function format_name_last_first($fullName) {
        // $fullName = trim($fullName ?? '');
    
        // if ($fullName === '') {
        //     return '';
        // }
    
        // $parts = explode(' ', $fullName);
    
        // if (count($parts) >= 2) {
        //     $firstName = array_shift($parts);
        //     $lastName = implode(' ', $parts);
        //     return $lastName . ', ' . $firstName;
        // }
    
        // return $fullName;
        $primary_name = explode(' ', $fullName, 3);
        $firstname = '';
        $middlename = '';
        $lastname = '';

        if (isset($primary_name[0])) {
            $firstname = $primary_name[0];
        }
        if (isset($primary_name[1])) {
            $middlename = $primary_name[1];
        }
        if (isset($primary_name[2])) {
            $lastname = $primary_name[2];
        }
        return $lastname . ', ' . $firstname . ' ' . $middlename;
    }
    foreach ($result as $data) {
        if (count($data['result']) > 0) {
            $total++;
            ?>

            <!-- <li class="dropdown-header"><?php echo $data['search_heading']; ?></li> -->
            <li class="dropdown-header">
                <?php echo ($data['search_heading'] == 'Leads') ? 'Cases' : (($data['search_heading'] == 'Staff Members') ? 'Staff Members' : ''); ?>
            </li>
            <li role="separator" class="divider"></li>
        <?php } ?>
        <?php foreach ($data['result'] as $_result) {
            $output = '';
            switch ($data['type']) {
                // switch ('leads') {
                // case 'clients':
                //     $output = '<a href="' . admin_url('clients/client/' . $_result['userid']) . '">' . $_result['company'] . '</a>';
                //     break;
                // case 'contacts':
                //     $output = '<a href="' . admin_url('clients/client/' . $_result['userid'] . '?contactid=' . $_result['id']) . '">' . $_result['firstname'] . ' ' . $_result['lastname'] . ' <small>' . get_company_name($_result['userid']) . '</small></a>';
                //     break;
                case 'staff':
                    $output = '<a href="' . admin_url('staff/member/' . $_result['staffid']) . '">' . $_result['firstname'] . ' ' . $_result['lastname'] . '</a>';
                    break;
                // case 'tickets':
                //     $output = '<a href="' . admin_url('tickets/ticket/' . $_result['ticketid']) . '">#' . $_result['ticketid'] . ' - ' . $_result['subject'] . '</a>';
                //     break;
                // case 'knowledge_base_articles':
                //     $output = '<a href="' . admin_url('knowledge_base/article/' . $_result['articleid']) . '">' . $_result['subject'] . '</a>';
                //     break;
                case 'leads':
                    $output = '<a href="#" onclick="init_lead(' . $_result['id'] . ');return false;">' . $_result['name'] . '</a>';
                    break;
                    // case 'tasks':
                    // $task_link = 'init_task_modal('.$_result['id'].'); return false;';
                    // $output = '<a href="#" onclick="'.$task_link.'">'.$_result['name'].'</a>';
                    // break;
                    // case 'contracts':
                    // $output = '<a href="'.admin_url('contracts/contract/'.$_result['id']).'">'.$_result['subject'].'</a>';
                    // break;
                    // case 'invoice_payment_records':
                    // $output = '<a href="'.admin_url('payments/payment/'.$_result['paymentid']).'">#'.$_result['paymentid'].'<span class="pull-right">'.date('Y',strtotime($_result['date'])).'</span></a>';
                    // break;
                    // case 'invoices':
                    // $output = '<a href="'.admin_url('invoices/list_invoices/'.$_result['invoiceid']).'">'.format_invoice_number($_result['invoiceid']).'<span class="pull-right">'.date('Y',strtotime($_result['date'])).'</span></a>';
                    // break;
                    // case 'credit_note':
                    // $output = '<a href="'.admin_url('credit_notes/list_credit_notes/'.$_result['credit_note_id']).'">'.format_credit_note_number($_result['credit_note_id']).'<span class="pull-right">'.date('Y',strtotime($_result['date'])).'</span></a>';
                    // break;
                    // case 'estimates':
                    // $output = '<a href="'.admin_url('estimates/list_estimates/'.$_result['estimateid']).'">'.format_estimate_number($_result['estimateid']).'<span class="pull-right">'.date('Y',strtotime($_result['date'])).'</span></a>';
                    // break;
                    // case 'expenses':
                    // $output = '<a href="'.admin_url('expenses/list_expenses/'.$_result['expenseid']).'">'.$_result['category_name']. ' - ' .app_format_money($_result['amount'], $_result['currency_name']).'</a>';
                    // break;
                    // case 'proposals':
                    // $output = '<a href="'.admin_url('proposals/list_proposals/'.$_result['id']).'">'.format_proposal_number($_result['id']) .' - ' . $_result['subject'] .'</a>';
                    // break;
                    // case 'custom_fields':
                    // $rel_data   = get_relation_data($_result['fieldto'], $_result['relid']);
                    // $rel_values = get_relation_values($rel_data, $_result['fieldto']);
                    // $output      = '<a class="pull-left" href="' . $rel_values['link'] . '">' . $rel_values['name'] .'<span class="pull-right">'._l($_result['fieldto']).'</span></a>';
                    // break;
                    // case 'invoice_items':
                    // $output = '<a href="'.admin_url('invoices/list_invoices/'.$_result['rel_id']).'">'.format_invoice_number($_result['rel_id']);
                    // $output .= '<br />';
                    // $output .= '<small>'.$_result['description'].'</small>';
                    // $output .= '</a>';
                    // break;
                    // case 'estimate_items':
                    // $output = '<a href="'.admin_url('estimates/list_estimates/'.$_result['rel_id']).'">'.format_estimate_number($_result['rel_id']);
                    // $output .= '<br />';
                    // $output .= '<small>'.$_result['description'].'</small>';
                    // $output .= '</a>';
                    // break;
                    // case 'projects':
                    // $output = '<a href="'.admin_url('projects/view/'.$_result['id']).'">'.$_result['name'].'</a>';
                    break;
            }
            ?>
            <li>
                <?php if($data['type'] == 'leads'){
                    $brokerage_name = get_brokerage_name_using_brokerage_id($this, $_result['brokerage_id']);
                    $brokerage_color = get_brokerage_color_using_brokerage_id($this, $_result['brokerage_id']);
                    $group_color = get_groups_color_by_group_name($this, $_result['assign_group']);
                    $lead_status = get_status_name_by_using_status_id($this, $_result['status']);
                    $lead_color = get_status_color_by_using_status_id($this, $_result['status']);
                    ?> 
                    <li class="search-result-card" style="background: #fff; border: 1px solid #e5e7eb; border-radius: 12px;margin-right:10px;margin-left:15px; padding: 16px; margin-bottom: 12px; box-shadow: rgb(0 0 0 / 27%) 0px 2px 6px; transition: box-shadow 0.2s ease-in-out; list-style: none; position: relative; min-height: 165px;" onmouseover="this.style.boxShadow='0 4px 12px rgba(0,0,0,0.1)'" onmouseout="this.style.boxShadow='0 2px 6px rgba(0,0,0,0.05)'">
                        <div class="col-md-12" style="margin-bottom: 10px;">
                            <div style="display:flex;">
                                <div class="tw-grow tw-mr-2" style="background-color:<?php echo $brokerage_color; ?>;padding: 5px;color: black;width: 10px;f;font-weight: 300;border-radius: 6px;display:flex;justify-content:center;align-items:center;font-size: smaller;">
                                    <span style="color:black;font-weight: 600;"><?php echo $brokerage_name; ?></span>
                                </div>
                                <div class="tw-grow tw-mr-2" style="background-color:<?php echo $group_color; ?>;padding: 5px;color: black;width: 10px;f;font-weight: 300;border-radius: 6px;display:flex;justify-content:center;align-items:center;font-size: smaller;">
                                    <span style="color:black;font-weight: 600;"><?php echo $_result['assign_group']; ?></span>
                                </div>
                            </div>
                        </div>
                        <div style="font-weight: 600; font-size: 1rem; margin-bottom: 8px;" style="margin-left: 10px;">
                           <p style="margin-left: 10px;font-size: smaller;">
                              <?php echo '#' . $_result['id'] . ' - <a href="#" onclick="init_lead(' . $_result['id'] . ');return false;" style="color: #2563eb; text-decoration: none;" onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'">' . format_name_last_first($_result['name']) . '</a>'; ?>
                           </p> 
                        </div>
                        <div class="row">
                            <?php
                                $isArchived = $_result['status'] == '9';
                                $isClosed = $_result['status'] == '5';
                                $boxWidth = ($isArchived || $isClosed) ? '160px' : '140px';

                                $archiveDate = $isArchived && !empty($_result['archive_date']) ? date('d F Y', strtotime($_result['archive_date'])) : '';
                                $closedDate = $isClosed && !empty($_result['closed_completed_at']) ? date('d F Y', strtotime($_result['closed_completed_at'])) : '';

                                if($_result['status'] == '5' && !empty($closedDate)){
                                    $lead_color = '#FF0000';
                                    $lead_status = 'Closed';
                                }

                                $dateText = $isArchived ? $archiveDate : ($isClosed ? $closedDate : '');
                            ?>

                            <div style="margin-bottom: 10px;margin-left: 25px; background-color: <?= $lead_color ?>; border-radius: 10px; text-align: center; width: <?= $boxWidth ?>;">
                                <span style="font-weight: 400; color: white;font-size: 12px;">
                                    <?= $lead_status ?> <?= $dateText ?>
                                </span>
                            </div>
                        </div>
                        <div class="row">
                            <?php if (isset($_result['lastcontact']) && $_result['lastcontact'] != null): ?>
                                <p class="col-md-12" style="position: absolute;right: 16px; font-size: 10px; color: #6b7280;display: flex; justify-content: end;">
                                    Last Contact: <?php echo _dt($_result['lastcontact']); ?>
                                </p>
                            <?php
                            endif; 
                            if (isset($_result['dateadded'])):  ?>
                                <p class="col-md-12" style="position: absolute;right: 16px; font-size: 10px; color: #6b7280;display: flex; justify-content: end;padding: 20px 0px">
                                    Created: <?php echo  _dt($_result['dateadded']); ?>
                                </p>
                            <?php endif; ?>
                        </div>
                    </li>
                    <?php }else{?>
                       
                        <?php echo hooks()->apply_filters('global_search_result_output', $output, ['result' => $_result, 'type' => $data['type']]);?>
                    <?php } ?>
               

            </li>
        <?php } ?>
    <?php } ?>
    <?php if ($total == 0) { ?>
        <li class="padding-5 text-center search-no-results">
            <?php echo _l('not_results_found'); ?>
        </li>
    <?php } ?>
</ul>