
<?php
    $cmsTypes = \App\Models\Customer\Customer::companyTypes();
    $cmsItems = $companies->map(fn($c) => [
        'id'   => (string) $c->id,
        'name' => $c->company_name ?? '',
        'sub'  => $cmsTypes[$c->company_type] ?? ($c->billing_city ?: ''),
        'bill' => [
            'billing_address'    => $c->billing_address,
            'billing_city'       => $c->billing_city,
            'billing_district'   => $c->billing_district,
            'billing_email'      => $c->billing_email ?: $c->email,
            'billing_tax_number' => $c->billing_tax_number ?: $c->company_tax_number,
            'billing_tax_office' => $c->billing_tax_office ?: $c->company_tax_office,
        ],
    ])->values();
    $cmsSelected = array_map('strval', $selectedCompanyIds ?? []);
?>

<div class="cms" id="cmsRoot">
    <div id="cmsHidden">
        <?php $__currentLoopData = $cmsSelected; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cid): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <?php if($companies->contains(fn($c) => (string) $c->id === $cid)): ?>
                <input type="hidden" name="company_ids[]" value="<?php echo e($cid); ?>">
            <?php endif; ?>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    </div>

    <div class="cms-control <?php echo e($errors->has('company_ids') || $errors->has('company_ids.*') ? 'field-error' : ''); ?>"
         id="cmsControl" role="combobox" aria-expanded="false" aria-haspopup="listbox">
        <span class="cms-lead"><i class="fas fa-building"></i></span>
        <div class="cms-chips" id="cmsChips"></div>
        <input type="text" class="cms-input" id="cmsInput" autocomplete="off"
               placeholder="<?php echo e($cmsItems->isEmpty() ? 'Kayıtlı şirket yok' : 'Şirket ara veya seçin…'); ?>"
               <?php echo e($cmsItems->isEmpty() ? 'disabled' : ''); ?>>
        <span class="cms-caret" id="cmsCaret"><i class="fas fa-chevron-down"></i></span>
    </div>

    <div class="cms-panel" id="cmsPanel" role="listbox">
        <div class="cms-list" id="cmsList"></div>
        <div class="cms-foot">
            <span class="cms-count" id="cmsCount"></span>
            <button type="button" class="cms-clear" id="cmsClear" onclick="cmsClearAll()">
                <i class="fas fa-xmark me-1"></i>Temizle
            </button>
        </div>
    </div>

    <?php $__errorArgs = ['company_ids'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> <div class="error-msg"><?php echo e($message); ?></div> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
    <?php $__errorArgs = ['company_ids.*'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> <div class="error-msg"><?php echo e($message); ?></div> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
</div>

<?php if (! $__env->hasRenderedOnce('d1959c6d-c26d-429f-bd3d-abea1f71a54b')): $__env->markAsRenderedOnce('d1959c6d-c26d-429f-bd3d-abea1f71a54b'); ?>
<?php $__env->startPush('styles'); ?>
<style>
/* ── cms: bağlı şirketler çoklu seçimi ─────────────────────────────── */
.cms { position: relative; }
.cms-control {
    display: flex; align-items: center; flex-wrap: wrap; gap: .35rem;
    min-height: 44px; padding: .3rem .6rem .3rem .8rem; cursor: text;
    border: 1.5px solid #e2e8f0; border-radius: 10px; background: #f8fafc;
    transition: border-color .2s, box-shadow .2s, background .2s;
}
.cms-control.focus {
    border-color: #6366f1; background: #fff;
    box-shadow: 0 0 0 3px rgba(99,102,241,.1);
}
.cms-lead { color: #94a3b8; font-size: .8rem; flex-shrink: 0; transition: color .2s; }
.cms-control.focus .cms-lead { color: #6366f1; }
.cms-chips { display: contents; }
.cms-input {
    flex: 1; min-width: 90px; border: none; outline: none; background: none;
    font-size: .875rem; color: #0f172a; padding: .35rem .2rem; height: 30px;
}
.cms-input::placeholder { color: #94a3b8; }
.cms-input:disabled { cursor: not-allowed; }
.cms-caret {
    margin-left: auto; color: #94a3b8; font-size: .7rem; flex-shrink: 0;
    padding: 0 .2rem; transition: transform .25s cubic-bezier(.4,0,.2,1);
}
.cms.open .cms-caret { transform: rotate(180deg); color: #6366f1; }

/* Chip */
.cms-chip {
    display: inline-flex; align-items: center; gap: .4rem;
    background: #fff; border: 1px solid #e2e8f0; border-radius: 8px;
    padding: .2rem .3rem .2rem .2rem; max-width: 100%;
    box-shadow: 0 1px 2px rgba(15,23,42,.04);
    animation: cmsChipIn .18s cubic-bezier(.34,1.56,.64,1);
}
@keyframes cmsChipIn { from { opacity: 0; transform: scale(.85); } to { opacity: 1; transform: scale(1); } }
.cms-chip-name {
    font-size: .8rem; font-weight: 600; color: #1e293b;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 180px;
}
.cms-chip-x {
    display: flex; align-items: center; justify-content: center;
    width: 18px; height: 18px; border: none; border-radius: 6px;
    background: transparent; color: #94a3b8; cursor: pointer;
    font-size: .68rem; transition: all .15s; flex-shrink: 0;
}
.cms-chip-x:hover { background: #fff1f2; color: #ef4444; }

/* Avatar (chip + satır ortak) */
.cms-av {
    display: flex; align-items: center; justify-content: center;
    width: 24px; height: 24px; border-radius: 7px; flex-shrink: 0;
    font-size: .6rem; font-weight: 800; color: #fff; letter-spacing: .3px;
}
.cms-av.g0 { background: linear-gradient(135deg,#6366f1,#818cf8); }
.cms-av.g1 { background: linear-gradient(135deg,#0ea5e9,#38bdf8); }
.cms-av.g2 { background: linear-gradient(135deg,#10b981,#34d399); }
.cms-av.g3 { background: linear-gradient(135deg,#f59e0b,#fbbf24); }
.cms-av.g4 { background: linear-gradient(135deg,#ec4899,#f472b6); }
.cms-av.g5 { background: linear-gradient(135deg,#8b5cf6,#a78bfa); }

/* Panel — akış içinde açılır, kart overflow'una takılmaz */
.cms-panel {
    max-height: 0; opacity: 0; overflow: hidden; visibility: hidden;
    transform: translateY(-4px);
    border: 1.5px solid transparent; border-radius: 12px; background: #fff;
    transition: max-height .28s cubic-bezier(.4,0,.2,1), opacity .2s, transform .25s,
                margin .28s, border-color .2s, box-shadow .2s, visibility .28s;
}
.cms.open .cms-panel {
    max-height: 320px; opacity: 1; visibility: visible; transform: none;
    margin-top: .45rem; border-color: #e2e8f0;
    box-shadow: 0 8px 24px rgba(15,23,42,.08);
}
.cms-list { max-height: 252px; overflow-y: auto; padding: .35rem; }
.cms-list::-webkit-scrollbar { width: 6px; }
.cms-list::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 99px; }

/* Satır */
.cms-row {
    display: flex; align-items: center; gap: .6rem; width: 100%;
    padding: .5rem .6rem; border: none; border-radius: 9px; background: none;
    cursor: pointer; text-align: left; transition: background .12s;
}
.cms-row:hover, .cms-row.active { background: #f8fafc; }
.cms-row .cms-av { width: 30px; height: 30px; font-size: .68rem; border-radius: 9px; }
.cms-row-meta { flex: 1; min-width: 0; }
.cms-row-name {
    font-size: .85rem; font-weight: 600; color: #0f172a;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.cms-row-name .cms-hl { color: #6366f1; background: #eef2ff; border-radius: 3px; }
.cms-row-sub { font-size: .72rem; color: #94a3b8; }
.cms-check {
    width: 20px; height: 20px; border-radius: 50%; flex-shrink: 0;
    border: 1.5px solid #cbd5e1; background: #fff;
    display: flex; align-items: center; justify-content: center;
    color: #fff; font-size: .58rem; transition: all .15s;
}
.cms-row.sel { background: #eef2ff; }
.cms-row.sel .cms-row-name { color: #4338ca; }
.cms-row.sel .cms-check {
    border-color: #6366f1; background: #6366f1;
    animation: cmsPop .2s cubic-bezier(.34,1.56,.64,1);
}
@keyframes cmsPop { 50% { transform: scale(1.25); } }
.cms-nores {
    padding: 1.1rem .8rem; text-align: center;
    font-size: .8rem; color: #94a3b8;
}
.cms-nores i { display: block; font-size: 1.1rem; margin-bottom: .35rem; opacity: .5; }

/* Alt bar */
.cms-foot {
    display: flex; align-items: center; justify-content: space-between;
    padding: .5rem .8rem; border-top: 1px solid #f1f5f9; background: #fafbff;
}
.cms-count { font-size: .72rem; font-weight: 600; color: #64748b; }
.cms-clear {
    border: none; background: none; padding: .2rem .45rem; border-radius: 7px;
    font-size: .72rem; font-weight: 700; color: #ef4444; cursor: pointer;
    transition: background .15s; visibility: hidden;
}
.cms-clear.show { visibility: visible; }
.cms-clear:hover { background: #fff1f2; }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
(function () {
    const ITEMS = <?php echo json_encode($cmsItems, 15, 512) ?>;
    const root   = document.getElementById('cmsRoot');
    if (!root) return;
    const control = document.getElementById('cmsControl');
    const input   = document.getElementById('cmsInput');
    const chipsEl = document.getElementById('cmsChips');
    const listEl  = document.getElementById('cmsList');
    const hidden  = document.getElementById('cmsHidden');
    const countEl = document.getElementById('cmsCount');
    const clearBt = document.getElementById('cmsClear');

    const sel = new Set(<?php echo json_encode($cmsSelected, 15, 512) ?>.filter(id => ITEMS.some(i => i.id === id)));
    let activeIdx = -1;

    // Türkçe karaktere ve büyük/küçük harfe duyarsız normalizasyon (1:1 uzunluk korunur)
    const TR = {'İ':'i','I':'i','ı':'i','Ş':'s','ş':'s','Ğ':'g','ğ':'g','Ü':'u','ü':'u','Ö':'o','ö':'o','Ç':'c','ç':'c'};
    const norm = s => [...(s || '')].map(ch => TR[ch] || ch.toLowerCase()).join('');
    const esc  = s => (s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    const initials = n => (n || '?').split(/\s+/).map(w => w[0] || '').slice(0, 2).join('').toUpperCase() || '?';
    const avCls = id => 'g' + (parseInt(id, 10) % 6);

    function highlight(name, q) {
        if (!q) return esc(name);
        const idx = norm(name).indexOf(norm(q));
        if (idx < 0) return esc(name);
        return esc(name.slice(0, idx)) + '<b class="cms-hl">' + esc(name.slice(idx, idx + q.length)) + '</b>' + esc(name.slice(idx + q.length));
    }

    function filtered() {
        const q = norm(input.value.trim());
        return q ? ITEMS.filter(i => norm(i.name).includes(q) || norm(i.sub).includes(q)) : ITEMS;
    }

    function renderChips() {
        chipsEl.innerHTML = [...sel].map(id => {
            const it = ITEMS.find(i => i.id === id);
            if (!it) return '';
            return `<span class="cms-chip">
                <span class="cms-av ${avCls(it.id)}">${esc(initials(it.name))}</span>
                <span class="cms-chip-name">${esc(it.name)}</span>
                <button type="button" class="cms-chip-x" data-id="${esc(it.id)}" title="Kaldır"><i class="fas fa-xmark"></i></button>
            </span>`;
        }).join('');
        chipsEl.querySelectorAll('.cms-chip-x').forEach(b =>
            b.addEventListener('click', e => { e.stopPropagation(); toggleItem(b.dataset.id); }));
        input.placeholder = sel.size ? 'Başka şirket ara…' : (ITEMS.length ? 'Şirket ara veya seçin…' : 'Kayıtlı şirket yok');
    }

    function renderList() {
        const items = filtered();
        activeIdx = Math.min(activeIdx, items.length - 1);
        const q = input.value.trim();
        if (!items.length) {
            listEl.innerHTML = `<div class="cms-nores"><i class="fas fa-building-circle-xmark"></i>"${esc(q)}" ile eşleşen şirket yok</div>`;
        } else {
            listEl.innerHTML = items.map((it, ix) => `
                <button type="button" class="cms-row ${sel.has(it.id) ? 'sel' : ''} ${ix === activeIdx ? 'active' : ''}" data-id="${esc(it.id)}" role="option" aria-selected="${sel.has(it.id)}">
                    <span class="cms-av ${avCls(it.id)}">${esc(initials(it.name))}</span>
                    <span class="cms-row-meta">
                        <span class="cms-row-name d-block">${highlight(it.name, q)}</span>
                        ${it.sub ? `<span class="cms-row-sub">${esc(it.sub)}</span>` : ''}
                    </span>
                    <span class="cms-check"><i class="fas fa-check"></i></span>
                </button>`).join('');
            listEl.querySelectorAll('.cms-row').forEach(r =>
                r.addEventListener('click', () => toggleItem(r.dataset.id)));
        }
        countEl.textContent = sel.size ? `${sel.size} şirket seçili` : `${ITEMS.length} şirket`;
        clearBt.classList.toggle('show', sel.size > 0);
    }

    function syncHidden() {
        hidden.innerHTML = [...sel].map(id => `<input type="hidden" name="company_ids[]" value="${esc(id)}">`).join('');
    }

    function toggleItem(id) {
        const adding = !sel.has(id);
        adding ? sel.add(id) : sel.delete(id);
        syncHidden(); renderChips(); renderList();
        if (adding) autofillBilling(id);
        input.focus();
    }

    // ── Seçilen şirketin fatura bilgilerini forma doldur ──
    // Kullanıcının elle girdiği değerler ezilmez; yalnızca boş alanlar ve
    // daha önce bu bileşenin doldurduğu (data-cms-auto) alanlar güncellenir.
    function autofillBilling(id) {
        const it = ITEMS.find(i => i.id === id);
        const form = root.closest('form');
        if (!it || !it.bill || !form) return;
        let filled = 0;
        Object.entries(it.bill).forEach(([name, val]) => {
            if (!val) return;
            const f = form.querySelector(`[name="${CSS.escape(name)}"]`);
            if (!f) return;
            if (f.value.trim() && f.dataset.cmsAuto !== '1') return;
            f.value = val;
            f.dataset.cmsAuto = '1';
            f.classList.remove('cms-flash'); void f.offsetWidth; f.classList.add('cms-flash');
            filled++;
        });
        if (filled) showNote(`<i class="fas fa-file-invoice"></i><span><b>${esc(it.name)}</b> kartından fatura bilgileri dolduruldu — isterseniz düzenleyebilirsiniz.</span>`);
    }

    let noteT = null;
    function showNote(html) {
        let n = root.querySelector('.cms-note');
        if (!n) { n = document.createElement('div'); n.className = 'cms-note'; root.appendChild(n); }
        n.innerHTML = html;
        n.classList.add('show');
        clearTimeout(noteT);
        noteT = setTimeout(() => n.classList.remove('show'), 4000);
    }

    // Alana elle müdahale edilirse otomatik doldurma işaretini kaldır
    const ownerForm = root.closest('form');
    if (ownerForm) ownerForm.addEventListener('input', e => {
        if (e.isTrusted && e.target?.dataset?.cmsAuto === '1') delete e.target.dataset.cmsAuto;
    });

    window.cmsClearAll = function () {
        sel.clear();
        syncHidden(); renderChips(); renderList();
        input.focus();
    };

    function open()  { root.classList.add('open'); control.setAttribute('aria-expanded', 'true'); renderList(); }
    function close() { root.classList.remove('open'); control.setAttribute('aria-expanded', 'false'); activeIdx = -1; }

    control.addEventListener('click', () => { if (!input.disabled) { input.focus(); open(); } });
    input.addEventListener('focus', () => { control.classList.add('focus'); open(); });
    input.addEventListener('blur',  () => control.classList.remove('focus'));
    input.addEventListener('input', () => { activeIdx = -1; open(); renderList(); });

    input.addEventListener('keydown', e => {
        const items = filtered();
        if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
            e.preventDefault(); open();
            activeIdx = e.key === 'ArrowDown'
                ? (activeIdx + 1) % items.length
                : (activeIdx <= 0 ? items.length - 1 : activeIdx - 1);
            renderList();
            listEl.querySelectorAll('.cms-row')[activeIdx]?.scrollIntoView({ block: 'nearest' });
        } else if (e.key === 'Enter') {
            e.preventDefault();
            const pick = items[activeIdx >= 0 ? activeIdx : 0];
            if (pick) { toggleItem(pick.id); input.value = ''; renderList(); }
        } else if (e.key === 'Escape') {
            close(); input.blur();
        } else if (e.key === 'Backspace' && !input.value && sel.size) {
            toggleItem([...sel].pop());
        }
    });

    document.addEventListener('click', e => { if (!root.contains(e.target)) close(); });

    syncHidden(); renderChips(); renderList();
})();
</script>
<?php $__env->stopPush(); ?>
<?php endif; ?>
<?php /**PATH C:\xampp\htdocs\acente\resources\views/agency/customers/partials/company-multiselect.blade.php ENDPATH**/ ?>