<?php
/**
 * Reusable Employee Live Search Component
 * Include this in any form where you need employee search
 * 
 * Usage:
 * include __DIR__ . '/live_search_component.php';
 * renderEmployeeLiveSearch($fieldName, $fieldLabel, $currentValue, $required);
 */

function renderEmployeeLiveSearch($fieldName = 'employee_name', $fieldLabel = 'Employee Name', $currentValue = '', $required = true, $includeHiddenId = false) {
    $fieldId = $fieldName . '_search';
    $resultsId = $fieldName . '_results';
    $requiredAttr = $required ? 'required' : '';
    $requiredMark = $required ? ' *' : '';
    
    ?>
    <div class="form-group">
        <label><?php echo htmlspecialchars($fieldLabel . $requiredMark); ?></label>
        <div style="position: relative;">
            <?php if ($includeHiddenId): ?>
            <input type="hidden" name="employee_id" id="<?php echo $fieldName; ?>_id" value="">
            <?php endif; ?>
            <input type="text" 
                   name="<?php echo $fieldName; ?>" 
                   id="<?php echo $fieldId; ?>" 
                   value="<?php echo htmlspecialchars($currentValue); ?>" 
                   autocomplete="off"
                   placeholder="Type to search employee..."
                   class="form-control employee-search-input"
                   data-results-target="<?php echo $resultsId; ?>"
                   <?php echo $requiredAttr; ?>>
            <div id="<?php echo $resultsId; ?>" class="search-dropdown"></div>
        </div>
        <small style="color: #666; font-size: 11px;">Type at least 2 characters to search</small>
    </div>
    
    <style>
    .search-dropdown {
        display: none;
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border: 1px solid #ddd;
        border-top: none;
        max-height: 300px;
        overflow-y: auto;
        z-index: 1000;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    
    .search-dropdown.active {
        display: block;
    }
    
    .search-result-item {
        padding: 10px;
        cursor: pointer;
        border-bottom: 1px solid #f0f0f0;
        transition: background 0.2s;
    }
    
    .search-result-item:hover {
        background: #f8f9fa;
    }
    
    .search-result-name {
        font-weight: bold;
        color: #333;
        font-size: 13px;
    }
    
    .search-result-details {
        font-size: 11px;
        color: #666;
        margin-top: 3px;
    }
    
    .search-result-details span {
        margin-right: 10px;
    }
    
    .search-no-results,
    .search-loading {
        padding: 10px;
        text-align: center;
        color: #999;
        font-size: 12px;
    }
    </style>
    
    <script>
    (function() {
        const searchInput = document.getElementById('<?php echo $fieldId; ?>');
        const searchResultsDiv = document.getElementById('<?php echo $resultsId; ?>');
        let searchTimeout = null;
        
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                
                const query = this.value.trim();
                
                if (query.length < 2) {
                    searchResultsDiv.classList.remove('active');
                    return;
                }
                
                searchResultsDiv.innerHTML = '<div class="search-loading">Searching...</div>';
                searchResultsDiv.classList.add('active');
                
                searchTimeout = setTimeout(function() {
                    performEmployeeSearch(query, searchResultsDiv, searchInput);
                }, 300);
            });
            
            document.addEventListener('click', function(e) {
                if (!searchInput.contains(e.target) && !searchResultsDiv.contains(e.target)) {
                    searchResultsDiv.classList.remove('active');
                }
            });
        }
        
        function performEmployeeSearch(query, resultsDiv, inputField) {
            fetch('<?php echo BASE_URL; ?>/modules/employee/search_employee_ajax.php?q=' + encodeURIComponent(query))
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.employees.length > 0) {
                        let html = '';
                        data.employees.forEach(function(emp) {
                            html += '<div class="search-result-item" onclick="window.selectEmployeeFromSearch_' + 
                                    inputField.id.replace(/-/g, '_') + '(' + JSON.stringify(emp) + ')">';
                            html += '<div class="search-result-name">' + escapeHtml(emp.employee_name) + '</div>';
                            html += '<div class="search-result-details">';
                            if (emp.emp_id) html += '<span>ID: ' + escapeHtml(emp.emp_id) + '</span>';
                            if (emp.department) html += '<span>Dept: ' + escapeHtml(emp.department) + '</span>';
                            if (emp.designation) html += '<span>Desig: ' + escapeHtml(emp.designation) + '</span>';
                            html += '</div></div>';
                        });
                        resultsDiv.innerHTML = html;
                    } else {
                        resultsDiv.innerHTML = '<div class="search-no-results">No employees found</div>';
                    }
                    resultsDiv.classList.add('active');
                })
                .catch(error => {
                    console.error('Search error:', error);
                    resultsDiv.innerHTML = '<div class="search-no-results">Search error</div>';
                });
        }
        
        window['selectEmployeeFromSearch_' + searchInput.id.replace(/-/g, '_')] = function(emp) {
            searchInput.value = emp.employee_name;
            
            <?php if ($includeHiddenId): ?>
            const hiddenIdField = document.getElementById('<?php echo $fieldName; ?>_id');
            if (hiddenIdField) {
                hiddenIdField.value = emp.employee_id || '';
            }
            <?php endif; ?>
            
            // Try to auto-fill related fields if they exist
            const empIdField = document.querySelector('input[name="emp_id"]');
            if (empIdField && emp.emp_id) empIdField.value = emp.emp_id;
            
            const deptField = document.querySelector('input[name="department"]');
            if (deptField && emp.department) deptField.value = emp.department;
            
            const desigField = document.querySelector('input[name="designation"]');
            if (desigField && emp.designation) desigField.value = emp.designation;
            
            const contactField = document.querySelector('input[name="contact_number"]');
            if (contactField && emp.contact_number) contactField.value = emp.contact_number;
            
            searchResultsDiv.classList.remove('active');
        };
        
        function escapeHtml(text) {
            if (!text) return '';
            const map = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'};
            return text.replace(/[&<>"']/g, m => map[m]);
        }
    })();
    </script>
    <?php
}
?>

