<!-- Modal -->
<div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="modal_vincular_cliente" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog" >
    <div class="modal-content">
        <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel1">Vincular cliente</h5>
        <button
                type="button"
                class="btn-close"
                data-bs-dismiss="modal"
                aria-label="Close"></button>
        </div>
        <div class="modal-body">

            <div class="search">
                <input type="search" class="form-control w-100" id="search" name="search" placeholder="Pesquisar cliente">
            </div>

            <hr>
            <div id="clientes-container">
                @include('dashboard.admin.pages.obras._includes.lista-cliente', ['clientes' => $clientes])
            </div>

        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">
            Close
        </button>
        <button type="button" class="btn btn-primary" id="confirmarCliente">Vincular</button>
        </div>
    </div>
    </div>
</div>

@push('scripts')
<script>
    console.log("testando")
    const searchInput = document.getElementById('search');
    const container = document.getElementById('clientes-container');

    document.getElementById('search').addEventListener('input', function () {
        fetch(`{{ route('obras.clientes.buscar') }}?search=${this.value}`)
            .then(res => res.text())
            .then(html => {
                document.getElementById('clientes-container').innerHTML = html;
                aplicarCheckboxUnico();
            });
    });


    let clienteSelecionado = null;

    function aplicarCheckboxUnico() {
        document.querySelectorAll('.cliente-checkbox').forEach(cb => {
            cb.onchange = function () {
                document.querySelectorAll('.cliente-checkbox').forEach(c => {
                    if (c !== this) c.checked = false;
                });
                clienteSelecionado = this.value;
            }
        });
    }

    document.getElementById('confirmarCliente').addEventListener('click', () => {
        if (!clienteSelecionado) {
            alert('Selecione um cliente');
            return;
        }

        document.getElementById('cliente_id').value = clienteSelecionado;
        bootstrap.Modal.getInstance(
            document.getElementById('modal_vincular_cliente')
        ).hide();
    });

    aplicarCheckboxUnico();
</script>
@endpush


