@push('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', $preselectedCustomer?->id ?? ''));
    @endphp
    <script>
        window.DATA = {!! json_encode($customerJson) !!};
        window.PRE = {!! json_encode($preSelId) !!};
        /* ═══ URLS ═══════════════════════════════════════════════════════ */
        const URL_PRODUCTS = '{{ route("agency.sales.api.products-by-type") }}';
        const URL_DATES = '{{ route("agency.sales.api.product-dates") }}';
        const URL_QUICK_CUSTOMER = '{{ route("agency.sales.api.quick-customer") }}';
        const URL_CUSTOMER_PASSENGERS = '{{ route("agency.sales.api.customer-passengers") }}';


        /* ═══ UTILS ═══════════════════════════════════════════════════════ */
        function n(s) {
            return (s || '').toLowerCase()
                .replace(/İ/g, 'i').replace(/ı/g, 'i')
                .replace(/Ğ/g, 'g').replace(/ğ/g, 'g')
                .replace(/Ü/g, 'u').replace(/ü/g, 'u')
                .replace(/Ş/g, 's').replace(/ş/g, 's')
                .replace(/Ö/g, 'o').replace(/ö/g, 'o')
                .replace(/Ç/g, 'c').replace(/ç/g, 'c')
                .trim();
        }
        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() || '?'; }

        /* ═══ CUSTOMER PICKER ════════════════════════════════════════════ */
        const DATA = {!! json_encode($customerJson) !!};
        const PRE = {!! 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');
            }

            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');
            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.innerHTML = q ? `"${eh(q)}" için müşteri bulunamadı.<br><button type="button" class="btn btn-sm btn-link mt-1 p-0 fw-bold" style="color:var(--cp);text-decoration:none" onclick="new bootstrap.Modal('#quickAddCustomerModal').show()"><i class="fas fa-plus-circle me-1"></i>"${eh(q)}" ismini yeni ekle?</button>` : 'Kayıtlı 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', e => {
                        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'; 
                
                // 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 = 'linear-gradient(135deg,#6366f1,#8b5cf6)'; 
                avEl.innerHTML = '<i class="fas fa-user"></i>'; 
                phEl.style.display = ''; 
                nmEl.style.display = 'none'; 
                sbEl.style.display = 'none'; 
                card.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();
            });
            
            // Trigger long-press when a customer is already selected
            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));

            trig.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open ? closeD() : openD(); } });
            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(); });
            /* ─── QUICK CUSTOMER SAVE ─── */
            const qBtn = document.getElementById('btnQuickCustomerSave'), qForm = document.getElementById('quickCustomerForm');
            if (qBtn) {
                qBtn.addEventListener('click', async () => {
                    const fd = new FormData(qForm);
                    qBtn.disabled = true;
                    qBtn.querySelector('.btn-text').classList.add('d-none');
                    qBtn.querySelector('.btn-spinner').classList.remove('d-none');
                    try {
                        const r = await fetch(URL_QUICK_CUSTOMER, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
                        const d = await r.json();
                        if (d.success) {
                            const newC = { id:String(d.customer.id), name:d.customer.full_name, phone:d.customer.phone, email:d.customer.email };
                            window.DATA.push(newC);
                            sel(newC);
                            const mEl = document.getElementById('quickAddCustomerModal');
                            const modal = bootstrap.Modal.getInstance(mEl) || new bootstrap.Modal(mEl);
                            modal.hide();
                            qForm.reset();
                            if(typeof Swal !== 'undefined') {
                                Swal.fire({ icon:'success', title:'Başarılı', text:'Müşteri eklendi ve seçildi.', timer:1500, showConfirmButton:false });
                            }
                        } else {
                            let msg = 'Hata oluştu.'; if (d.errors) msg = Object.values(d.errors).flat().join('\n');
                            alert(msg);
                        }
                    } catch(e) { console.error(e); alert('Sistem hatası oluştu.'); }
                    finally {
                        qBtn.disabled = false;
                        qBtn.querySelector('.btn-text').classList.remove('d-none');
                        qBtn.querySelector('.btn-spinner').classList.add('d-none');
                    }
                });
            }

        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));
            }
        })();

        /* ═══ ÜRÜN TİPİ SEÇİCİ ══════════════════════════════════════════ */
        let currentTypeCode = null;
        let selectedProductData = null;
        let selectedDateData = null;

        // ─── 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.clearBtn = document.getElementById(options.clearBtnId);
                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', () => {
                        if (this.clearBtn) this.clearBtn.style.display = this.searchInput.value ? 'flex' : 'none';
                        this.currentPage = 1;
                        this.applyFilter();
                    });
                }
                if (this.clearBtn) {
                    this.clearBtn.addEventListener('click', () => {
                        this.searchInput.value = '';
                        this.clearBtn.style.display = 'none';
                        this.currentPage = 1;
                        this.applyFilter();
                        this.searchInput.focus();
                    });
                }
                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();
                
                // Arama kutusunu göster/gizle
                if (this.searchControl) {
                    this.searchControl.style.display = data.length > 0 ? '' : 'none';
                }
            }

            applyFilter() {
                const query = this.searchInput ? n(this.searchInput.value) : '';
                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() {
                this.container.innerHTML = '';
                const start = (this.currentPage - 1) * this.perPage;
                const end = start + this.perPage;
                const pageItems = this.filteredData.slice(start, end);

                if (pageItems.length === 0) {
                    this.container.innerHTML = '<div style="padding:2rem;text-align:center;color:#94a3b8;font-size:.85rem"><i class="fas fa-search me-2"></i>Sonuç bulunamadı.</div>';
                } else {
                    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.totalPages === 0;
                }
                
                // Animasyon efekti
                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',
            clearBtnId: 'productSearchClear',
            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.dataset.hasdates = p.has_dates ? '1' : '0';
                
                const codeHtml = p.code ? `<span class="badge bg-light text-muted border" style="font-size:10px;padding:2px 6px">${eh(p.code)}</span>` : '';
                const cityHtml = p.departure_city ? `<span><i class="fas fa-map-marker-alt me-1 text-primary"></i>${eh(p.departure_city)}</span>` : '';
                const durHtml = p.duration ? `<span><i class="fas fa-clock me-1"></i>${p.duration} ${p.duration > 12 ? 'Saat' : 'Gün'}</span>` : '';
                const mealHtml = p.meal_included ? `<span><i class="fas fa-utensils me-1"></i>Yemek Dahil</span>` : '';
                const locHtml = p.visit_locations ? `<div style="font-size:.68rem;color:#94a3b8;margin-top:2px" class="text-truncate"><i class="fas fa-route me-1"></i>${eh(p.visit_locations)}</div>` : '';

                el.innerHTML = `
                    <div style="flex:1">
                        <div class="d-flex align-items-center gap-2 mb-1">
                            ${codeHtml}
                            <div style="font-size:.86rem;font-weight:700;color:var(--text)">${eh(p.name)}</div>
                        </div>
                        <div class="d-flex align-items-center gap-3" style="font-size:.72rem;color:var(--muted)">
                            ${cityHtml}
                            ${durHtml}
                            ${mealHtml}
                        </div>
                        ${locHtml}
                    </div>
                    <div class="prod-price">${parseFloat(p.base_price).toFixed(2)} ${p.currency}</div>
                `;
                el.addEventListener('click', () => selectProduct(el, p));
                return el;
            },
            onSearch: (p, q) => n(p.name).includes(q)
        });

        const dateMgr = new PaginatedManager({
            containerId: 'dateGrid',
            searchId: 'dateSearchContainer',
            paginationId: 'datePagination',
            searchInputId: 'dateSearchInput',
            clearBtnId: 'dateSearchClear',
            prevBtnId: 'prevDate',
            nextBtnId: 'nextDate',
            pageInfoId: 'datePage',
            totalPageInfoId: 'dateTotalPage',
            perPage: 8,
            renderItem: (dt) => {
                const card = document.createElement('div');
                card.className = 'date-card';
                if (document.getElementById('tourDateIdInput').value == dt.id) card.classList.add('sel');
                const dur = dt.duration_days > 1 ? `<span class="info-badge ibg-blue" style="margin-top:4px"><i class="fas fa-moon me-1"></i>${dt.duration_days} gün</span>` : '';
                const guar = dt.guarantee_departure ? `<div class="dc-badge"><i class="fas fa-check-circle"></i>Garantili Kalkış</div>` : '';
                const dep = dt.departure_time ? `<div class="dc-end" style="margin-top:2px"><i class="fas fa-clock me-1"></i>${dt.departure_time}${dt.return_time ? ' – ' + dt.return_time : ''}</div>` : '';
                card.innerHTML = `<div class="dc-date">${dt.start_date_display}${dt.end_date_display && dt.end_date !== dt.start_date ? ' – ' + dt.end_date_display : ''}</div>${dep}${dur}<div class="dc-price">${parseFloat(dt.adult_price).toFixed(2)} ${dt.currency}</div><div class="dc-cap"><i class="fas fa-users me-1"></i>${dt.remaining_capacity ?? '∞'} kişilik yer</div>${guar}`;
                card.addEventListener('click', () => selectDate(card, dt));
                return card;
            },
            onSearch: (dt, q) => {
                if (!q) return true;
                const searchStr = dt.search_text || n(dt.start_date_display + ' ' + (dt.end_date_display || ''));
                return searchStr.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 radio = this.querySelector('input[type=radio]');
                radio.checked = true;
                const ptId = radio.value;

                selectedProductData = null; selectedDateData = null;
                document.getElementById('productIdInput').value = '';
                document.getElementById('tourDateIdInput').value = '';
                document.getElementById('tourDateCard').style.display = 'none';

                try {
                    const r = await fetch(URL_PRODUCTS + '?product_type_id=' + ptId);
                    const d = await r.json();
                    currentTypeCode = d.type_code;

                    // Ürün listesi
                    if (d.products.length) {
                        prodMgr.setData(d.products);
                        document.getElementById('productCard').style.display = '';
                        document.getElementById('productCardTitle').textContent = this.querySelector('.pt-label').textContent + ' Seçimi';
                    } else {
                        // Ürün yoksa bilgilendirici mesaj göster
                        document.getElementById('productList').innerHTML = `<div style="padding:.9rem 1rem;background:#f8fafc;border-radius:10px;border:1.5px dashed #cbd5e1;text-align:center;color:#64748b;font-size:.83rem">
                            <i class="fas fa-info-circle me-2" style="color:#6366f1"></i>
                            Bu hizmet türü için henüz ürün tanımlanmamış.
                            Manuel satış oluşturabilirsiniz (tarih ve fiyatı kendiniz girebilirsiniz).
                        </div>`;
                        document.getElementById('productCard').style.display = '';
                        document.getElementById('productCardTitle').textContent = this.querySelector('.pt-label').textContent + ' Seçimi';
                        document.getElementById('productSearchContainer').style.display = 'none';
                        document.getElementById('productPagination').style.display = 'none';
                    }

                    // Dinamik alanlar
                    buildExtraFields(d.extra_fields, this.querySelector('.pt-label').textContent);

                    // Tarih kartını göster/gizle
                    updateDateVisibility(false);

                    // Fiyat badge
                    document.getElementById('priceSourceBadge').style.display = 'none';
                } catch (err) { console.error(err); }
            });
        });

        async function selectProduct(el, p) {
            document.querySelectorAll('.prod-item').forEach(e => e.classList.remove('sel'));
            el.classList.add('sel');
            document.getElementById('productIdInput').value = p.id;
            selectedProductData = p;
            selectedDateData = null;
            document.getElementById('tourDateIdInput').value = '';

            if (p.has_dates) {
                await loadDates(p.id);
                document.getElementById('tourDateCard').style.display = '';
                document.getElementById('simpleDateCard').style.display = 'none';
            } else {
                document.getElementById('tourDateCard').style.display = 'none';
                document.getElementById('simpleDateCard').style.display = '';
                setPrice(p.base_price, 0, 0, p.currency, 'Ürün Fiyatı');
            }
        }

        async function loadDates(productId) {
            const grid = document.getElementById('dateGrid');
            const loading = document.getElementById('dateLoading');
            const noDate = document.getElementById('noDateMsg');
            grid.innerHTML = ''; loading.style.display = ''; noDate.style.display = 'none';
            document.getElementById('customDateFields').style.display = 'none';

            try {
                const r = await fetch(URL_DATES + '?product_id=' + productId);
                const d = await r.json();
                loading.style.display = 'none';

                if (!d.has_dates || !d.dates.length) {
                    noDate.style.display = '';
                    document.getElementById('customDateFields').style.display = '';
                    document.getElementById('dateSearchContainer').style.display = 'none';
                    document.getElementById('datePagination').style.display = 'none';
                    return;
                }
                dateMgr.setData(d.dates);
            } catch (e) { loading.style.display = 'none'; noDate.style.display = ''; }
        }

        function selectDate(card, dt) {
            document.querySelectorAll('.date-card').forEach(c => c.classList.remove('sel'));
            card.classList.add('sel');
            selectedDateData = dt;
            document.getElementById('tourDateIdInput').value = dt.id;

            // Tarih alanlarını doldur
            const sd = document.getElementById('startDate'); if (sd) sd.value = dt.start_date;
            const ed = document.getElementById('endDate'); if (ed) ed.value = dt.end_date || dt.start_date;
            const sd2 = document.getElementById('startDateSimple'); if (sd2) sd2.value = dt.start_date;
            const ed2 = document.getElementById('endDateSimple'); if (ed2) ed2.value = dt.end_date || dt.start_date;

            setPrice(dt.adult_price, dt.child_price, dt.infant_price, dt.currency, 'Tarih Fiyatı');
        }

        function setPrice(adult, child, infant, currency, source) {
            document.getElementById('unitPrice').value = parseFloat(adult || 0).toFixed(2);
            document.getElementById('childPrice').value = parseFloat(child || 0).toFixed(2);
            document.getElementById('infantPrice').value = parseFloat(infant || 0).toFixed(2);
            const cs = document.getElementById('currencySelect');
            if (currency && cs) { Array.from(cs.options).forEach(o => { if (o.value === currency) o.selected = true; }); }

            const badge = document.getElementById('priceSourceBadge');
            badge.innerHTML = `<span class="info-badge ibg-green"><i class="fas fa-check-circle me-1"></i>${source} olarak dolduruldu. Üzerinde düzenleme yapabilirsiniz.</span>`;
            badge.style.display = '';
            calcPrice();
        }

        function updateDateVisibility(hasDates) {
            document.getElementById('simpleDateCard').style.display = hasDates ? 'none' : '';
        }

        function buildExtraFields(fields, typeName) {
            const cnt = document.getElementById('extraContainer');
            cnt.innerHTML = '';
            if (!fields || !fields.length) { document.getElementById('extraCard').style.display = 'none'; return; }
            fields.forEach(f => {
                const wrap = document.createElement('div'); wrap.className = 'fl';
                let inp = '';
                if (f.type === 'select') { const opts = Object.entries(f.options).map(([v, l]) => `<option value="${v}">${l}</option>`).join(''); inp = `<select name="extra_data[${f.key}]" class="fi"><option value="">Seçiniz</option>${opts}</select>`; }
                else if (f.type === 'boolean') { inp = `<select name="extra_data[${f.key}]" class="fi"><option value="">Seçiniz</option><option value="1">Evet</option><option value="0">Hayır</option></select>`; }
                else { inp = `<input type="${f.type === 'number' ? 'number' : 'text'}" name="extra_data[${f.key}]" class="fi" placeholder="${f.label}">`; }
                wrap.innerHTML = `<label>${f.label}</label>${inp}`; cnt.appendChild(wrap);
            });
            document.getElementById('extraCard').style.display = '';
            document.getElementById('extraTitle').textContent = typeName + ' Detayları';
        }

        /* Özel tarih toggle */
        document.getElementById('customDateToggle').addEventListener('click', function () {
            const f = document.getElementById('customDateFields');
            const vis = f.style.display !== 'none';
            f.style.display = vis ? 'none' : '';
            this.innerHTML = vis ? '<i class="fas fa-plus"></i> Özel tarih gir' : '<i class="fas fa-times"></i> Özel tarihi kapat';
        });

        /* ═══ ÖDEME DURUMU ═══════════════════════════════════════════════ */
        function togglePayment() {
            const ps = document.getElementById('paymentStatus').value;
            document.getElementById('paidAmountWrap').style.display = ['partial', 'paid'].includes(ps) ? '' : 'none';
            if (ps === 'paid') { const t = parseFloat(document.getElementById('hTotal').value || 0); document.getElementById('paidAmount').value = t.toFixed(2); }
            calcPrice();
        }

        /* ═══ FİYAT HESAPLAMA ════════════════════════════════════════════ */
        function calcPrice() {
            const up = parseFloat(document.getElementById('unitPrice')?.value || 0);
            const cp = parseFloat(document.getElementById('childPrice')?.value || 0);
            const ip = parseFloat(document.getElementById('infantPrice')?.value || 0);
            const a = parseInt(document.getElementById('adultCount')?.value || 1);
            const c = parseInt(document.getElementById('childCount')?.value || 0);
            const inf = parseInt(document.getElementById('infantCount')?.value || 0);
            const dr = parseFloat(document.getElementById('discountRate')?.value || 0);
            const tax = parseFloat(document.getElementById('taxAmount')?.value || 0);
            const pd = parseFloat(document.getElementById('paidAmount')?.value || 0);
            const sub = (up * a) + (cp * c) + (ip * inf);
            const disc = sub * (dr / 100);
            const tot = Math.max(0, sub - disc + tax);
            const rem = Math.max(0, tot - pd);
            const fmt = x => x.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            document.getElementById('dSub').textContent = fmt(sub) + ' ₺';
            document.getElementById('dDisc').textContent = '- ' + fmt(disc) + ' ₺';
            document.getElementById('dTax').textContent = '+ ' + fmt(tax) + ' ₺';
            document.getElementById('dTotal').textContent = fmt(tot) + ' ₺';
            document.getElementById('dPaid').textContent = fmt(pd) + ' ₺';
            document.getElementById('dRem').textContent = fmt(rem) + ' ₺';
            document.getElementById('hTotal').value = tot.toFixed(2);
            document.getElementById('hRem').value = rem.toFixed(2);
            document.getElementById('hSub').value = sub.toFixed(2);
            document.getElementById('hDisc').value = disc.toFixed(2);
        }
        calcPrice();

        /* ═══ 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 veya sadece bu müşteri için sıfırlanmışsa 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');
            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 = '';
                emptyMsg.style.display = 'block';
                return;
            }
            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 güncelle (Yetişkin/Çocuk/Bebek ayrımı için)
            container.querySelectorAll('.p-form-item').forEach((item, idx) => {
                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');
            const customerId = document.getElementById('cspHidden').value;
            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="fi 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 class="req">*</span></label>
                            <input type="text" name="passengers[${index}][first_name]" class="fi p-fn" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="fl">
                            <label>Soyad <span class="req">*</span></label>
                            <input type="text" name="passengers[${index}][last_name]" class="fi p-ln" required>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="fl">
                            <label>Cinsiyet</label>
                            <select name="passengers[${index}][gender]" class="fi 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="fi p-ni" data-digits="off">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="fl">
                            <label>Doğum Tarihi</label>
                            <input type="date" name="passengers[${index}][birth_date]" class="fi 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="fi 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="fi 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="fi 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="fi p-sr">
                        </div>
                    </div>
                    <input type="hidden" name="passengers[${index}][id]" class="p-id">
                </div>
            `;
            container.appendChild(div);
        }

        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);
                }
            });
        });
        observer.observe(document.getElementById('cspHidden'), { attributes: true });

        updatePassengerForms();
        if (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('[style*="font-weight:700"]').textContent.trim(),
                code: el.dataset.code,
                base_price: el.dataset.price,
                currency: el.dataset.currency,
                has_dates: el.dataset.hasdates === '1',
                duration: el.dataset.duration,
                departure_city: el.dataset.city,
                visit_locations: el.dataset.locations,
                meal_included: el.dataset.meal === '1'
            });
        });
        if (initialProds.length > 0) {
            prodMgr.setData(initialProds);
            document.getElementById('productSearchContainer').style.display = '';
        }

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

    </script>
@endpush
