{{-- Quick-view "Tarihler & Fiyatlar" sekmesi — stiller + etkileşim (kart/tablo, filtre, kopyala, oto-bitiş) --}}
<style>
    .qd-wrap { --qd-cols: 1.6fr .65fr 1.05fr .55fr 1fr .75fr 1.35fr auto; }

    /* Toolbar */
    .qd-toolbar { display:flex; align-items:center; justify-content:space-between; gap:.75rem; flex-wrap:wrap; margin-bottom:1.1rem; }
    .qd-tb-left { display:flex; align-items:center; gap:.5rem; flex-wrap:wrap; }
    .qd-tb-right { display:flex; align-items:center; gap:.6rem; }
    .qd-search { position:relative; display:flex; align-items:center; }
    .qd-search > i { position:absolute; left:.7rem; color:#94a3b8; font-size:.8rem; pointer-events:none; }
    .qd-search input { border:1.5px solid #e2e8f0; background:#f8fafc; border-radius:10px; padding:.5rem .7rem .5rem 2rem; font-size:.82rem; color:#0f172a; transition:.15s; width:170px; }
    .qd-search.qd-search-date input { width:150px; }
    .qd-search input:focus { outline:none; border-color:#2563eb; background:#fff; box-shadow:0 0 0 3px rgba(37,99,235,.1); }
    .qd-statusfilter { border:1.5px solid #e2e8f0; background:#f8fafc; border-radius:10px; padding:.5rem .7rem; font-size:.82rem; color:#0f172a; }

    .qd-viewtoggle { display:inline-flex; background:#f1f5f9; border-radius:10px; padding:3px; }
    .qd-vt-btn { width:34px; height:30px; display:grid; place-items:center; border:none; background:transparent; color:#64748b; border-radius:8px; cursor:pointer; font-size:.85rem; transition:.15s; }
    .qd-vt-btn:hover { color:#2563eb; }
    .qd-vt-btn.active { background:#fff; color:#2563eb; box-shadow:0 1px 3px rgba(15,23,42,.12); }

    .qd-addbtn { display:inline-flex; align-items:center; gap:.5rem; border:none; border-radius:10px; padding:.55rem 1rem; font-size:.82rem; font-weight:700; cursor:pointer; color:#fff; background:linear-gradient(135deg,#2563eb,#1e40af); transition:.15s; }
    .qd-addbtn:hover { transform:translateY(-1px); box-shadow:0 4px 14px rgba(37,99,235,.32); }

    /* Ekleme formu */
    .qd-addform { display:none; background:#fff; border:1.5px solid #dbeafe; border-radius:18px; padding:1.35rem; margin-bottom:1.25rem; box-shadow:0 8px 28px rgba(37,99,235,.08); }
    .qd-addform.open { display:block; animation:qdIn .18s ease; }
    @keyframes qdIn { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:none; } }
    .qd-addform-head { font-size:.95rem; font-weight:800; color:#1e3a8a; display:flex; align-items:center; gap:.55rem; margin-bottom:1rem; }
    .qd-addform-head i { color:#2563eb; }
    .qd-addform-foot { display:flex; justify-content:flex-end; gap:.6rem; margin-top:1rem; padding-top:1rem; border-top:1px dashed #eef2f7; }

    /* Kopyala barı */
    .qd-copybar { display:flex; align-items:center; gap:.65rem; background:linear-gradient(135deg,#faf5ff,#eff6ff); border:1px solid #e9d5ff; border-radius:12px; padding:.6rem .85rem; margin-bottom:1rem; flex-wrap:wrap; }
    .qd-copybar > i { color:#9333ea; }
    .qd-copybar label { font-size:.76rem; font-weight:700; color:#6b21a8; margin:0; }
    .qd-copybar select { flex:1; min-width:180px; }

    /* Form alanları */
    .qd-fieldset { margin-bottom:1.1rem; }
    .qd-fs-title { font-size:.78rem; font-weight:800; color:#334155; text-transform:uppercase; letter-spacing:.03em; display:flex; align-items:center; gap:.5rem; margin-bottom:.7rem; }
    .qd-fs-title i { color:#2563eb; font-size:.85rem; }
    .qd-form { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:.7rem; }
    .qd-form + .qd-form { margin-top:.7rem; }
    .qd-fld { display:flex; flex-direction:column; gap:.28rem; }
    .qd-fld.full { grid-column:1/-1; }
    .qd-fld > label { font-size:.68rem; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:.02em; display:flex; align-items:baseline; flex-wrap:wrap; gap:.2rem .35rem; line-height:1.25; }
    .qd-fld > label small { text-transform:none; font-weight:600; color:#94a3b8; letter-spacing:0; }
    /* Etiket 1 veya 2 satır olsa da input'ları aynı hizada (alta) tut */
    .qd-fld > .qd-inp { margin-top:auto; }
    .qd-auto { background:#dcfce7; color:#166534; font-size:.58rem; padding:1px 6px; border-radius:6px; font-weight:800; }
    .qd-inp { width:100%; border:1.5px solid #e2e8f0; background:#f8fafc; border-radius:9px; padding:.5rem .7rem; font-size:.85rem; color:#0f172a; transition:.15s; }
    .qd-inp:focus { outline:none; border-color:#2563eb; background:#fff; box-shadow:0 0 0 3px rgba(37,99,235,.1); }
    textarea.qd-inp { min-height:60px; resize:vertical; }
    .qd-checks { display:flex; gap:1.25rem; flex-wrap:wrap; margin-top:.8rem; font-size:.82rem; font-weight:600; color:#475569; }
    .qd-checks input { accent-color:#2563eb; margin-right:.35rem; }
    .qd-hint { font-size:.72rem; color:#94a3b8; margin:.5rem 0 .6rem; }
    .qd-stage-row { align-items:end; margin-bottom:.5rem; }
    .qd-stage-act { justify-content:flex-end; }

    /* Esnek deadline kuralı */
    .qd-rule .qd-rule-row { display:flex; flex-wrap:wrap; gap:.5rem; align-items:center; }
    .qd-rule .qd-rule-rel { display:flex; flex-wrap:wrap; gap:.5rem; align-items:center; }
    .qd-rule .qd-rule-mode { border-color:#c7d2fe; background:#eef2ff; font-weight:600; }

    /* Liste */
    .qd-list { margin-top:.25rem; }
    .qd-head { display:none; grid-template-columns:var(--qd-cols); gap:.6rem; padding:.55rem .9rem; font-size:.68rem; font-weight:800; text-transform:uppercase; letter-spacing:.04em; color:#94a3b8; }
    .qd-head .qd-h-acts { text-align:right; }

    .qd-row { transition:.15s; }
    .qd-main { display:grid; gap:.75rem; }
    .qd-cell { min-width:0; }
    .qd-date-range { display:block; font-weight:800; color:#0f172a; font-size:.92rem; }
    .qd-code { display:block; font-size:.72rem; color:#94a3b8; font-weight:600; margin-top:1px; }
    .qd-c-dur { font-size:.83rem; color:#475569; font-weight:600; }
    .qd-c-dur i { color:#94a3b8; }
    .qd-price-val { font-size:1rem; font-weight:800; color:#16a34a; }
    .qd-c-price small { color:#94a3b8; font-weight:600; font-size:.72rem; }
    .qd-price-sub { display:block; font-size:.68rem; color:#d97706; font-weight:700; margin-top:1px; }
    .qd-c-room { font-size:.85rem; font-weight:700; color:#334155; }
    .qd-c-room i { color:#94a3b8; }
    .qd-capbar { height:6px; background:#f1f5f9; border-radius:99px; overflow:hidden; margin-bottom:3px; }
    .qd-capbar i { display:block; height:100%; background:#22c55e; border-radius:99px; }
    .qd-capbar i.warn { background:#f59e0b; }
    .qd-capbar i.danger { background:#ef4444; }
    .qd-cap-txt { font-size:.72rem; color:#64748b; font-weight:600; }
    .qd-c-acts { display:inline-flex; gap:5px; align-items:center; }
    /* Kalkış etiketleri (kesin kalkış, dolu, son yerler, yeni, sezon…) — sarıp taşar */
    .qd-badges { display:flex; flex-wrap:wrap; gap:4px; align-items:center; }
    .qd-badges .pqv-badge { font-size:.66rem; padding:3px 8px; }

    /* ── KART MODU (varsayılan) ── */
    .qd-list:not(.qd-mode-table) .qd-head { display:none; }
    .qd-list:not(.qd-mode-table) .qd-row { border:1px solid #eef2f7; border-radius:16px; margin-bottom:.9rem; box-shadow:0 1px 3px rgba(15,23,42,.04); overflow:hidden; }
    .qd-list:not(.qd-mode-table) .qd-row:hover { border-color:#bfdbfe; box-shadow:0 8px 22px rgba(37,99,235,.09); }
    .qd-list:not(.qd-mode-table) .qd-main { grid-template-columns:repeat(auto-fit,minmax(105px,1fr)); gap:.85rem 1rem; padding:1.1rem 1.2rem; align-items:end; }
    .qd-list:not(.qd-mode-table) .qd-c-date { grid-column:1/-1; }
    .qd-list:not(.qd-mode-table) .qd-c-acts { grid-column:1/-1; justify-content:flex-end; border-top:1px dashed #eef2f7; margin-top:.35rem; padding-top:.85rem; }
    .qd-list:not(.qd-mode-table) .qd-cell[data-label]::before { content:attr(data-label); display:block; font-size:.62rem; text-transform:uppercase; letter-spacing:.03em; color:#94a3b8; font-weight:800; margin-bottom:4px; }

    /* ── TABLO MODU ── */
    .qd-list.qd-mode-table { border:1px solid #eef2f7; border-radius:14px; overflow:hidden; }
    .qd-list.qd-mode-table .qd-head { display:grid; background:#f8fafc; border-bottom:1px solid #e2e8f0; }
    .qd-list.qd-mode-table .qd-row { border-bottom:1px solid #f1f5f9; }
    .qd-list.qd-mode-table .qd-row:last-of-type { border-bottom:none; }
    .qd-list.qd-mode-table .qd-row:hover { background:#f8fafc; }
    .qd-list.qd-mode-table .qd-main { grid-template-columns:var(--qd-cols); align-items:center; padding:.65rem .9rem; }
    .qd-list.qd-mode-table .qd-cell[data-label]::before { display:none; }
    .qd-list.qd-mode-table .qd-c-acts { justify-content:flex-end; }
    .qd-list.qd-mode-table .qd-date-range { font-size:.86rem; }
    .qd-list.qd-mode-table .qd-price-val { font-size:.9rem; }

    .qd-editform { padding:0 1.2rem 1.2rem; }
    .qd-list.qd-mode-table .qd-editform { padding:1rem .9rem 1.2rem; background:#fbfdff; border-top:1px dashed #e2e8f0; }

    .qd-noresult { text-align:center; padding:2.5rem 1rem; color:#94a3b8; }
    .qd-noresult i { font-size:2rem; color:#cbd5e1; margin-bottom:.6rem; display:block; }
    .qd-noresult p { margin:0; font-size:.88rem; }

    /* ── Açılır-kapanır bölüm (yaş aralıkları, pazaryeri fiyatları…) — kapalı başlar ── */
    .qd-fold-head { display:flex; align-items:center; gap:.7rem; width:100%; text-align:left; font-family:inherit; background:#f8fafc; border:1.5px dashed #e2e8f0; border-radius:12px; padding:.6rem .8rem; cursor:pointer; transition:border-color .15s, background .15s; }
    .qd-fold-head:hover { border-color:#c7d2fe; background:#f5f7ff; }
    .qd-fold.open .qd-fold-head { border-style:solid; border-color:#c7d2fe; background:#eef2ff; border-bottom-left-radius:0; border-bottom-right-radius:0; }
    .qd-fold-ico { width:30px; height:30px; border-radius:9px; display:grid; place-items:center; background:#e0e7ff; color:#4338ca; font-size:.85rem; flex-shrink:0; }
    .qd-fold-info { flex:1; min-width:0; display:flex; flex-direction:column; gap:1px; }
    .qd-fold-info b { font-size:.78rem; font-weight:800; color:#334155; text-transform:uppercase; letter-spacing:.03em; }
    .qd-fold-info small { font-size:.72rem; color:#64748b; font-weight:600; }
    .qd-fold-chip { font-size:.62rem; font-weight:800; border-radius:20px; padding:3px 9px; white-space:nowrap; }
    .qd-fold-chip.is-auto { color:#4338ca; background:#e0e7ff; }
    .qd-fold-chip.is-custom { color:#92400e; background:#fef3c7; }
    .qd-fold-chip.is-empty { color:#64748b; background:#f1f5f9; }
    .qd-fold-chev { color:#94a3b8; font-size:.75rem; transition:transform .18s; }
    .qd-fold.open .qd-fold-chev { transform:rotate(180deg); }
    .qd-fold-body { border:1.5px solid #c7d2fe; border-top:none; border-radius:0 0 12px 12px; padding:.85rem .8rem; background:#fff; animation:qdIn .18s ease; }
    /* Fold içindeki pazaryeri bölümünün kendi üst boşluğunu sıfırla */
    .qd-fold-body .mpp-section { margin:0; }

    @media (max-width:640px) {
        .qd-search input { width:130px; }
        .qd-list.qd-mode-table .qd-head { display:none; }
        .qd-list.qd-mode-table .qd-main { grid-template-columns:repeat(auto-fit,minmax(105px,1fr)); }
        .qd-list.qd-mode-table .qd-cell[data-label]::before { content:attr(data-label); display:block; font-size:.62rem; text-transform:uppercase; color:#94a3b8; font-weight:800; margin-bottom:4px; }
    }
</style>

<script>
(function () {
    // ── Her render'da: kaydedilmiş görünüm modunu uygula ──
    document.querySelectorAll('.qd-list').forEach(function (list) {
        if (list.__qdInit) return;
        list.__qdInit = true;
        var mode = localStorage.getItem('pqv_dates_view') || 'card';
        qdApplyMode(list, mode);
    });

    function qdApplyMode(list, mode) {
        list.classList.toggle('qd-mode-table', mode === 'table');
        list.classList.toggle('qd-mode-card', mode !== 'table');
        var wrap = list.closest('.qd-wrap');
        if (wrap) wrap.querySelectorAll('[data-qd-view]').forEach(function (b) {
            b.classList.toggle('active', b.dataset.qdView === mode);
        });
    }
    window.qdApplyMode = qdApplyMode;

    function qdRunFilter(wrap) {
        var q = (wrap.querySelector('[data-qd-filter]') || {}).value || '';
        q = q.toLowerCase().trim();
        var from = (wrap.querySelector('[data-qd-from]') || {}).value || '';
        var st = (wrap.querySelector('[data-qd-status]') || {}).value || '';
        var shown = 0, rows = wrap.querySelectorAll('[data-qd-item]');
        rows.forEach(function (row) {
            var ok = true;
            if (q && (row.dataset.qdSearch || '').indexOf(q) === -1) ok = false;
            if (from && (row.dataset.qdDate || '') < from) ok = false;
            if (st && (row.dataset.qdStatus || '') !== st) ok = false;
            row.style.display = ok ? '' : 'none';
            if (ok) shown++;
        });
        var nr = wrap.querySelector('.qd-noresult');
        if (nr) nr.style.display = (rows.length > 0 && shown === 0) ? '' : 'none';
    }

    if (window.__qdDatesInit) return;
    window.__qdDatesInit = true;

    // Görünüm değiştir (kart/tablo) + hafızaya al
    document.addEventListener('click', function (e) {
        var b = e.target.closest('[data-qd-view]');
        if (!b) return;
        var wrap = b.closest('.qd-wrap'); if (!wrap) return;
        var list = wrap.querySelector('.qd-list'); if (!list) return;
        var mode = b.dataset.qdView;
        localStorage.setItem('pqv_dates_view', mode);
        qdApplyMode(list, mode);
    });

    // Ekleme formu aç/kapa
    document.addEventListener('click', function (e) {
        var b = e.target.closest('[data-qd-addtoggle]');
        if (!b) return;
        var wrap = b.closest('.qd-wrap'); if (!wrap) return;
        var f = wrap.querySelector('#qd-add-form');
        if (f) {
            f.classList.toggle('open');
            if (f.classList.contains('open')) { var s = f.querySelector('[data-qd-start]'); if (s) s.focus(); }
        }
    });

    // Açılır-kapanır bölüm (yaş aralıkları, pazaryeri fiyatları…)
    document.addEventListener('click', function (e) {
        var b = e.target.closest('[data-qd-fold-toggle]');
        if (!b) return;
        var box = b.closest('[data-qd-fold]'); if (!box) return;
        var body = box.querySelector('[data-qd-fold-body]');
        var open = box.classList.toggle('open');
        if (body) body.hidden = !open;
        b.setAttribute('aria-expanded', open ? 'true' : 'false');
    });

    // Yaş inputları değişince kapalı başlıktaki özet + rozet canlı güncellensin
    document.addEventListener('input', function (e) {
        var inp = e.target.closest('[data-qd-age]');
        if (!inp) return;
        var box = inp.closest('[data-qd-fold]'); if (!box) return;
        var g = function (k) { var el = box.querySelector('[data-qd-age="' + k + '"]'); return (el && el.value !== '') ? el.value : null; };
        var f = function (a, b) { return (a === null && b === null) ? '—' : ((a === null ? '?' : a) + '–' + (b === null ? '?' : b) + ' yaş'); };
        var sum = box.querySelector('[data-qd-ages-summary]');
        if (sum) sum.textContent = 'Çocuk ' + f(g('cmin'), g('cmax')) + ' · Bebek ' + f(g('imin'), g('imax'));
        var chip = box.querySelector('[data-qd-ages-chip]');
        if (chip) { chip.textContent = 'Bu tarihe özel'; chip.className = 'qd-fold-chip is-custom'; }
    });

    // Pazaryeri fiyat fold'unun kapalı başlık özeti: ana pazarın taban yetişkin fiyatı
    function qdMppFoldSummary(fold) {
        var sum = fold.querySelector('[data-qd-mpp-summary]');
        if (!sum) return;
        var txt = 'Henüz fiyat girilmedi';
        var primary = fold.querySelector('.mpp-card.is-primary');
        if (primary) {
            var base = primary.querySelector('[data-mpp-classrow][data-is-base="1"]') || primary;
            var inp = base.querySelector('[data-mpp-field="adult_price"]');
            var v = (inp && inp.value !== '') ? parseFloat(inp.value) : NaN;
            if (!isNaN(v)) txt = 'Yetişkin ' + v.toLocaleString('tr-TR') + ' ' + (primary.dataset.currency || '') + ' · ana pazar';
        }
        sum.textContent = txt;
    }

    // Fiyat hücreleri değişince özet canlı güncellensin
    document.addEventListener('input', function (e) {
        var inp = e.target.closest('[data-mpp-field]');
        if (!inp) return;
        var fold = inp.closest('[data-qd-mppfold]');
        if (fold) qdMppFoldSummary(fold);
    });

    // Filtreleme
    document.addEventListener('input', function (e) {
        var el = e.target.closest('[data-qd-filter],[data-qd-from]');
        if (!el) return; var w = el.closest('.qd-wrap'); if (w) qdRunFilter(w);
    });
    document.addEventListener('change', function (e) {
        var el = e.target.closest('[data-qd-status],[data-qd-from]');
        if (!el) return; var w = el.closest('.qd-wrap'); if (w) qdRunFilter(w);
    });

    // Fiyatları başka tarihten kopyala
    document.addEventListener('change', function (e) {
        var sel = e.target.closest('[data-qd-copyfrom]');
        if (!sel) return;
        var opt = sel.selectedOptions[0];
        if (!opt || !opt.value) return;
        var prices = {};
        try { prices = JSON.parse(opt.dataset.prices || '{}'); } catch (_) {}
        var form = sel.closest('form'); if (!form) return;
        Object.keys(prices).forEach(function (k) {
            var v = prices[k];
            var inp = form.querySelector('[name="' + k + '"]');
            if (inp && v !== null && v !== undefined && v !== '') inp.value = v;
        });
        // Kopyalanan yaş değerleri kapalı "Yaş Aralıkları" başlığındaki özete yansısın
        var ageInp = form.querySelector('[data-qd-age]');
        if (ageInp) ageInp.dispatchEvent(new Event('input', { bubbles: true }));
        // Kopyalanan pazaryeri fiyatları da kapalı başlık özetine yansısın
        form.querySelectorAll('[data-qd-mppfold]').forEach(qdMppFoldSummary);

        // Pazaryeri × sınıf fiyat matrisini de doldur (kaynak tarihin fiyatları)
        var mpPrices = {};
        try { mpPrices = JSON.parse(opt.dataset.mpPrices || '{}'); } catch (_) {}
        Object.keys(mpPrices).forEach(function (mpId) {
            var row = form.querySelector('[data-mpp-row][data-mp-id="' + mpId + '"]');
            if (!row) return;
            var classMap = mpPrices[mpId] || {};
            Object.keys(classMap).forEach(function (ck) {
                var cr = row.querySelector('[data-mpp-classrow][data-class-id="' + ck + '"]');
                if (!cr) return;
                var fields = classMap[ck] || {};
                Object.keys(fields).forEach(function (f) {
                    var v = fields[f];
                    var inp = cr.querySelector('[data-mpp-field="' + f + '"]');
                    if (!inp) return;
                    inp.value = (v === null || v === undefined) ? '' : v;
                    var isPrimary = row.classList.contains('is-primary');
                    var isBase = cr.getAttribute('data-is-base') === '1';
                    if (!(isPrimary && isBase)) inp.dataset.manual = inp.value.trim() === '' ? '' : '1';
                });
            });
        });

        sel.value = '';
        if (window.PQV) PQV.toast('Fiyatlar bu tarihe kopyalandı');
    });

    // Tarihi kopyala — "bitişten kaç gün sonra?" sor (periyot otomatik önerilir)
    document.addEventListener('click', function (e) {
        var b = e.target.closest('[data-qd-duplicate]');
        if (!b) return;
        e.preventDefault();
        var url = b.getAttribute('data-qd-duplicate');
        var tab = b.getAttribute('data-reload-tab') || 'dates';
        var suggest = b.getAttribute('data-suggest-offset');
        if (suggest === null || suggest === '') suggest = '7';

        var doDup = function (offset) {
            if (!window.PQV) return;
            PQV.send(url, 'POST', { offset_days: offset }).then(function (res) {
                if (res.data.success !== false && res.ok) { PQV.toast(res.data.message || 'Kopyalandı'); PQV.reload(tab, b); }
                else PQV.toast(res.data.message || 'Kopyalanamadı', 'error');
            });
        };

        if (typeof Swal === 'undefined') { doDup(parseInt(suggest, 10) || 0); return; }

        var ps = 'border:1px solid #dbeafe;background:#eff6ff;color:#1d4ed8;font-size:.75rem;font-weight:700;padding:6px 12px;border-radius:9px;cursor:pointer;transition:.15s';
        Swal.fire({
            title: 'Tarihi Kopyala',
            html:
                '<p style="font-size:.85rem;color:#475569;margin:.1rem 0 .7rem">Bu turun <b>bitişinden kaç gün sonrasına</b> kopyalansın?</p>' +
                '<input id="qdOffset" type="number" min="0" class="swal2-input" style="max-width:150px;margin-inline:auto" value="' + suggest + '">' +
                '<div style="display:flex;gap:.45rem;justify-content:center;flex-wrap:wrap;margin-top:.7rem">' +
                    '<button type="button" class="qd-preset" data-v="0" style="' + ps + '">Bittiği gibi</button>' +
                    '<button type="button" class="qd-preset" data-v="7" style="' + ps + '">1 hafta sonra</button>' +
                    '<button type="button" class="qd-preset" data-v="30" style="' + ps + '">1 ay sonra</button>' +
                '</div>' +
                '<p style="font-size:.72rem;color:#94a3b8;margin:.75rem 0 0">Öneri, turun tespit edilen periyoduna göre dolduruldu.</p>',
            showCancelButton: true,
            confirmButtonText: '<i class="fas fa-copy"></i> Kopyala',
            cancelButtonText: 'Vazgeç',
            confirmButtonColor: '#2563eb',
            didOpen: function (popup) {
                popup.querySelectorAll('.qd-preset').forEach(function (btn) {
                    btn.addEventListener('click', function () {
                        var inp = document.getElementById('qdOffset');
                        if (inp) inp.value = btn.getAttribute('data-v');
                    });
                });
            },
            preConfirm: function () {
                var inp = document.getElementById('qdOffset');
                var v = inp ? parseInt(inp.value, 10) : 0;
                if (isNaN(v) || v < 0) v = 0;
                return v;
            }
        }).then(function (res) { if (res.isConfirmed) doDup(res.value); });
    });

    // Deadline kuralı: mode değişince tarih/göreli alanlarını göster-gizle
    document.addEventListener('change', function (e) {
        var sel = e.target.closest('.qd-rule-mode');
        if (!sel) return;
        var rule = sel.closest('.qd-rule');
        if (!rule) return;
        var at = rule.querySelector('.qd-rule-at');
        var rel = rule.querySelector('.qd-rule-rel');
        if (at) at.style.display = sel.value === 'datetime' ? '' : 'none';
        if (rel) rel.style.display = sel.value === 'relative' ? '' : 'none';
    });

    // Başlangıç tarihinden otomatik bitiş tarihi (tur süresine göre)
    document.addEventListener('change', function (e) {
        var s = e.target.closest('[data-qd-start]');
        if (!s || !s.value) return;
        var wrap = s.closest('.qd-wrap');
        var dur = parseInt((wrap && wrap.dataset.qdDuration) || '1', 10) || 1;
        var form = s.closest('form');
        var end = form && form.querySelector('[data-qd-end]');
        if (end) {
            var p = s.value.split('-').map(Number);
            var d = new Date(p[0], p[1] - 1, p[2]);
            d.setDate(d.getDate() + dur - 1);
            var iso = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
            end.value = iso;
            end.min = s.value;
        }
    });

    // Bir sarmalayıcıdaki alanları toplu aç/kapat. Kapalıyken disabled → forma dahil edilmez.
    function qdSetSectionEnabled(wrap, on) {
        if (!wrap) return;
        wrap.style.display = on ? '' : 'none';
        wrap.querySelectorAll('input, select, textarea').forEach(function (el) { el.disabled = !on; });
    }

    // Özel ödeme planı aç/kapa
    document.addEventListener('change', function (e) {
        var cb = e.target.closest('[data-qd-cpp-toggle]');
        if (!cb) return;
        var fs = cb.closest('.qd-fieldset');
        qdSetSectionEnabled(fs && fs.querySelector('[data-qd-cpp-wrap]'), cb.checked);
    });

    // Ödeme aşaması ekle
    document.addEventListener('click', function (e) {
        var b = e.target.closest('[data-qd-stage-add]');
        if (!b) return;
        var wrap = b.closest('[data-qd-cpp-wrap]');
        var rows = wrap && wrap.querySelector('[data-qd-stage-rows]');
        if (!rows) return;
        var i = rows.children.length;
        var row = document.createElement('div');
        row.className = 'qd-form qd-stage-row';
        row.innerHTML =
            '<div class="qd-fld"><label>Etiket</label><input type="text" name="payment_schedule[' + i + '][label]" class="qd-inp" placeholder="Ör: Kapora"></div>' +
            '<div class="qd-fld"><label>Yüzde %</label><input type="number" min="0" max="100" name="payment_schedule[' + i + '][percent]" class="qd-inp"></div>' +
            '<div class="qd-fld"><label>Tetikleyici</label><select name="payment_schedule[' + i + '][trigger]" class="qd-inp">' +
                '<option value="at_booking">Rezervasyonda</option>' +
                '<option value="days_before_departure">Kalkıştan X gün önce</option>' +
                '<option value="on_departure">Kalkışta</option>' +
            '</select></div>' +
            '<div class="qd-fld"><label>Gün (X)</label><input type="number" min="0" name="payment_schedule[' + i + '][offset_days]" class="qd-inp"></div>' +
            '<div class="qd-fld qd-stage-act"><button type="button" class="pqv-iconbtn danger" data-qd-stage-remove title="Aşamayı sil"><i class="fas fa-times"></i></button></div>';
        rows.appendChild(row);
    });

    // Ödeme aşaması sil + kalanları yeniden indeksle (dizi boşluksuz kalmalı)
    document.addEventListener('click', function (e) {
        var b = e.target.closest('[data-qd-stage-remove]');
        if (!b) return;
        var rows = b.closest('[data-qd-stage-rows]');
        var row = b.closest('.qd-stage-row');
        if (!row || !rows) return;
        row.remove();
        Array.from(rows.children).forEach(function (r, i) {
            r.querySelectorAll('[name^="payment_schedule["]').forEach(function (el) {
                el.name = el.name.replace(/^payment_schedule\[\d+\]/, 'payment_schedule[' + i + ']');
            });
        });
    });

    // Seri üretim aç/kapa — açıkken form dates.bulk'a gider (data-alt-action)
    document.addEventListener('change', function (e) {
        var cb = e.target.closest('[data-qd-series-toggle]');
        if (!cb) return;
        var fs = cb.closest('.qd-fieldset');
        qdSetSectionEnabled(fs && fs.querySelector('[data-qd-series-wrap]'), cb.checked);
    });
})();
</script>
