// Cari arama ve seçim işlemleri merkezi script

document.addEventListener('DOMContentLoaded', function() {
    const cariAramaInput = document.getElementById('cari_arama');
    if(cariAramaInput) cariAramaInput.addEventListener('input', cariAra);
});

function cariAra() {
    const arama = document.getElementById('cari_arama').value;
    const sonuclarDiv = document.getElementById('cariSonuclar');
    if (arama.length < 2) {
        sonuclarDiv.style.display = 'none';
        return;
    }
    fetch('../ajax/cari_ara_ajax.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'arama=' + encodeURIComponent(arama)
    })
    .then(response => response.json())
    .then(data => {
        let html = '';
        if (data.success && data.cariler.length > 0) {
            data.cariler.forEach(cari => {
                html += `<a href="#" class="autocomplete-suggestion" onclick="event.preventDefault(); cariSec(${cari.id}, '${cari.ad_soyad.replace(/'/g, "\\'")}')">${cari.ad_soyad}</a>`;
            });
        } else {
            html = '<div class="autocomplete-suggestion text-muted">Sonuç bulunamadı</div>';
        }
        sonuclarDiv.innerHTML = html;
        sonuclarDiv.style.display = 'block';
    });
}

window.cariSec = function(id, ad) {
    document.getElementById('cari_id').value = id;
    document.getElementById('cari_arama').value = ad;
    document.getElementById('seciliCari').innerHTML = `<div class="alert alert-success mb-0">Seçilen: <strong>${ad}</strong></div>`;
    document.getElementById('cariSonuclar').style.display = 'none';
}
