<?php $__env->startPush('scripts'); ?>
    
    <?php
        $customerJson = $customers->map(function ($c) {
            return [
                'id' => (string) $c->id, 
                'name' => trim($c->first_name . ' ' . $c->last_name), 
                'first_name' => $c->first_name,
                'last_name' => $c->last_name,
                'phone' => $c->phone ?? '', 
                'email' => $c->email ?? '',
                'gender' => $c->gender,
                'national_id' => $c->national_id,
                'birth_date' => $c->birth_date ? $c->birth_date->format('Y-m-d') : null
            ]; 
        })->values();
        $preSelId = (string) (old('customer_id', $reservation->customer_id ?? ''));
    ?>
    <script>
        const URL_PRODUCTS = '<?php echo e(route("agency.sales.api.products-by-type")); ?>';
        const URL_CUSTOMER_PASSENGERS = '<?php echo e(route("agency.sales.api.customer-passengers")); ?>';
        
        const EXISTING_PASSENGERS = <?php echo json_encode($reservation->passengers->map(function($p) {
            return [
                'id' => $p->id,
                'first_name' => $p->first_name,
                'last_name' => $p->last_name,
                'gender' => $p->gender,
                'birth_date' => $p->birth_date ? $p->birth_date->format('Y-m-d') : null,
                'national_id' => $p->national_id,
                'phone' => $p->phone,
                'email' => $p->email,
                'relationship' => $p->relationship,
                'room_number' => $p->pivot->room_number,
                'seat_number' => $p->pivot->seat_number,
                'special_request' => $p->pivot->special_request,
            ];
        })); ?>;
        window.DATA = <?php echo json_encode($customerJson); ?>;
        window.PRE = <?php echo json_encode($preSelId); ?>;

        (function () {
            let lpTimer, isLP = false;
            function startLP(id, el) {
                if (!id || id === '0') return;
                isLP = false;
                el.classList.add('lp-holding');
                lpTimer = setTimeout(() => {
                    isLP = true;
                    el.classList.remove('lp-holding');
                    if (typeof closeD === 'function') closeD();
                    if (typeof openCustomerDrawer === 'function') openCustomerDrawer(id);
                }, 1000);
            }
            function stopLP(el) {
                clearTimeout(lpTimer);
                if (el) el.classList.remove('lp-holding');
            }

            function n(s) { return (s || '').toLowerCase().replace(/ğ/g, 'g').replace(/ü/g, 'u').replace(/ş/g, 's').replace(/ı/g, 'i').replace(/ö/g, 'o').replace(/ç/g, 'c').replace(/İ/g, 'i').replace(/Ğ/g, 'g').replace(/Ü/g, 'u').replace(/Ş/g, 's').replace(/Ö/g, 'o').replace(/Ç/g, 'c'); }
            function eh(s) { return (s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
            function hl(t, q) { if (!q) return eh(t); const i = n(t).indexOf(n(q)); if (i < 0) return eh(t); return eh(t.slice(0, i)) + '<mark>' + eh(t.slice(i, i + q.length)) + '</mark>' + eh(t.slice(i + q.length)); }
            const COLS = ['linear-gradient(135deg,#6366f1,#8b5cf6)', 'linear-gradient(135deg,#ec4899,#f43f5e)', 'linear-gradient(135deg,#0ea5e9,#06b6d4)', 'linear-gradient(135deg,#10b981,#059669)', 'linear-gradient(135deg,#f59e0b,#ef4444)'];
            function avc(name) { return COLS[(name || 'A').charCodeAt(0) % COLS.length]; }
            function ini(name) { return (name || '?').split(/\s+/).map(w => w[0] || '').slice(0, 2).join('').toUpperCase() || '?'; }

            const drop = document.createElement('div'); drop.className = 'csp-drop'; drop.id = 'cspDrop';
            drop.innerHTML = `<div class="csp-sw"><i class="fas fa-search"></i><input class="csp-inp" id="cspInp" type="text" placeholder="İsim, telefon veya e-posta…" autocomplete="off"><button type="button" class="csp-xbtn" id="cspXbtn"><i class="fas fa-times"></i></button></div><div class="csp-list" id="cspList"></div><div class="csp-empty" id="cspEmpty"><i class="fas fa-user-slash"></i><span id="cspEmptyTxt">Sonuç bulunamadı</span></div>`;
            document.body.appendChild(drop);

            const inp = drop.querySelector('#cspInp'), list = drop.querySelector('#cspList'), emptyEl = drop.querySelector('#cspEmpty'), emptyTxt = drop.querySelector('#cspEmptyTxt'), xbtn = drop.querySelector('#cspXbtn');
            const hid = document.getElementById('cspHidden'), trig = document.getElementById('cspTrigger'), avEl = document.getElementById('cspAv'), phEl = document.getElementById('cspPh'), nmEl = document.getElementById('cspNm'), sbEl = document.getElementById('cspSb'), card = document.getElementById('cspCard'), cardAv = document.getElementById('cspCardAv'), cardNm = document.getElementById('cspCardNm'), cardMt = document.getElementById('cspCardMt'), cardLk = document.getElementById('cspCardLk'), infoEl = document.getElementById('cspInfo');
            let open = false, foc = -1;

            function pos() { const r = trig.getBoundingClientRect(); drop.style.left = r.left + 'px'; drop.style.width = r.width + 'px'; drop.style.top = (window.innerHeight - r.bottom > 250 ? r.bottom + 4 : (r.top - 260)) + 'px'; }
            function openD() { if (open) return; open = true; trig.classList.add('open'); drop.classList.add('open'); pos(); inp.value = ''; xbtn.style.display = 'none'; render(''); setTimeout(() => inp.focus(), 40); }
            function closeD() { if (!open) return; open = false; trig.classList.remove('open'); drop.classList.remove('open'); foc = -1; }

            function render(q) {
                const nq = n(q), fil = nq ? window.DATA.filter(c => n(c.name + ' ' + c.phone + ' ' + c.email).includes(nq)) : window.DATA;
                list.innerHTML = ''; foc = -1;
                if (!fil.length) { emptyEl.style.display = 'flex'; emptyTxt.textContent = q ? `"${eh(q)}" için bulunamadı` : 'Seçilecek müşteri yok'; return; }
                emptyEl.style.display = 'none';
                fil.slice(0, 80).forEach((c, i) => {
                    const sub = [c.phone, c.email].filter(Boolean).join(' · ');
                    const row = document.createElement('div'); row.className = 'csp-row'; row.dataset.idx = i;
                    row.innerHTML = `<div class="csp-rav" style="background:${avc(c.name)}">${eh(ini(c.name))}</div><div><div class="csp-rname">${hl(c.name, q)}</div>${sub ? '<div class="csp-rsub">' + eh(sub) + '</div>' : ''}</div>`;
                    row.addEventListener('mousedown', e => { if (e.button === 0) startLP(c.id, row); });
                    row.addEventListener('mouseup', e => { stopLP(row); });
                    row.addEventListener('click', e => { 
                        if (isLP) { isLP = false; return; }
                        sel(c); 
                    });
                    row.addEventListener('mouseleave', () => stopLP(row));
                    row.addEventListener('touchstart', () => startLP(c.id, row), {passive:true});
                    row.addEventListener('touchend', () => stopLP(row));
                    
                    list.appendChild(row);
                });
            }
            function sel(c) { 
                hid.value = c.id; 
                const col = avc(c.name), av = ini(c.name), sub = [c.phone, c.email].filter(Boolean).join(' · '); 
                avEl.style.background = col; 
                avEl.textContent = av; 
                phEl.style.display = 'none';
                nmEl.textContent = c.name; 
                nmEl.style.display = 'block'; 
                sbEl.style.display = sub ? 'block' : 'none';
                if(infoEl) infoEl.style.display = 'block';

                // Sidebar summary update
                const sumEl = document.getElementById('customerSummaryHtml');
                const detCard = document.getElementById('customerDetailsCard');
                if (sumEl && detCard) {
                    sumEl.innerHTML = `
                        <div style="font-weight:700; color:#1e293b; font-size:0.9rem; margin-bottom:4px">${c.name}</div>
                        ${c.phone ? `<div><i class="fas fa-phone-alt me-2" style="width:14px;color:#94a3b8"></i>${c.phone}</div>` : ''}
                        ${c.email ? `<div class="mt-1"><i class="fas fa-envelope me-2" style="width:14px;color:#94a3b8"></i>${c.email}</div>` : ''}
                        ${c.national_id ? `<div class="mt-1"><i class="fas fa-id-card me-2" style="width:14px;color:#94a3b8"></i>${c.national_id}</div>` : ''}
                    `;
                    detCard.style.display = 'block';
                }

                cardAv.style.background = col; 
                cardAv.textContent = av; 
                cardNm.textContent = c.name; 
                cardMt.textContent = sub || 'İletişim bilgisi yok'; 
                cardLk.href = '/agency/customers/' + c.id; 
                card.style.display = ''; 
                closeD(); 
            }
            window.cspClear = function () { 
                hid.value = ''; 
                avEl.style.background = 'var(--cp)'; 
                avEl.innerHTML = '<i class="fas fa-user"></i>'; 
                phEl.style.display = ''; 
                if(infoEl) infoEl.style.display = 'none'; 
                card.style.display = 'none'; 
                nmEl.style.display = 'none'; 
                sbEl.style.display = 'none'; 
                const detCard = document.getElementById('customerDetailsCard');
                if (detCard) detCard.style.display = 'none';
            };
            trig.addEventListener('click', (e) => { 
                if (isLP) { isLP = false; return; }
                open ? closeD() : openD(); 
            });
            trig.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open ? closeD() : openD(); } });

            // Trigger long-press on trig
            trig.addEventListener('mousedown', e => { if (e.button === 0 && hid.value) startLP(hid.value, trig); });
            trig.addEventListener('mouseup', () => stopLP(trig));
            trig.addEventListener('mouseleave', () => stopLP(trig));
            trig.addEventListener('touchstart', () => { if (hid.value) startLP(hid.value, trig); }, {passive:true});
            trig.addEventListener('touchend', () => stopLP(trig));

            inp.addEventListener('input', function () { xbtn.style.display = this.value ? '' : 'none'; render(this.value); });
            xbtn.addEventListener('click', () => { inp.value = ''; xbtn.style.display = 'none'; render(''); inp.focus(); });
            inp.addEventListener('keydown', e => { const rows = list.querySelectorAll('.csp-row'); if (!rows.length) return; if (e.key === 'ArrowDown') { e.preventDefault(); rows[foc]?.classList.remove('focused'); foc = Math.min(foc + 1, rows.length - 1); rows[foc].classList.add('focused'); rows[foc].scrollIntoView({ block: 'nearest' }); } else if (e.key === 'ArrowUp') { e.preventDefault(); rows[foc]?.classList.remove('focused'); foc = Math.max(foc - 1, 0); rows[foc].classList.add('focused'); rows[foc].scrollIntoView({ block: 'nearest' }); } else if (e.key === 'Enter' && foc >= 0) { e.preventDefault(); const nq = n(inp.value); const fil = nq ? window.DATA.filter(c => n(c.name + ' ' + c.phone + ' ' + c.email).includes(nq)) : window.DATA; const item = fil[parseInt(rows[foc].dataset.idx)]; if (item) sel(item); } else if (e.key === 'Escape') closeD(); });
            window.addEventListener('scroll', () => { if (open) pos(); }, true);
            window.addEventListener('resize', () => { if (open) pos(); });
            document.addEventListener('click', e => { if (!trig.contains(e.target) && !drop.contains(e.target)) closeD(); });
            if (window.PRE) { const f = window.DATA.find(c => c.id == window.PRE); if (f) sel(f); }

            // Selected card long press
            const cardEl = document.getElementById('cspCard');
            if (cardEl) {
                cardEl.addEventListener('mousedown', e => { if (e.button === 0 && hid.value) startLP(hid.value, cardEl); });
                cardEl.addEventListener('mouseup', () => stopLP(cardEl));
                cardEl.addEventListener('mouseleave', () => stopLP(cardEl));
                cardEl.addEventListener('touchstart', () => { if (hid.value) startLP(hid.value, cardEl); }, {passive:true});
                cardEl.addEventListener('touchend', () => stopLP(cardEl));
            }
        })();

        function calcPrice() {
            const unitPrice = parseFloat(document.getElementById('unitPrice')?.value || 0);
            const childPrice = parseFloat(document.getElementById('childPrice')?.value || unitPrice * 0.5);
            const infantPrice = parseFloat(document.getElementById('infantPrice')?.value || 0);
            const adults = parseInt(document.getElementById('adultCount')?.value || 1);
            const children = parseInt(document.getElementById('childCount')?.value || 0);
            const infants = parseInt(document.getElementById('infantCount')?.value || 0);
            const discountR = parseFloat(document.getElementById('discountRate')?.value || 0);
            const tax = parseFloat(document.getElementById('taxAmount')?.value || 0);
            const paid = parseFloat(document.getElementById('paidAmount')?.value || 0);

            const subtotal = (unitPrice * adults) + (childPrice * children) + (infantPrice * infants);
            const discountAmt = subtotal * (discountR / 100);
            const total = Math.max(0, subtotal - discountAmt + tax);
            const remaining = Math.max(0, total - paid);
            const fmt = n => n.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

            if (document.getElementById('displaySubtotal')) document.getElementById('displaySubtotal').textContent = fmt(subtotal) + ' ₺';
            if (document.getElementById('displayDiscount')) document.getElementById('displayDiscount').textContent = '- ' + fmt(discountAmt) + ' ₺';
            if (document.getElementById('displayTax')) document.getElementById('displayTax').textContent = '+ ' + fmt(tax) + ' ₺';
            if (document.getElementById('displayTotal')) document.getElementById('displayTotal').textContent = fmt(total) + ' ₺';
            if (document.getElementById('displayRemaining')) document.getElementById('displayRemaining').textContent = fmt(remaining) + ' ₺';

            if (document.getElementById('hiddenTotal')) document.getElementById('hiddenTotal').value = total.toFixed(2);
            if (document.getElementById('hiddenRemaining')) document.getElementById('hiddenRemaining').value = remaining.toFixed(2);
            if (document.getElementById('hiddenSubtotal')) document.getElementById('hiddenSubtotal').value = subtotal.toFixed(2);
            if (document.getElementById('hiddenDiscountAmt')) document.getElementById('hiddenDiscountAmt').value = discountAmt.toFixed(2);
        }

        /* ─── PRODUCT TYPE & PRODUCT SELECTION ─── */
        // ─── PAGINATION MANAGER ───
        class PaginatedManager {
            constructor(options) {
                this.container = document.getElementById(options.containerId);
                this.searchControl = document.getElementById(options.searchId);
                this.paginationBox = document.getElementById(options.paginationId);
                this.searchInput = document.getElementById(options.searchInputId);
                this.prevBtn = document.getElementById(options.prevBtnId);
                this.nextBtn = document.getElementById(options.nextBtnId);
                this.pageInfo = document.getElementById(options.pageInfoId);
                this.totalPageInfo = document.getElementById(options.totalPageInfoId);
                
                this.allData = [];
                this.filteredData = [];
                this.perPage = options.perPage || 10;
                this.currentPage = 1;
                this.renderItem = options.renderItem;
                this.onSearch = options.onSearch || null;

                if (this.searchInput) {
                    this.searchInput.addEventListener('input', () => {
                        this.currentPage = 1;
                        this.applyFilter();
                    });
                }
                if (this.prevBtn) {
                    this.prevBtn.addEventListener('click', () => {
                        if (this.currentPage > 1) {
                            this.currentPage--;
                            this.render();
                        }
                    });
                }
                if (this.nextBtn) {
                    this.nextBtn.addEventListener('click', () => {
                        if (this.currentPage < this.totalPages) {
                            this.currentPage++;
                            this.render();
                        }
                    });
                }
            }

            setData(data) {
                this.allData = data;
                this.currentPage = 1;
                if (this.searchInput) this.searchInput.value = '';
                this.applyFilter();
                
                if (this.searchControl) {
                    this.searchControl.style.display = data.length > 5 ? '' : 'none';
                }
            }

            applyFilter() {
                const query = this.searchInput ? this.searchInput.value.toLowerCase().trim() : '';
                if (this.onSearch) {
                    this.filteredData = this.allData.filter(item => this.onSearch(item, query));
                } else {
                    this.filteredData = this.allData;
                }
                this.totalPages = Math.ceil(this.filteredData.length / this.perPage);
                this.render();
            }

            render() {
                if (!this.container) return;
                this.container.innerHTML = '';
                const start = (this.currentPage - 1) * this.perPage;
                const end = start + this.perPage;
                const pageItems = this.filteredData.slice(start, end);

                pageItems.forEach(item => {
                    const el = this.renderItem(item);
                    this.container.appendChild(el);
                });

                if (this.paginationBox) {
                    this.paginationBox.style.display = this.totalPages > 1 ? 'flex' : 'none';
                    if (this.pageInfo) this.pageInfo.textContent = this.currentPage;
                    if (this.totalPageInfo) this.totalPageInfo.textContent = this.totalPages;
                    if (this.prevBtn) this.prevBtn.disabled = this.currentPage === 1;
                    if (this.nextBtn) this.nextBtn.disabled = this.currentPage === this.totalPages;
                }
                this.container.style.opacity = '0';
                setTimeout(() => { this.container.style.opacity = '1'; this.container.style.transition = 'opacity 0.2s'; }, 10);
            }
        }

        const prodMgr = new PaginatedManager({
            containerId: 'productList',
            searchId: 'productSearchContainer',
            paginationId: 'productPagination',
            searchInputId: 'productSearchInput',
            prevBtnId: 'prevProduct',
            nextBtnId: 'nextProduct',
            pageInfoId: 'prodPage',
            totalPageInfoId: 'prodTotalPage',
            perPage: 8,
            renderItem: (p) => {
                const el = document.createElement('div');
                el.className = 'prod-item';
                if (document.getElementById('productIdInput').value == p.id) el.classList.add('sel');
                el.dataset.id = p.id; el.dataset.price = p.base_price; el.dataset.currency = p.currency;
                el.innerHTML = `<div><div style="font-size:.86rem;font-weight:600;color:var(--text-main)">${p.name}</div></div><div class="prod-price">${parseFloat(p.base_price).toLocaleString('tr-TR', {minimumFractionDigits:2})} ${p.currency}</div>`;
                el.addEventListener('click', () => selectProduct(el));
                return el;
            },
            onSearch: (p, q) => p.name.toLowerCase().includes(q)
        });

        document.querySelectorAll('.pt-btn').forEach(btn => {
            btn.addEventListener('click', async function() {
                document.querySelectorAll('.pt-btn').forEach(b => b.classList.remove('sel'));
                this.classList.add('sel');
                const ptId = this.querySelector('input').value;
                
                // Load products
                try {
                    const r = await fetch(`${URL_PRODUCTS}?product_type_id=${ptId}`, { headers: {'X-Requested-With': 'XMLHttpRequest'} });
                    const d = await r.json();
                    const pCard = document.getElementById('productCard');
                    const pList = document.getElementById('productList');
                    const pInput = document.getElementById('productIdInput');
                    
                    if (d.products && d.products.length > 0) {
                        pCard.style.display = 'block';
                        prodMgr.setData(d.products);
                    } else {
                        pList.innerHTML = `<div style="padding:1rem;background:#f8fafc;border-radius:10px;border:1.5px dashed #cbd5e1;text-align:center;color:#64748b;font-size:0.83rem">
                            <i class="fas fa-info-circle me-2" style="color:#6366f1"></i>
                            Seçili hizmet türü için ürün bulunamadı.
                        </div>`;
                        pCard.style.display = 'block';
                        document.getElementById('productSearchContainer').style.display = 'none';
                        document.getElementById('productPagination').style.display = 'none';
                    }
                } catch(e) { console.error(e); }
            });
        });

        function selectProduct(el) {
            document.querySelectorAll('.prod-item').forEach(i => i.classList.remove('sel'));
            el.classList.add('sel');
            document.getElementById('productIdInput').value = el.dataset.id;
            
            // Update price if empty or first time
            const up = document.getElementById('unitPrice');
            if (!up.value || up.value == "0") {
                up.value = el.dataset.price;
                calcPrice();
            }
        }

        // Initial product listeners
        document.querySelectorAll('.prod-item').forEach(el => {
            el.addEventListener('click', () => selectProduct(el));
        });

        /* ═══ YOLCU YÖNETİMİ ══════════════════════════════════════════════ */
        let customerPassengers = [];
        
        async function fetchCustomerPassengers(customerId) {
            if (!customerId) {
                customerPassengers = [];
                updatePassengerForms();
                return;
            }
            try {
                const r = await fetch(URL_CUSTOMER_PASSENGERS + '?customer_id=' + customerId);
                const d = await r.json();
                customerPassengers = d.passengers || [];
                updatePassengerForms();

                // Müşteri bilgisini DATA içinden bulup 1. yolcuyu dolduralım
                const mainCust = window.DATA.find(c => c.id == customerId);
                if (mainCust) {
                    fillFirstPassengerWithCustomer(mainCust);
                }
            } catch (e) {
                console.error('Yolcu listesi alınamadı:', e);
            }
        }

        function fillFirstPassengerWithCustomer(c) {
            const firstForm = document.querySelector('.p-form-item');
            if (!firstForm) return;
            
            // Eğer form boşsa (yeni ürün seçimi veya yeni müşteri seçimi) doldur
            const fnInp = firstForm.querySelector('.p-fn');
            if (fnInp && !fnInp.value) {
                fnInp.value = c.first_name || '';
                firstForm.querySelector('.p-ln').value = c.last_name || '';
                firstForm.querySelector('.p-ph').value = c.phone || c.email || '';
                if (c.gender) firstForm.querySelector('.p-gn').value = c.gender;
                if (c.national_id) firstForm.querySelector('.p-ni').value = c.national_id;
                if (c.birth_date) firstForm.querySelector('.p-bd').value = c.birth_date;
            }
        }

        function updatePassengerForms() {
            const container = document.getElementById('passengerContainer');
            if (!container) return;
            const emptyMsg = document.getElementById('passengerEmpty');
            const ac = parseInt(document.getElementById('adultCount').value || 0);
            const cc = parseInt(document.getElementById('childCount').value || 0);
            const ic = parseInt(document.getElementById('infantCount').value || 0);
            const total = ac + cc + ic;

            if (total === 0) {
                container.innerHTML = '';
                if (emptyMsg) emptyMsg.style.display = 'block';
                return;
            }
            if (emptyMsg) emptyMsg.style.display = 'none';

            const currentCount = container.querySelectorAll('.p-form-item').length;
            
            if (currentCount !== total) {
                if (total > currentCount) {
                    for (let i = currentCount; i < total; i++) {
                        addPassengerForm(i);
                    }
                } else {
                    for (let i = currentCount - 1; i >= total; i--) {
                        container.children[i]?.remove();
                    }
                }
            }

            // Etiketleri ve Seçenekleri güncelle
            const opts = customerPassengers.map(p => `<option value="${p.id}" data-p='${JSON.stringify(p)}'>${p.first_name} ${p.last_name}</option>`).join('');
            
            container.querySelectorAll('.p-form-item').forEach((item, idx) => {
                // Dropdown seçeneklerini güncelle
                const sel = item.querySelector('.p-select');
                if (sel) {
                    const currentVal = sel.value;
                    sel.innerHTML = `<option value="">-- Yeni Yolcu Gir --</option>${opts}`;
                    
                    // İlk yüklemede veya müşteri değiştiğinde eşleşen yolcuyu seç
                    if (EXISTING_PASSENGERS && EXISTING_PASSENGERS[idx]) {
                        sel.value = EXISTING_PASSENGERS[idx].id;
                    } else if (currentVal) {
                        sel.value = currentVal;
                    }
                }

                // Etiketleri güncelle
                const labelDiv = item.querySelector('.p-type-label');
                if (labelDiv) {
                    let label = '';
                    if (idx < ac) label = (idx + 1) + '. Yetişkin';
                    else if (idx < ac + cc) label = (idx - ac + 1) + '. Çocuk';
                    else label = (idx - ac - cc + 1) + '. Bebek';
                    
                    if (idx === 0) label += ' (Ana Yolcu/Müşteri)';
                    labelDiv.textContent = label;
                }
            });
        }

        function addPassengerForm(index) {
            const container = document.getElementById('passengerContainer');
            const div = document.createElement('div');
            div.className = 'p-form-item';
            div.style.padding = '1.25rem';
            div.style.background = '#fcfdfe';
            div.style.border = '1.5px solid #eef2f6';
            div.style.borderRadius = '14px';
            div.style.position = 'relative';

            const opts = customerPassengers.map(p => `<option value="${p.id}" data-p='${JSON.stringify(p)}'>${p.first_name} ${p.last_name}</option>`).join('');
            
            div.innerHTML = `
                <div style="font-size:.8rem;font-weight:700;color:var(--cp);margin-bottom:1rem;display:flex;align-items:center;gap:8px">
                    <div style="width:24px;height:24px;border-radius:6px;background:var(--cp);color:#fff;display:flex;align-items:center;justify-content:center;font-size:10px">${index + 1}</div>
                    <span class="p-type-label"></span>
                </div>
                <div class="row g-3">
                    <div class="col-md-4">
                        <div class="fl">
                            <label>Kayıtlı Yolcu Seç</label>
                            <select class="field-input p-select" onchange="fillPassenger(this, ${index})">
                                <option value="">-- Yeni Yolcu Gir --</option>
                                ${opts}
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="fl">
                            <label>Ad <span style="color:#ef4444">*</span></label>
                            <input type="text" name="passengers[${index}][first_name]" class="field-input p-fn" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="fl">
                            <label>Soyad <span style="color:#ef4444">*</span></label>
                            <input type="text" name="passengers[${index}][last_name]" class="field-input p-ln" required>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="fl">
                            <label>Cinsiyet</label>
                            <select name="passengers[${index}][gender]" class="field-input p-gn">
                                <option value="">Seçiniz</option>
                                <option value="male">Erkek</option>
                                <option value="female">Kadın</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="fl">
                            <label>T.C. / Pasaport</label>
                            <input type="text" name="passengers[${index}][national_id]" class="field-input p-ni">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="fl">
                            <label>Doğum Tarihi</label>
                            <input type="date" name="passengers[${index}][birth_date]" class="field-input p-bd">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="fl">
                            <label>E-posta / Telefon</label>
                            <input type="text" name="passengers[${index}][phone]" class="field-input p-ph" placeholder="İletişim...">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="fl">
                            <label>Yakınlık</label>
                            <input type="text" name="passengers[${index}][relationship]" class="field-input p-rel" placeholder="Eşi, çocuğu vb.">
                    </div>
                    </div>
                    <div class="col-md-4">
                        <div class="fl">
                            <label>Koltuk / Oda No</label>
                            <input type="text" name="passengers[${index}][room_number]" class="field-input p-rn" placeholder="Örn: Oda 302, Koltuk 12">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="fl">
                            <label>Özel İstek</label>
                            <input type="text" name="passengers[${index}][special_request]" class="field-input p-sr">
                        </div>
                    </div>
                    <input type="hidden" name="passengers[${index}][id]" class="p-id">
                </div>
            `;
            container.appendChild(div);

            // Eğer mevcut yolculardan biri bu indexe karşılık geliyorsa doldur
            if (EXISTING_PASSENGERS && EXISTING_PASSENGERS[index]) {
                const p = EXISTING_PASSENGERS[index];
                div.querySelector('.p-id').value = p.id || '';
                div.querySelector('.p-fn').value = p.first_name || '';
                div.querySelector('.p-ln').value = p.last_name || '';
                div.querySelector('.p-gn').value = p.gender || '';
                div.querySelector('.p-ni').value = p.national_id || '';
                if (p.birth_date) div.querySelector('.p-bd').value = p.birth_date;
                div.querySelector('.p-ph').value = p.phone || p.email || '';
                div.querySelector('.p-rel').value = p.relationship || '';
                div.querySelector('.p-rn').value = p.room_number || p.seat_number || '';
                div.querySelector('.p-sr').value = p.special_request || '';
            }
        }

        function fillPassenger(select, index) {
            const row = select.closest('.p-form-item');
            const val = select.value;
            if (!val) {
                row.querySelector('.p-id').value = '';
                row.querySelector('.p-fn').value = '';
                row.querySelector('.p-ln').value = '';
                row.querySelectorAll('input, select').forEach(i => { if(!i.classList.contains('p-select')) i.value = ''; });
                return;
            }
            const opt = select.options[select.selectedIndex];
            const p = JSON.parse(opt.dataset.p);
            
            row.querySelector('.p-id').value = p.id;
            row.querySelector('.p-fn').value = p.first_name;
            row.querySelector('.p-ln').value = p.last_name;
            row.querySelector('.p-gn').value = p.gender || '';
            row.querySelector('.p-ni').value = p.national_id || '';
            if (p.birth_date) row.querySelector('.p-bd').value = p.birth_date.split('T')[0];
            row.querySelector('.p-ph').value = p.phone || p.email || '';
            row.querySelector('.p-rel').value = p.relationship || '';
        }

        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === "attributes" && mutation.attributeName === "value") {
                    fetchCustomerPassengers(mutation.target.value);
                }
            });
        });
        const hidEl = document.getElementById('cspHidden');
        if (hidEl) observer.observe(hidEl, { attributes: true });

        updatePassengerForms();
        if (document.getElementById('cspHidden') && document.getElementById('cspHidden').value) {
            fetchCustomerPassengers(document.getElementById('cspHidden').value);
        }

        window.updatePassengerForms = updatePassengerForms;
        window.fillPassenger = fillPassenger;

        // İlk yüklemede ürünler varsa mgr'ye aktar
        const initialProds = [];
        document.querySelectorAll('#productList .prod-item').forEach(el => {
            initialProds.push({
                id: el.dataset.id,
                name: el.querySelector('div div').textContent.trim(),
                base_price: el.dataset.price,
                currency: el.dataset.currency,
                has_dates: el.dataset.hasdates === '1'
            });
        });
        if (initialProds.length > 0) {
            prodMgr.setData(initialProds);
            if (document.getElementById('productSearchContainer')) document.getElementById('productSearchContainer').style.display = initialProds.length > 5 ? '' : 'none';
        }

        // Initialize tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });

    </script>
<?php $__env->stopPush(); ?>
<?php /**PATH C:\xampp\htdocs\acente\resources\views/agency/sales/edit/scripts.blade.php ENDPATH**/ ?>