@php
    $statusSteps = [
        'potential'  => ['label' => 'Potansiyel'],
        'offer_sent' => ['label' => 'Teklif Verildi'],
        'revised'    => ['label' => 'Revize Edildi'],
        'confirmed'  => ['label' => 'Satış Tamamlandı'],
        'in_progress'=> ['label' => 'Devam Ediyor'],
        'completed'  => ['label' => 'Kapanan'],
    ];
    $statusKeys = array_keys($statusSteps);
    $productsByType = $products->groupBy(fn($p) => $p->productType?->name ?? 'Diğer');

    // Birleşik mod: mevcut satışa (taslak/gerçek) bağlı ön-dolum
    $sale = $sale ?? null;
    $saleCust = $sale?->customer;
    $saleCustName = $saleCust?->full_name;
    $saleCustSub = $saleCust?->phone ?: (is_array($saleCust?->emails ?? null) ? ($saleCust->emails[0] ?? '') : '');
    $curStatus = $sale?->status ?: 'potential';
    $curStatusIdx = array_search($curStatus, $statusKeys, true);
    $curStatusIdx = $curStatusIdx === false ? 0 : $curStatusIdx;
    $sv = fn($f, $d = '') => ($sale && $sale->{$f} !== null) ? $sale->{$f} : $d;
    $sd = fn($f) => $sale && $sale->{$f} ? \Carbon\Carbon::parse($sale->{$f})->format('Y-m-d') : '';
    $saleItems = $sale ? $sale->items->map(fn($it) => [
        'name' => $it->name,
        'quantity' => (float) $it->quantity,
        'unit_price' => (float) $it->unit_price,
        'tax_rate' => (float) $it->tax_rate,
        'currency' => $it->currency,
        'product_id' => $it->product_id,
        'itemable_type' => $it->itemable_type,
        'itemable_id' => $it->itemable_id,
    ])->values()->all() : [];

    // Kalem kaydı olmayan mevcut satışlar (eski akışla / tur tarihi seçimiyle oluşturulanlar):
    // tabloyu boş göstermek yerine satırları satışın fiyat kırılımından (yetişkin/çocuk/bebek) türet.
    // Kırılım satış toplamını tutmuyorsa (indirim vb.) tek satıra düşülür; kayıt ilk otomatik
    // kayıtta gerçek SaleItem'lara dönüşür.
    if ($sale && empty($saleItems)) {
        $derivedName = $sale->reservable?->name ?? $sale->product?->name ?? $sale->title;
        if ($derivedName) {
            $rows = [];
            $unitP = (float) ($sale->unit_price ?? 0);
            $childP = (float) ($sale->child_price ?? 0);
            $infP = (float) ($sale->infant_price ?? 0);
            if ($unitP > 0 && $sale->adult_count > 0) {
                $rows[] = ['label' => 'Yetişkin', 'qty' => (int) $sale->adult_count, 'price' => $unitP];
                if ($sale->child_count > 0 && $childP > 0) $rows[] = ['label' => 'Çocuk', 'qty' => (int) $sale->child_count, 'price' => $childP];
                if ($sale->infant_count > 0 && $infP > 0) $rows[] = ['label' => 'Bebek', 'qty' => (int) $sale->infant_count, 'price' => $infP];
            }
            $rowsSum = collect($rows)->sum(fn($r) => $r['qty'] * $r['price']);
            if ((empty($rows) || abs($rowsSum - (float) $sale->total_amount) > 0.01) && (float) $sale->total_amount > 0) {
                $rows = [['label' => null, 'qty' => 1, 'price' => (float) $sale->total_amount]];
            }
            $saleItems = collect($rows)->map(fn($r) => [
                'name' => $derivedName . ($r['label'] ? ' · ' . $r['label'] : ''),
                'quantity' => $r['qty'],
                'unit_price' => $r['price'],
                'tax_rate' => 0, // tur fiyatları kişi başı KDV dahil kabul edilir (çifte vergi olmasın)
                'currency' => $sale->currency ?: 'TRY',
                'product_id' => $sale->product_id,
                'itemable_type' => null,
                'itemable_id' => null,
                'tour_line' => true, // katalogdan yeni kalkış seçilirse bu satırlar değiştirilir
            ])->values()->all();
        }
    }

    // Kayıtlı satış dövizi, kalemlerin (tek tip) dövizinden farklıysa kullanıcı özet
    // panelde bilinçli olarak farklı birim seçmiş demektir → otomatik döviz takibi
    // (qcAutoFollowCurrency) açılışta bu seçimi TRY'ye/kalem dövizine geri çevirmesin.
    $itemCurrencies = collect($saleItems)->pluck('currency')->filter()->unique()->values();
    $currencyIsManual = $sale && $itemCurrencies->count() === 1 && $itemCurrencies->first() !== ($sale->currency ?: 'TRY');
@endphp

<x-quick-view.layout class="qv-sales-wrapper qv-wrapper">

    {{-- Hidden status input --}}
    <input type="hidden" id="qc-status-value" value="{{ $curStatus }}">

    {{-- ═══ HEADER (kompakt: başlık + inline metrikler) ═══ --}}
    <div class="sqv-header">
        <div class="sqv-header-left">
            <div class="sqv-icon"><i class="fas fa-cart-plus"></i></div>
            <div class="sqv-title-group">
                <h3 class="sqv-title">{{ $sale?->title ?: 'Yeni Satış' }}</h3>
                <div class="sqv-subtitle">
                    <span class="sqv-code">{{ $sale?->sale_code ?? 'YENİ' }}</span>
                    <span class="sqv-dot">•</span>
                    <span id="qc-customer-label"><i class="fas fa-user"></i> {{ $saleCustName ?? 'Müşteri seçin' }}</span>
                </div>
            </div>
        </div>

        <div class="sqv-stats">
            <div class="sqv-stat">
                <span class="sqv-stat-label">Toplam</span>
                <span class="sqv-stat-val" id="qc-metric-total">₺0,00</span>
            </div>
            <span class="sqv-stat-sep"></span>
            <div class="sqv-stat">
                <span class="sqv-stat-label">Ödenen</span>
                <span class="sqv-stat-val pos" id="qc-metric-paid">₺0,00</span>
            </div>
            <span class="sqv-stat-sep"></span>
            <div class="sqv-stat">
                <span class="sqv-stat-label">Kalan</span>
                <span class="sqv-stat-val neg" id="qc-metric-remaining">₺0,00</span>
            </div>
            <span class="sqv-stat-sep"></span>
            <div class="sqv-stat sqv-stat-narrow">
                <span class="sqv-stat-label">Kişi</span>
                <span class="sqv-stat-val" id="qc-metric-people">1</span>
            </div>
            <div class="sqv-stat sqv-stat-narrow">
                <span class="sqv-stat-label">Durum</span>
                <span class="sqv-stat-chip" id="qc-metric-status">{{ $statusSteps[$curStatus]['label'] ?? 'Potansiyel' }}</span>
            </div>
        </div>

        <div class="sqv-actions">
            <button class="qv-action-btn qv-copy" onclick="copyQvLink()" title="Bağlantıyı kopyala"><i class="fas fa-link"></i></button>
            <button class="qv-action-btn qv-share" onclick="openQvShare()" title="Mesaj olarak gönder"><i class="fas fa-paper-plane"></i></button>
            <button class="qv-action-btn qv-minimize" onclick="minimizeQuickView()" title="Küçült"><i class="fas fa-minus"></i></button>
            <button class="qv-action-btn qv-close sqv-close" onclick="qcClose()" title="Kapat"><i class="fas fa-times"></i></button>
        </div>
    </div>

    {{-- ═══ PIPELINE (ince stepper) ═══ --}}
    <div class="sqv-pipeline-wrap">
        <div class="sqv-pipeline" id="qc-pipeline">
            @foreach($statusSteps as $key => $step)
                <div class="sqv-seg {{ $loop->index < $curStatusIdx ? 'done' : ($loop->index === $curStatusIdx ? 'current' : 'future') }}"
                     onclick="qcSelectStatus('{{ $key }}', this)"
                     data-key="{{ $key }}"
                     title="{{ $step['label'] }}">
                    <span class="sqv-seg-dot"></span>
                    <span class="sqv-seg-label">{{ $step['label'] }}</span>
                </div>
            @endforeach
        </div>
    </div>

    {{-- ═══ TABS ═══ --}}
    <x-quick-view.header>
        <x-slot:tabs>
            <x-quick-view.tab id="qcgeneral"  label="Genel"   icon="fas fa-th-large" active="true" />
            <x-quick-view.tab id="qcproducts" label="Ürünler" icon="fas fa-box" />
        </x-slot:tabs>
    </x-quick-view.header>

    {{-- ═══ CONTENT ═══ --}}
    <x-quick-view.content>

        {{-- ─────────────────────── TAB: GENEL ─────────────────────── --}}
        <div id="qv-tab-qcgeneral" class="qv-tab-panel active">
            <div class="p-4">
                <div class="qc-autofill-note">
                    <div class="qc-autofill-ico"><i class="fas fa-wand-magic-sparkles"></i></div>
                    <div class="qc-autofill-txt">
                        <b>Otomatik doldurma:</b> Ürünler sekmesinden tur/hizmet ekledikçe <b>başlık, hizmet türü, katılımcı sayısı ve tutar</b> alanları <u>boşsa</u> otomatik doldurulur — bu alanları kendiniz elle de girebilirsiniz, elle girdiğiniz değerler korunur.
                    </div>
                </div>
                <div class="row g-4">

                    {{-- ── LEFT COLUMN (7/12) ── --}}
                    <div class="col-md-7">

                        {{-- MÜŞTERİ --}}
                        <div class="sqv-card mb-4">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h6 class="sqv-card-title mb-0"><i class="fas fa-user-tie me-2 text-primary"></i>Müşteri <span class="text-danger">*</span></h6>
                                <button type="button" class="qc-newcust-btn" onclick="qcToggleCustomerForm(true)">
                                    <i class="fas fa-user-plus me-1"></i> Yeni Müşteri
                                </button>
                            </div>

                            {{-- Aranabilir müşteri seçici (server-side arama) --}}
                            <div class="qc-cust-picker" id="qc-cust-picker">
                                <input type="hidden" id="qc-customer-id" value="{{ $sale?->customer_id }}">
                                <button type="button" class="qc-cust-trigger {{ $saleCust ? 'selected' : '' }}" id="qc-cust-trigger" onclick="qcCustToggle(event)">
                                    <span class="qc-cust-tr-ico {{ $saleCust ? 'has' : '' }}" id="qc-cust-tr-ico">@if($saleCust){{ mb_strtoupper(mb_substr($saleCustName ?? '?', 0, 2)) }}@else<i class="fas fa-magnifying-glass"></i>@endif</span>
                                    <span class="qc-cust-tr-txt" id="qc-cust-tr-txt">@if($saleCust)<b>{{ $saleCustName }}</b>@if($saleCustSub) <span class="qc-cust-tr-sub">{{ $saleCustSub }}</span>@endif @else Müşteri seçin veya arayın… @endif</span>
                                    <i class="fas fa-chevron-down qc-cust-caret"></i>
                                </button>
                                <div class="qc-cust-dropdown" id="qc-cust-dropdown">
                                    <div class="qc-cust-search">
                                        <i class="fas fa-magnifying-glass"></i>
                                        <input type="text" id="qc-cust-search-input" placeholder="İsim, TC kimlik, telefon veya e-posta ile ara…" autocomplete="off" oninput="qcCustSearch(this.value)">
                                    </div>
                                    <div class="qc-cust-list" id="qc-cust-list"></div>
                                    <button type="button" class="qc-cust-addnew" onclick="qcCustClose(); qcToggleCustomerForm(true)">
                                        <i class="fas fa-user-plus me-1"></i> Bulamadın mı? <b>Yeni müşteri ekle</b>
                                    </button>
                                </div>
                            </div>

                            {{-- Yeni müşteri hızlı formu --}}
                            <div id="qc-quick-customer-form" class="qc-newcust-form d-none">
                                <div class="qc-newcust-head"><i class="fas fa-user-plus"></i> Yeni Müşteri Ekle</div>
                                <div class="row g-2">
                                    <div class="col-md-6">
                                        <label class="qc-nc-label">Adı <span class="req">*</span></label>
                                        <input type="text" id="qc_new_first_name" class="qc-nc-input" placeholder="Ahmet" autocomplete="off">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="qc-nc-label">Soyadı <span class="req">*</span></label>
                                        <input type="text" id="qc_new_last_name" class="qc-nc-input" placeholder="Yılmaz" autocomplete="off">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="qc-nc-label">Telefon</label>
                                        <input type="text" id="qc_new_phone" class="qc-nc-input" placeholder="05XX XXX XX XX" autocomplete="off">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="qc-nc-label">E-Posta</label>
                                        <input type="email" id="qc_new_email" class="qc-nc-input" placeholder="ornek@site.com" autocomplete="off">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="qc-nc-label">T.C. / Pasaport</label>
                                        <input type="text" id="qc_new_national_id" class="qc-nc-input" placeholder="Opsiyonel" autocomplete="off">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="qc-nc-label">Cinsiyet</label>
                                        <select id="qc_new_gender" class="qc-nc-input">
                                            <option value="">Seçiniz</option>
                                            <option value="male">Erkek</option>
                                            <option value="female">Kadın</option>
                                        </select>
                                    </div>
                                    <div class="col-12">
                                        <div id="qc-newcust-error" class="qc-nc-error" style="display:none;"></div>
                                    </div>
                                    <div class="col-12 d-flex justify-content-end gap-2 mt-1">
                                        <button type="button" class="qc-nc-cancel" onclick="qcToggleCustomerForm(false)">İptal</button>
                                        <button type="button" class="qc-nc-save" id="qc-nc-save-btn" onclick="qcSaveQuickCustomer()">
                                            <span class="qc-nc-save-txt"><i class="fas fa-check me-1"></i> Kaydet ve Seç</span>
                                            <span class="qc-nc-save-load d-none"><i class="fas fa-spinner fa-spin me-1"></i> Ekleniyor…</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- ANLAŞMA BİLGİLERİ --}}
                        <div class="sqv-card mb-4">
                            <h6 class="sqv-card-title"><i class="fas fa-handshake me-2 text-primary"></i>Anlaşma Hakkında</h6>
                            <div class="row g-3">
                                <div class="col-12">
                                    <label class="sqv-form-label">Satış Başlığı</label>
                                    <input type="text" id="qc-title" class="form-control qc-form-control"
                                        placeholder="Örn: Kapadokya Balon Turu Satışı" value="{{ $sale?->title }}"
                                        oninput="qcUpdateHeaderSubtitle()">
                                </div>
                                <div class="col-6">
                                    <label class="sqv-form-label">Başlangıç Tarihi *</label>
                                    <input type="date" id="qc-start-date" class="form-control qc-form-control" value="{{ $sd('start_date') ?: date('Y-m-d') }}" required>
                                </div>
                                <div class="col-6">
                                    <label class="sqv-form-label">Bitiş Tarihi</label>
                                    <input type="date" id="qc-end-date" class="form-control qc-form-control" value="{{ $sd('end_date') }}">
                                </div>
                                <div class="col-6">
                                    <label class="sqv-form-label">Hizmet Türü</label>
                                    <select id="qc-product-type" class="form-select qc-form-select">
                                        <option value="">— Seçin —</option>
                                        @foreach($productTypes as $pt)
                                            <option value="{{ $pt->id }}" @selected($sale?->product_type_id == $pt->id)>{{ $pt->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="sqv-form-label">Sorumlu Personel</label>
                                    <select id="qc-agent" class="form-select qc-form-select">
                                        <option value="">— Atanmamış —</option>
                                        @foreach($agents as $agent)
                                            <option value="{{ $agent->id }}" @selected($sale ? ($sale->assigned_to == $agent->id) : (Auth::id() == $agent->id))>{{ $agent->full_name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="sqv-form-label">Alış Yeri (Pickup)</label>
                                    <input type="text" id="qc-pickup" class="form-control qc-form-control" placeholder="Otel adı veya adres..." value="{{ $sale?->pickup_location }}">
                                </div>
                                <div class="col-6">
                                    <label class="sqv-form-label">Uçuş Kodu</label>
                                    <input type="text" id="qc-flight" class="form-control qc-form-control" placeholder="TK1903 vb..." value="{{ $sale?->flight_number }}">
                                </div>
                            </div>
                        </div>

                        {{-- NOTLAR --}}
                        <div class="sqv-card sqv-notes-card">
                            <h6 class="sqv-card-title"><i class="fas fa-sticky-note me-2 text-warning"></i>Dahili ve Müşteri Notları</h6>
                            <div class="sqv-note-section mb-3">
                                <label class="fw-bold" style="color:#b45309;font-size:0.7rem;">Müşteri Notu</label>
                                <div class="rte-wrap mt-1">
                                    <div id="qc-customer-note-editor" data-placeholder="Müşteriye iletilecek notlar...">{!! $sale?->customer_note !!}</div>
                                </div>
                                {{-- Quill içeriği bu gizli alana senkronlanır; otomatik kayıt payload'u buradan okur --}}
                                <textarea id="qc-customer-note" class="d-none">{{ $sale?->customer_note }}</textarea>
                            </div>
                            <hr style="border-color:#fde68a">
                            <div class="sqv-note-section">
                                <label class="fw-bold" style="color:#b45309;font-size:0.7rem;">Dahili Not</label>
                                <div class="rte-wrap mt-1">
                                    <div id="qc-internal-note-editor" data-placeholder="Sadece çalışanlar görebilir...">{!! $sale?->internal_note !!}</div>
                                </div>
                                <textarea id="qc-internal-note" class="d-none">{{ $sale?->internal_note }}</textarea>
                            </div>
                        </div>

                    </div>

                    {{-- ── RIGHT COLUMN (5/12) ── --}}
                    <div class="col-md-5">

                        {{-- KATILIMCIlar --}}
                        <div class="sqv-card mb-4">
                            <h6 class="sqv-card-title"><i class="fas fa-users me-2 text-primary"></i>Katılımcı Sayısı</h6>
                            <div class="row g-2">
                                <div class="col-4">
                                    <label class="sqv-form-label">Yetişkin *</label>
                                    <input type="number" id="qc-adult" class="form-control qc-form-control text-center fw-bold"
                                        value="{{ $sale?->adult_count ?? 1 }}" min="1" oninput="qcUpdateMetrics()">
                                </div>
                                <div class="col-4">
                                    <label class="sqv-form-label">Çocuk</label>
                                    <input type="number" id="qc-child" class="form-control qc-form-control text-center fw-bold"
                                        value="{{ $sale?->child_count ?? 0 }}" min="0" oninput="qcUpdateMetrics()">
                                </div>
                                <div class="col-4">
                                    <label class="sqv-form-label">Bebek</label>
                                    <input type="number" id="qc-infant" class="form-control qc-form-control text-center fw-bold"
                                        value="{{ $sale?->infant_count ?? 0 }}" min="0" oninput="qcUpdateMetrics()">
                                </div>
                            </div>
                        </div>

                        {{-- FİNANSAL BİLGİLER --}}
                        <div class="sqv-card mb-4">
                            <h6 class="sqv-card-title"><i class="fas fa-coins me-2 text-primary"></i>Fiyat ve Ödeme</h6>
                            <div class="row g-3">
                                <div class="col-7">
                                    <label class="sqv-form-label">Toplam Tutar *</label>
                                    <input type="number" id="qc-total-amount" class="form-control qc-form-control fw-extrabold text-primary"
                                        placeholder="0.00" step="any" min="0" style="font-size:1.05rem;"
                                        value="{{ $sale && $sale->total_amount ? number_format($sale->total_amount, 2, '.', '') : '' }}"
                                        oninput="qcTotalEdited()">
                                </div>
                                <div class="col-5">
                                    <label class="sqv-form-label">Para Birimi</label>
                                    <select id="qc-currency" class="form-select qc-form-select fw-bold" onchange="qcOnSaleCurrencyChange(this.value)">
                                        @foreach($activeCurrencies as $curr)
                                            <option value="{{ $curr->code }}" @selected($curr->code === ($sale?->currency ?: 'TRY'))>{{ $curr->code }} ({{ $curr->symbol }})</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="sqv-form-label">Ödenen Tutar</label>
                                    <input type="number" id="qc-paid-amount" class="form-control qc-form-control fw-bold text-success"
                                        placeholder="0.00" value="{{ $sale && $sale->paid_amount ? number_format($sale->paid_amount, 2, '.', '') : 0 }}" step="any" min="0"
                                        oninput="qcUpdateMetrics()">
                                </div>
                                <div class="col-6">
                                    <label class="sqv-form-label">Kalan Tutar</label>
                                    <input type="text" id="qc-remaining-display" class="form-control qc-form-control bg-light fw-bold text-muted"
                                        value="0.00" readonly>
                                </div>
                                <div class="col-12">
                                    <label class="sqv-form-label">Ödeme Durumu</label>
                                    <select id="qc-payment-status" class="form-select qc-form-select fw-bold">
                                        <option value="unpaid" @selected(($sale?->payment_status ?? 'unpaid') === 'unpaid')>Ödenmedi</option>
                                        <option value="partial" @selected($sale?->payment_status === 'partial')>Kısmi Ödeme</option>
                                        <option value="paid" @selected($sale?->payment_status === 'paid')>Ödendi</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        {{-- OTOMATİK KAYIT DURUMU + BİTİR --}}
                        <div class="qc-autosave-strip">
                            <i class="fas fa-bolt"></i>
                            <span>Bu satış <b>otomatik kaydediliyor</b> — her değişiklik anında saklanır.</span>
                            <span class="qc-save-indicator" id="qc-save-indicator" data-state="saved"><i class="fas fa-circle-check"></i> Kaydedildi</span>
                        </div>
                        <div class="d-grid">
                            <button type="button" onclick="qcClose()"
                                class="btn btn-lg fw-bold"
                                style="background:#f1f5f9;color:#334155;border:none;border-radius:14px;font-size:0.95rem;padding:0.85rem;transition:all 0.2s;">
                                <i class="fas fa-xmark me-2"></i>Kapat
                            </button>
                        </div>

                    </div>
                </div>
            </div>
        </div>

        {{-- ─────────────────────── TAB: ÜRÜNLER ─────────────────────── --}}
        <div id="qv-tab-qcproducts" class="qv-tab-panel">
            {{-- Seçilen tur + kalkış tarihi bağı (satış bu tarihe bağlanır → operasyon & yolcu listesi) --}}
            <input type="hidden" id="qc-product-id" value="">
            <input type="hidden" id="qc-tour-date-id" value="">
            <input type="hidden" id="qc-tour-date-type" value="">
            <div class="p-4">
                <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                    <div>
                        <h6 class="sqv-card-title mb-0" style="font-weight:800;font-size:0.95rem;color:#1e293b;">
                            <i class="fas fa-box me-2 text-primary"></i>Satış Kalemleri
                        </h6>
                        <p class="text-muted mb-0" style="font-size:0.72rem;margin-top:2px;">
                            <i class="fas fa-keyboard me-1"></i>Adı direkt yazın
                            <span class="mx-1 text-muted">·</span>
                            <i class="fas fa-layer-group me-1 text-indigo"></i>veya <strong>Katalog</strong>'dan tur, ürün ya da tedarikçi hizmeti seçin
                        </p>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-catalog-open btn-sm" onclick="openProductCatalog(null)">
                            <i class="fas fa-layer-group me-1"></i> Katalog
                        </button>
                        <button class="btn btn-outline-secondary btn-sm" style="border-radius:10px;font-weight:700;" onclick="addBlankQvProductRow()">
                            <i class="fas fa-plus me-1 text-primary"></i> Satır
                        </button>
                        <button class="btn btn-success btn-sm" style="border-radius:10px;font-weight:700;box-shadow:0 4px 10px rgba(16,185,129,0.2);" onclick="qcSyncProductTotals()">
                            <i class="fas fa-sync me-1"></i> Toplamı Güncelle
                        </button>
                    </div>
                </div>

                {{-- Bağlı kalkış rozeti --}}
                <div id="qc-departure-banner" class="qc-dep-banner" style="display:none;">
                    <div class="qc-dep-icon"><i class="fas fa-calendar-check"></i></div>
                    <div class="qc-dep-info">
                        <div class="qc-dep-title" id="qc-dep-title">—</div>
                        <div class="qc-dep-sub" id="qc-dep-sub">—</div>
                    </div>
                    <div class="qc-dep-badge" id="qc-dep-cap"></div>
                    <button type="button" class="qc-dep-clear" onclick="clearTourDeparture()" title="Kalkış bağını kaldır">
                        <i class="fas fa-times"></i>
                    </button>
                </div>

                <div class="table-responsive">
                    <table class="table align-middle" style="font-size:0.88rem;min-width:900px;">
                        <thead>
                            <tr style="font-size:0.72rem;text-transform:uppercase;letter-spacing:0.04em;color:#64748b;border-bottom:2px solid #f1f5f9;">
                                <th>Ürün / Hizmet Adı</th>
                                <th class="text-center" style="width:95px;">Adet</th>
                                <th class="text-end" style="width:160px;">Birim Fiyat</th>
                                <th class="text-center" style="width:90px;">KDV</th>
                                <th class="text-end" style="width:110px;">KDV Tutarı</th>
                                <th class="text-end" style="width:140px;">Toplam</th>
                                <th style="width:36px;"></th>
                            </tr>
                        </thead>
                        <tbody id="qv-products-tbody">
                            <tr id="qv-no-products-row">
                                <td colspan="7" class="text-center py-5 text-muted">
                                    <i class="fas fa-box-open mb-2" style="font-size:2rem;opacity:0.3;display:block;"></i>
                                    Henüz kalem eklenmedi.
                                    <div class="mt-3">
                                        <button type="button" class="btn btn-catalog-open btn-sm" onclick="openProductCatalog(null)">
                                            <i class="fas fa-layer-group me-1"></i> Katalogdan Seç
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                {{-- Özet --}}
                <div class="d-flex justify-content-between align-items-center mt-4 border-top pt-3">
                    <span class="text-muted small"><i class="fas fa-info-circle me-1"></i> Ürünleri ekledikten sonra <strong>Toplamı Güncelle</strong> ile Genel sekmesine aktarabilirsiniz.</span>
                    <div class="card border-0 bg-light p-3" style="width:350px;border-radius:12px;box-shadow:0 1px 3px rgba(0,0,0,0.02);">
                        <div class="d-flex justify-content-between align-items-center mb-2 pb-2 border-bottom">
                            <span class="text-muted fw-semibold" style="font-size:0.8rem;"><i class="fas fa-coins me-1 text-warning"></i>Toplam Para Birimi</span>
                            <select id="qv-summary-currency" class="form-select form-select-sm fw-bold" style="width:auto;border-radius:8px;font-size:0.82rem;" onchange="qcOnSummaryCurrencyChange(this.value)">
                                @foreach($activeCurrencies as $curr)
                                    <option value="{{ $curr->code }}" @selected($curr->code === ($sale?->currency ?: 'TRY'))>{{ $curr->code }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div id="qv-summary-mixed" class="mb-2" style="display:none;font-size:0.72rem;color:#b45309;background:#fffbeb;border:1px solid #fde68a;border-radius:8px;padding:5px 9px;">
                            <i class="fas fa-circle-info me-1"></i> Kalemler farklı para birimlerinde — toplam seçtiğiniz birime çevrilir.
                        </div>
                        <div class="d-flex justify-content-between mb-2" style="font-size:0.82rem;">
                            <span class="text-muted fw-semibold">Ara Toplam:</span>
                            <span class="fw-bold text-dark" id="qv-summary-subtotal">₺0,00</span>
                        </div>
                        <div class="d-flex justify-content-between mb-2" style="font-size:0.82rem;">
                            <span class="text-muted fw-semibold">KDV Toplamı:</span>
                            <span class="fw-bold text-muted" id="qv-summary-tax">₺0,00</span>
                        </div>
                        <div class="border-top my-2"></div>
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="text-dark fw-bold" style="font-size:0.95rem;">Genel Toplam:</span>
                            <span class="text-primary fw-extrabold" style="font-size:1.25rem;" id="qv-summary-total">₺0,00</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </x-quick-view.content>

    {{-- ═══ ÜRÜN & HİZMET KATALOĞU MODALI ═══ --}}
    <div class="modal fade qvcat-modal" id="qvProductCatalogModal" tabindex="-1" aria-hidden="true" style="z-index:1065;">
        <div class="modal-dialog qvcat-dialog modal-dialog-centered">
            <div class="modal-content qvcat-content">

                {{-- Header --}}
                <div class="qvcat-header">
                    <div class="qvcat-head-title">
                        <div class="qvcat-head-icon"><i class="fas fa-layer-group"></i></div>
                        <div>
                            <h5>Ürün &amp; Hizmet Kataloğu</h5>
                            <p>Turları tarih &amp; fiyatıyla, ürünleri ve tedarikçi hizmetlerini tek yerden seçin</p>
                        </div>
                    </div>
                    <button type="button" class="qvcat-x" data-bs-dismiss="modal"><i class="fas fa-times"></i></button>
                </div>

                {{-- Tabs --}}
                <div class="qvcat-tabs">
                    <button type="button" class="qvcat-tab active" data-cat-tab="products" onclick="catalogSwitchTab('products', this)">
                        <i class="fas fa-box-open"></i> Ürünler &amp; Turlar
                        <span class="qvcat-tab-count">{{ $products->count() }}</span>
                    </button>
                    <button type="button" class="qvcat-tab" data-cat-tab="suppliers" onclick="catalogSwitchTab('suppliers', this)">
                        <i class="fas fa-handshake"></i> Tedarikçi Hizmetleri
                        <span class="qvcat-tab-count">{{ $supplierCatalog->count() }}</span>
                    </button>
                </div>

                {{-- Toolbar --}}
                <div class="qvcat-toolbar">
                    <div class="qvcat-search">
                        <i class="fas fa-search"></i>
                        <input type="text" id="catalogSearchInput" placeholder="Ara: tur veya ürün adı..." oninput="filterCatalog()" autocomplete="off">
                    </div>
                    <select id="catalogTypeFilter" class="qvcat-filter" onchange="filterCatalog()">
                        <option value="">Tüm Ürün Tipleri</option>
                        @foreach($products->pluck('productType')->filter()->unique('id') as $pt)
                            <option value="{{ $pt->id }}">{{ $pt->name }}</option>
                        @endforeach
                    </select>
                    <select id="catalogSupplierFilter" class="qvcat-filter" onchange="filterCatalog()" style="display:none;">
                        <option value="">Tüm Hizmet Tipleri</option>
                        @foreach($supplierCatalog->pluck('type_label', 'type') as $tk => $tl)
                            <option value="{{ $tk }}">{{ $tl }}</option>
                        @endforeach
                    </select>
                    <select id="catalogCurrencyFilter" class="qvcat-filter" onchange="filterCatalog()" style="display:none;">
                        <option value="">Tüm Para Birimleri</option>
                        @foreach($supplierCatalog->pluck('currency')->filter()->unique()->sort()->values() as $cc)
                            <option value="{{ $cc }}">{{ $cc }}</option>
                        @endforeach
                    </select>
                </div>

                {{-- Body --}}
                <div class="qvcat-body">

                    {{-- ── PANE: ÜRÜNLER & TURLAR ── --}}
                    <div class="qvcat-pane active" id="catPaneProducts">

                        {{-- ürün/tur grid --}}
                        <div id="catalogProductGrid">
                            @forelse($productsByType as $typeName => $typeProducts)
                                <div class="qvcat-group" data-type-name="{{ $typeName }}">
                                    <div class="qvcat-group-head">
                                        <span class="qvcat-group-badge">{{ $typeName }}</span>
                                        <span class="qvcat-group-line"></span>
                                        <span class="qvcat-group-n">{{ $typeProducts->count() }}</span>
                                    </div>
                                    <div class="qvcat-grid">
                                        @foreach($typeProducts as $p)
                                            @php $isTour = \Illuminate\Support\Str::contains($p->productable_type ?? '', ['Tour', 'DayTrip']); @endphp
                                            <div class="qvcat-card catalog-product-item {{ $isTour ? 'is-tour' : '' }}"
                                                 data-name="{{ strtolower($p->name) }}"
                                                 data-type-id="{{ $p->productType?->id }}"
                                                 data-id="{{ $p->id }}"
                                                 data-pname="{{ $p->name }}"
                                                 data-price="{{ $p->base_price }}"
                                                 data-currency="{{ $p->currency }}"
                                                 data-has-dates="{{ $isTour ? 1 : 0 }}"
                                                 onclick="catalogPickProduct(this)">
                                                <div class="qvcat-card-ico"><i class="fas {{ $p->productType?->icon ?? 'fa-box' }}"></i></div>
                                                <div class="qvcat-card-body">
                                                    <div class="qvcat-card-name">{{ $p->name }}</div>
                                                    <div class="qvcat-card-meta">
                                                        @if($isTour)
                                                            <span class="qvcat-chip tour"><i class="fas fa-calendar-days"></i> Tarih &amp; fiyat seç</span>
                                                        @else
                                                            <span class="qvcat-chip"><i class="fas fa-tag"></i> Ürün</span>
                                                        @endif
                                                    </div>
                                                </div>
                                                <div class="qvcat-card-right">
                                                    @if($p->base_price)
                                                        <div class="qvcat-card-price">{{ $isTour ? '~' : '' }}{{ number_format($p->base_price, 0, ',', '.') }} <small>{{ $p->currency }}</small></div>
                                                    @else
                                                        <div class="qvcat-card-price muted">—</div>
                                                    @endif
                                                    <div class="qvcat-card-cta">{{ $isTour ? 'Tarih Seç' : 'Seç' }} <i class="fas fa-chevron-right"></i></div>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            @empty
                                <div class="qvcat-empty">
                                    <i class="fas fa-box-open"></i>
                                    <p>Tanımlı ürün bulunamadı.</p>
                                </div>
                            @endforelse
                            <div id="catalogNoResults" class="qvcat-empty d-none">
                                <i class="fas fa-search"></i>
                                <p>Arama kriterlerine uygun sonuç yok.</p>
                            </div>
                        </div>

                        {{-- tur tarihi drill-down --}}
                        <div id="catalogDateView" style="display:none;">
                            <button type="button" class="qvcat-back" onclick="catalogBackToGrid()"><i class="fas fa-arrow-left"></i> Ürünlere dön</button>
                            <div class="qvcat-date-head">
                                <div class="qvcat-date-head-ico"><i class="fas fa-calendar-star"></i></div>
                                <div>
                                    <div class="qvcat-date-head-name" id="catalogDateTourName">—</div>
                                    <div class="qvcat-date-head-sub">Kalkış tarihi seçip fiyat tipini belirleyin — ya da <b>özel tarih</b> girin.</div>
                                </div>
                            </div>
                            <div id="catalogDateLoading" class="qvcat-date-loading"><i class="fas fa-spinner fa-spin me-2"></i> Tarihler yükleniyor…</div>
                            <div id="catalogDateGrid" class="qvcat-date-grid"></div>
                            <div id="catalogDateNoUpcoming" class="qvcat-date-none d-none">
                                <i class="fas fa-calendar-xmark me-1"></i> Bu tur için yaklaşan kayıtlı kalkış yok. Aşağıdan özel tarih girebilirsiniz.
                            </div>

                            {{-- Fiyat tipi seçici (bir tarih seçilince açılır) --}}
                            <div id="catalogFarePanel" class="qvcat-fare-panel" style="display:none;">
                                <div class="qvcat-fare-head">
                                    <span><i class="fas fa-coins"></i> Fiyat tipleri — <b id="catalogFareDate">—</b></span>
                                    <span class="qvcat-fare-total">Toplam: <b id="catalogFareTotal">0</b></span>
                                </div>
                                <div id="catalogFareRows" class="qvcat-fare-rows"></div>
                                <div class="qvcat-fare-actions">
                                    <button type="button" class="qvcat-fare-cancel" onclick="catalogCloseFares()">Vazgeç</button>
                                    <button type="button" class="qvcat-fare-confirm" onclick="catalogApplyFares()"><i class="fas fa-check me-1"></i> Bu tarihi seç ve ekle</button>
                                </div>
                            </div>

                            {{-- Özel tarih (kayıtlı tarih olmadan sat) --}}
                            <div class="qvcat-customdate">
                                <div class="qvcat-customdate-head" onclick="catalogToggleCustomDate()">
                                    <span><i class="fas fa-calendar-plus"></i> Kayıtlı tarih olmadan sat — <b>özel tarih gir</b></span>
                                    <i class="fas fa-chevron-down" id="catalogCustomChevron"></i>
                                </div>
                                <div id="catalogCustomBody" class="qvcat-customdate-body" style="display:none;">
                                    <div class="qvcat-cd-fields">
                                        <div class="qvcat-cd-fld">
                                            <label>Başlangıç</label>
                                            <input type="date" id="catalogCustomStart" value="{{ date('Y-m-d') }}">
                                        </div>
                                        <div class="qvcat-cd-fld">
                                            <label>Bitiş</label>
                                            <input type="date" id="catalogCustomEnd">
                                        </div>
                                        <div class="qvcat-cd-fld">
                                            <label>Kişi Başı Fiyat</label>
                                            <input type="number" id="catalogCustomPrice" min="0" step="any" placeholder="0">
                                        </div>
                                        <div class="qvcat-cd-fld">
                                            <label>Para Birimi</label>
                                            <select id="catalogCustomCurrency">
                                                @foreach($activeCurrencies as $curr)
                                                    <option value="{{ $curr->code }}">{{ $curr->code }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <button type="button" class="qvcat-cd-apply" onclick="applyCustomTourDate()"><i class="fas fa-check me-1"></i> Uygula</button>
                                    </div>
                                    <div class="qvcat-cd-hint"><i class="fas fa-circle-info"></i> Özel tarihte satış tura bağlanır ama belirli bir kalkışa bağlanmaz. Fiyat ve adetleri kalem tablosunda düzenleyebilirsiniz.</div>
                                </div>
                            </div>
                        </div>

                    </div>

                    {{-- ── PANE: TEDARİKÇİ HİZMETLERİ ── --}}
                    <div class="qvcat-pane" id="catPaneSuppliers">
                        <div id="catalogSupplierGrid">
                            @php $supplierGroups = $supplierCatalog->groupBy('type'); @endphp
                            @forelse($supplierGroups as $typeKey => $items)
                                <div class="qvcat-group" data-sup-type="{{ $typeKey }}">
                                    <div class="qvcat-group-head">
                                        <span class="qvcat-group-badge sup"><i class="fas {{ $items->first()['type_icon'] }} me-1"></i>{{ $items->first()['type_label'] }}</span>
                                        <span class="qvcat-group-line"></span>
                                        <span class="qvcat-group-n">{{ $items->count() }}</span>
                                    </div>
                                    <div class="qvcat-grid">
                                        @foreach($items as $it)
                                            <div class="qvcat-card catalog-supplier-item"
                                                 data-name="{{ strtolower($it['title'].' '.$it['subtitle'].' '.$it['supplier_name']) }}"
                                                 data-sup-type="{{ $it['type'] }}"
                                                 data-id="{{ $it['id'] }}"
                                                 data-title="{{ $it['title'] }}"
                                                 data-price="{{ $it['sale_price'] }}"
                                                 data-currency="{{ $it['currency'] }}"
                                                 data-tax="{{ $it['tax_rate'] }}"
                                                 data-supplier="{{ $it['supplier_name'] }}"
                                                 onclick="catalogPickSupplier(this)">
                                                <div class="qvcat-card-ico sup"><i class="fas {{ $it['type_icon'] }}"></i></div>
                                                <div class="qvcat-card-body">
                                                    <div class="qvcat-card-name">{{ $it['title'] }}</div>
                                                    <div class="qvcat-card-meta">
                                                        @if($it['subtitle'])<span class="qvcat-chip"><i class="fas fa-circle-info"></i> {{ $it['subtitle'] }}</span>@endif
                                                        <span class="qvcat-chip muted"><i class="fas fa-building"></i> {{ $it['supplier_name'] }}</span>
                                                    </div>
                                                </div>
                                                <div class="qvcat-card-right">
                                                    <div class="qvcat-card-price">{{ number_format($it['sale_price'], 0, ',', '.') }} <small>{{ $it['currency'] }}</small></div>
                                                    <div class="qvcat-card-cta">Ekle <i class="fas fa-chevron-right"></i></div>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            @empty
                                <div class="qvcat-empty">
                                    <i class="fas fa-handshake-angle"></i>
                                    <p>Aktif tedarikçi fiyat kalemi yok.<br><span style="font-size:0.75rem;">Tedarikçiler modülünden sezon fiyatı girerek buraya ekleyebilirsiniz.</span></p>
                                </div>
                            @endforelse
                            <div id="catalogSupplierNoResults" class="qvcat-empty d-none">
                                <i class="fas fa-search"></i>
                                <p>Arama kriterlerine uygun hizmet yok.</p>
                            </div>
                        </div>
                    </div>

                </div>

                {{-- Footer --}}
                <div class="qvcat-footer">
                    <span class="qvcat-foot-hint"><i class="fas fa-circle-info me-1"></i> Tur seçip tarih belirlerseniz yolcular otomatik olarak operasyona ve tur kalkışına işlenir.</span>
                    <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal" style="border-radius:10px;font-weight:700;">Kapat</button>
                </div>

            </div>
        </div>
    </div>

</x-quick-view.layout>

{{-- ═══ CSS ═══ --}}
<style>
    /* ═══ HEADER (kompakt: başlık + inline metrikler) ═══ */
    .sqv-header{display:flex;align-items:center;gap:1.1rem;padding:0.8rem 1.4rem;background:linear-gradient(135deg,#0f172a 0%,#1e293b 100%);flex-shrink:0;position:relative;}
    .sqv-header-left{display:flex;align-items:center;gap:0.8rem;min-width:0;flex-shrink:1;}
    .sqv-icon{width:42px;height:42px;border-radius:13px;display:grid;place-items:center;font-size:1.05rem;flex-shrink:0;background:rgba(255,255,255,0.1)!important;color:#fff!important;border:1px solid rgba(255,255,255,0.15);}
    .sqv-title-group{min-width:0;}
    .sqv-title{font-size:1.1rem;font-weight:800;color:#fff;letter-spacing:-0.02em;margin:0;line-height:1.25;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
    .sqv-subtitle{display:flex;align-items:center;gap:0.4rem;font-size:0.73rem;color:rgba(255,255,255,0.55);flex-wrap:wrap;margin-top:1px;}
    .sqv-code{font-weight:800;color:rgba(255,255,255,0.5);font-size:0.6rem;letter-spacing:0.06em;background:rgba(255,255,255,0.08);padding:2px 8px;border-radius:6px;}
    .sqv-dot{color:rgba(255,255,255,0.25);}

    /* inline metrikler (ayrı bant kaldırıldı) */
    .sqv-stats{display:flex;align-items:center;gap:0;margin-left:auto;flex-shrink:0;}
    .sqv-stat{display:flex;flex-direction:column;align-items:flex-end;gap:1px;padding:0 0.9rem;min-width:0;}
    .sqv-stat-narrow{padding:0 0.75rem;align-items:center;}
    .sqv-stat-label{font-size:0.58rem;font-weight:800;color:#94a3b8;text-transform:uppercase;letter-spacing:0.05em;white-space:nowrap;}
    .sqv-stat-val{font-size:0.98rem;font-weight:800;color:#1e293b;letter-spacing:-0.02em;white-space:nowrap;line-height:1.15;}
    .sqv-stat-val.pos{color:#16a34a;}
    .sqv-stat-val.neg{color:#dc2626;}
    .sqv-stat-chip{font-size:0.7rem;font-weight:800;color:#4338ca;background:#eef2ff;border:1px solid #e0e7ff;border-radius:20px;padding:2px 11px;white-space:nowrap;margin-top:1px;}
    .sqv-stat-sep{width:1px;height:26px;background:rgba(148,163,184,0.25);flex-shrink:0;}
    .sqv-actions{display:flex;align-items:center;gap:0.5rem;margin-left:0.4rem;flex-shrink:0;}
    .sqv-close{flex-shrink:0;}
    @media (max-width:1200px){ .sqv-stats > :nth-child(2), .sqv-stats > :nth-child(3), .sqv-stats > :nth-child(4), .sqv-stats > :nth-child(5), .sqv-stats > :nth-child(6){display:none;} }
    @media (max-width:820px){ .sqv-stats{display:none;} }

    /* ═══ PIPELINE (ince stepper) ═══ */
    .sqv-pipeline-wrap{background:#fff;border-bottom:1px solid #eef2f7;padding:0.5rem 1.4rem;flex-shrink:0;}
    .sqv-pipeline{display:flex;gap:6px;width:100%;}
    .sqv-seg{flex:1;display:flex;align-items:center;justify-content:center;gap:6px;padding:0.4rem 0.5rem;border-radius:8px;cursor:pointer;transition:all .25s cubic-bezier(.4,0,.2,1);position:relative;min-height:30px;border:1.5px solid transparent;background:#f8fafc;}
    .sqv-seg-dot{width:6px;height:6px;border-radius:50%;background:#cbd5e1;flex-shrink:0;transition:.2s;}
    .sqv-seg-label{font-size:0.66rem;font-weight:700;white-space:nowrap;letter-spacing:0.01em;}
    .sqv-seg.done{background:#eef2ff;border-color:#e0e7ff;}
    .sqv-seg.done .sqv-seg-dot{background:#6366f1;}
    .sqv-seg.done .sqv-seg-label{color:#4f46e5;}
    .sqv-seg.current{background:linear-gradient(135deg,#34d399,#10b981);border-color:#059669;box-shadow:0 4px 12px rgba(16,185,129,0.28);}
    .sqv-seg.current .sqv-seg-dot{background:#fff;box-shadow:0 0 0 3px rgba(255,255,255,0.35);}
    .sqv-seg.current .sqv-seg-label{color:#fff;font-weight:800;}
    .sqv-seg.future{background:#f8fafc;border-color:#eef2f7;}
    .sqv-seg.future .sqv-seg-label{color:#94a3b8;}
    .sqv-seg:hover{transform:translateY(-1px);}
    .sqv-seg.future:hover{background:#f1f5f9;border-color:#e2e8f0;}

    /* ═══ CARDS ═══ */
    .sqv-card{background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:1.25rem;box-shadow:0 1px 3px rgba(0,0,0,0.02);}
    .sqv-card-title{font-weight:800;font-size:0.88rem;color:#1e293b;margin-bottom:1rem;display:block;}
    .sqv-notes-card{background:linear-gradient(135deg,#fffbeb,#fefce8)!important;border-color:#fde68a!important;}
    .sqv-field{margin-bottom:0.25rem;}
    .sqv-field label{font-size:0.72rem;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:0.04em;display:block;margin-bottom:4px;}

    /* ═══ FORM INPUTS ═══ */
    .sqv-form-label{font-size:0.72rem;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:0.04em;display:block;margin-bottom:5px;}
    .qc-form-control{border-radius:10px;border:1.5px solid #e2e8f0;padding:0.5rem 0.75rem;font-size:0.85rem;font-weight:600;transition:border-color 0.2s;}
    .qc-form-control:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,0.1);}
    .qc-form-select{border-radius:10px;border:1.5px solid #e2e8f0;padding:0.5rem 0.75rem;font-size:0.85rem;font-weight:600;transition:border-color 0.2s;}
    .qc-form-select:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,0.1);}

    /* ═══ PRODUCT TABLE ═══ */
    .qv-product-name-cell{display:flex;align-items:center;gap:8px;}
    .qv-product-name-cell input{border:none;border-bottom:1.5px solid transparent;border-radius:0;background:transparent;font-size:0.88rem;font-weight:700;padding:4px 6px;transition:all 0.2s;width:100%;}
    .qv-product-name-cell input:focus{outline:none;border-bottom-color:#6366f1;background:#f8f9ff;}
    .qv-product-row td input,.qv-product-row td select{border:none;border-bottom:1.5px solid transparent;border-radius:0;background:transparent;font-size:0.85rem;padding:4px 6px;transition:all 0.2s;}
    .qv-product-row td input:focus,.qv-product-row td select:focus{outline:none;border-bottom-color:#6366f1;background:#f8f9ff;}
    .btn-catalog-pick{display:flex;align-items:center;gap:5px;font-size:0.7rem;font-weight:700;color:#6366f1;background:#ede9fe;border:none;border-radius:8px;padding:4px 10px;cursor:pointer;white-space:nowrap;transition:all 0.2s;flex-shrink:0;}
    .btn-catalog-pick:hover{background:#ddd6fe;transform:translateY(-1px);}

    /* ═══ KATALOG AÇMA BUTONU ═══ */
    .btn-catalog-open{display:inline-flex;align-items:center;gap:6px;border:none;border-radius:10px;font-weight:800;font-size:0.78rem;color:#fff;
        background:linear-gradient(135deg,#6366f1,#4f46e5);padding:0.42rem 0.9rem;box-shadow:0 4px 12px rgba(79,70,229,0.28);transition:transform .15s,box-shadow .15s;}
    .btn-catalog-open:hover{color:#fff;transform:translateY(-1px);box-shadow:0 8px 20px rgba(79,70,229,0.36);}

    /* ═══ BAĞLI KALKIŞ ROZETİ ═══ */
    .qc-dep-banner{display:flex;align-items:center;gap:0.85rem;margin-bottom:1rem;padding:0.85rem 1rem;border-radius:14px;
        background:linear-gradient(135deg,#eef2ff,#f5f3ff);border:1.5px solid #ddd6fe;box-shadow:0 4px 14px rgba(99,102,241,0.08);}
    .qc-dep-icon{width:40px;height:40px;border-radius:12px;flex-shrink:0;display:grid;place-items:center;font-size:1.05rem;color:#fff;background:linear-gradient(135deg,#6366f1,#4338ca);}
    .qc-dep-info{flex:1;min-width:0;}
    .qc-dep-title{font-weight:800;font-size:0.9rem;color:#312e81;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
    .qc-dep-sub{font-size:0.74rem;color:#6d28d9;font-weight:600;margin-top:2px;}
    .qc-dep-badge{flex-shrink:0;font-size:0.72rem;font-weight:800;color:#4338ca;background:#fff;border:1px solid #ddd6fe;border-radius:20px;padding:5px 11px;}
    .qc-dep-clear{flex-shrink:0;width:30px;height:30px;border-radius:9px;border:none;background:rgba(99,102,241,0.12);color:#6366f1;cursor:pointer;transition:.15s;}
    .qc-dep-clear:hover{background:#ef4444;color:#fff;}

    /* Genel sekmesi — otomatik doldurma notu */
    .qc-autofill-note{display:flex;align-items:flex-start;gap:0.7rem;margin-bottom:1.1rem;padding:0.8rem 1rem;border-radius:14px;background:linear-gradient(135deg,#eef2ff,#faf5ff);border:1px solid #e0e7ff;}
    .qc-autofill-ico{width:34px;height:34px;border-radius:10px;flex-shrink:0;display:grid;place-items:center;font-size:0.9rem;color:#fff;background:linear-gradient(135deg,#818cf8,#6366f1);}
    .qc-autofill-txt{font-size:0.78rem;color:#4338ca;line-height:1.5;font-weight:500;}
    .qc-autofill-txt b{color:#3730a3;font-weight:800;}
    .qc-autofill-txt u{text-decoration-color:#a5b4fc;}

    /* ═══ MÜŞTERİ SEÇİCİ (aranabilir) ═══ */
    .qc-newcust-btn{display:inline-flex;align-items:center;border:1px solid #e0e7ff;background:#eef2ff;color:#4f46e5;font-weight:700;font-size:0.72rem;border-radius:9px;padding:0.35rem 0.75rem;cursor:pointer;transition:.15s;}
    .qc-newcust-btn:hover{background:#4f46e5;color:#fff;border-color:#4f46e5;}
    .qc-cust-picker{position:relative;}
    .qc-cust-trigger{display:flex;align-items:center;gap:0.7rem;width:100%;border:1.5px solid #e2e8f0;background:#fff;border-radius:12px;padding:0.55rem 0.75rem;cursor:pointer;transition:.15s;text-align:left;}
    .qc-cust-trigger:hover{border-color:#c7d2fe;}
    .qc-cust-trigger.open,.qc-cust-trigger.selected{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,0.1);}
    .qc-cust-tr-ico{width:34px;height:34px;border-radius:10px;flex-shrink:0;display:grid;place-items:center;font-size:0.82rem;font-weight:800;color:#94a3b8;background:#f1f5f9;}
    .qc-cust-tr-ico.has{color:#fff;background:linear-gradient(135deg,#6366f1,#4338ca);}
    .qc-cust-tr-txt{flex:1;min-width:0;font-size:0.86rem;font-weight:600;color:#64748b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
    .qc-cust-tr-txt b{color:#1e293b;font-weight:700;}
    .qc-cust-tr-sub{color:#94a3b8;font-weight:600;font-size:0.78rem;}
    .qc-cust-caret{color:#94a3b8;font-size:0.72rem;flex-shrink:0;transition:transform .2s;}
    .qc-cust-trigger.open .qc-cust-caret{transform:rotate(180deg);}
    .qc-cust-dropdown{display:none;position:absolute;top:calc(100% + 6px);left:0;right:0;z-index:60;background:#fff;border:1px solid #e2e8f0;border-radius:14px;box-shadow:0 18px 44px rgba(15,23,42,0.16);overflow:hidden;}
    .qc-cust-dropdown.open{display:block;animation:qcCustIn .15s ease;}
    @keyframes qcCustIn{from{opacity:0;transform:translateY(-5px);}to{opacity:1;transform:none;}}
    .qc-cust-search{display:flex;align-items:center;gap:8px;padding:0.65rem 0.8rem;border-bottom:1px solid #f1f5f9;}
    .qc-cust-search i{color:#94a3b8;font-size:0.82rem;}
    .qc-cust-search input{flex:1;border:none;outline:none;font-size:0.86rem;font-weight:600;color:#1e293b;background:none;}
    .qc-cust-list{max-height:270px;overflow-y:auto;padding:0.35rem;}
    .qc-cust-row{display:flex;align-items:center;gap:0.7rem;padding:0.5rem 0.55rem;border-radius:10px;cursor:pointer;transition:background .12s;}
    .qc-cust-row:hover{background:#f5f7ff;}
    .qc-cust-av{width:36px;height:36px;border-radius:10px;flex-shrink:0;display:grid;place-items:center;font-size:0.76rem;font-weight:800;color:#4f46e5;background:#eef2ff;}
    .qc-cust-meta{flex:1;min-width:0;}
    .qc-cust-name{font-weight:700;font-size:0.85rem;color:#1e293b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
    .qc-cust-sub{font-size:0.73rem;color:#94a3b8;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
    .qc-cust-pick{color:#cbd5e1;font-size:0.88rem;flex-shrink:0;}
    .qc-cust-row:hover .qc-cust-pick{color:#6366f1;}
    .qc-cust-loading,.qc-cust-empty{padding:1.4rem 1rem;text-align:center;color:#94a3b8;font-size:0.83rem;font-weight:600;}
    .qc-cust-addnew{width:100%;border:none;border-top:1px solid #f1f5f9;background:#fafbff;color:#4f46e5;font-size:0.77rem;font-weight:600;padding:0.6rem;cursor:pointer;transition:.15s;}
    .qc-cust-addnew:hover{background:#eef2ff;}
    .qc-cust-addnew b{font-weight:800;}
    /* Yeni müşteri formu */
    .qc-newcust-form{background:linear-gradient(135deg,#f8fafc,#f5f3ff);border:1.5px dashed #ddd6fe;border-radius:14px;padding:1rem;margin-bottom:0.85rem;}
    .qc-newcust-head{font-size:0.8rem;font-weight:800;color:#4338ca;margin-bottom:0.75rem;display:flex;align-items:center;gap:7px;}
    .qc-newcust-head i{color:#6366f1;}
    .qc-nc-label{font-size:0.64rem;font-weight:800;text-transform:uppercase;letter-spacing:0.03em;color:#64748b;margin-bottom:3px;display:block;}
    .qc-nc-label .req{color:#ef4444;}
    .qc-nc-input{width:100%;border:1.5px solid #e2e8f0;background:#fff;border-radius:9px;padding:0.45rem 0.65rem;font-size:0.84rem;font-weight:600;color:#1e293b;transition:.15s;}
    .qc-nc-input:focus{outline:none;border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,0.1);}
    .qc-nc-error{background:#fef2f2;border:1px solid #fecaca;color:#b91c1c;border-radius:9px;padding:0.5rem 0.75rem;font-size:0.78rem;font-weight:600;}
    .qc-nc-cancel{border:1.5px solid #e2e8f0;background:#fff;color:#64748b;font-weight:700;font-size:0.76rem;border-radius:9px;padding:0.4rem 0.9rem;cursor:pointer;}
    .qc-nc-cancel:hover{background:#f1f5f9;}
    .qc-nc-save{border:none;background:linear-gradient(135deg,#6366f1,#4f46e5);color:#fff;font-weight:800;font-size:0.78rem;border-radius:9px;padding:0.4rem 1.1rem;cursor:pointer;box-shadow:0 4px 12px rgba(79,70,229,0.28);}
    .qc-nc-save:disabled{opacity:0.7;cursor:not-allowed;}

    /* ═══ OTOMATİK KAYIT ŞERİDİ ═══ */
    .qc-autosave-strip{display:flex;align-items:center;gap:0.5rem;font-size:0.75rem;color:#475569;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:10px;padding:0.5rem 0.8rem;margin-bottom:0.6rem;}
    .qc-autosave-strip > i{color:#16a34a;}
    .qc-autosave-strip b{color:#15803d;}
    .qc-save-indicator{margin-left:auto;font-weight:800;font-size:0.72rem;white-space:nowrap;}
    .qc-save-indicator[data-state="saved"]{color:#16a34a;}
    .qc-save-indicator[data-state="saving"]{color:#d97706;}
    .qc-save-indicator[data-state="error"]{color:#dc2626;}

    /* ═══ KATALOG MODALI ═══ */
    .qvcat-dialog{max-width:1240px;width:97%;}
    .qvcat-content{border:none;border-radius:22px;overflow:hidden;box-shadow:0 32px 80px rgba(2,6,23,0.4);max-height:90vh;display:flex;flex-direction:column;background:#f8fafc;}
    .qvcat-header{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:1.35rem 1.75rem;flex-shrink:0;
        background:linear-gradient(135deg,#0f172a 0%,#1e293b 55%,#312e81 140%);position:relative;overflow:hidden;}
    .qvcat-header::before{content:'';position:absolute;top:-60%;right:-8%;width:340px;height:340px;background:radial-gradient(circle,rgba(99,102,241,0.28),transparent 70%);pointer-events:none;}
    .qvcat-head-title{display:flex;align-items:center;gap:0.9rem;position:relative;z-index:1;min-width:0;}
    .qvcat-head-icon{width:46px;height:46px;border-radius:14px;display:grid;place-items:center;font-size:1.25rem;color:#c7d2fe;background:rgba(99,102,241,0.18);border:1px solid rgba(199,210,254,0.2);flex-shrink:0;}
    .qvcat-head-title h5{margin:0;color:#fff;font-weight:800;font-size:1.12rem;letter-spacing:-0.02em;}
    .qvcat-head-title p{margin:2px 0 0;color:#94a3b8;font-size:0.74rem;}
    .qvcat-x{width:38px;height:38px;border-radius:11px;border:1px solid rgba(255,255,255,0.12);background:rgba(255,255,255,0.06);color:rgba(255,255,255,0.6);cursor:pointer;transition:.15s;position:relative;z-index:1;flex-shrink:0;}
    .qvcat-x:hover{background:rgba(239,68,68,0.2);color:#fca5a5;border-color:rgba(239,68,68,0.3);}

    .qvcat-tabs{display:flex;gap:4px;padding:0 1.25rem;background:#0f172a;flex-shrink:0;}
    .qvcat-tab{display:inline-flex;align-items:center;gap:8px;border:none;background:none;cursor:pointer;padding:0.85rem 1.1rem;font-size:0.84rem;font-weight:700;
        color:#64748b;border-bottom:2.5px solid transparent;transition:.15s;}
    .qvcat-tab:hover{color:#cbd5e1;}
    .qvcat-tab.active{color:#fff;border-bottom-color:#818cf8;}
    .qvcat-tab i{font-size:0.9rem;}
    .qvcat-tab-count{font-size:0.66rem;font-weight:800;background:rgba(255,255,255,0.1);color:#cbd5e1;padding:2px 8px;border-radius:20px;}
    .qvcat-tab.active .qvcat-tab-count{background:#6366f1;color:#fff;}

    .qvcat-toolbar{display:flex;gap:0.6rem;padding:0.85rem 1.25rem;background:#fff;border-bottom:1px solid #e2e8f0;flex-shrink:0;}
    .qvcat-search{position:relative;flex:1;display:flex;align-items:center;}
    .qvcat-search i{position:absolute;left:14px;color:#94a3b8;font-size:0.85rem;pointer-events:none;}
    .qvcat-search input{width:100%;border:1.5px solid #e2e8f0;background:#f8fafc;border-radius:11px;padding:0.55rem 0.9rem 0.55rem 38px;font-size:0.86rem;font-weight:600;color:#1e293b;transition:.15s;}
    .qvcat-search input:focus{outline:none;border-color:#6366f1;background:#fff;box-shadow:0 0 0 3px rgba(99,102,241,0.1);}
    .qvcat-filter{max-width:210px;border:1.5px solid #e2e8f0;background:#f8fafc;border-radius:11px;padding:0.55rem 0.8rem;font-size:0.82rem;font-weight:700;color:#334155;cursor:pointer;}
    .qvcat-filter:focus{outline:none;border-color:#6366f1;}

    .qvcat-body{flex:1;overflow-y:auto;overflow-x:hidden;padding:1.15rem 1.25rem;min-height:340px;min-width:0;}
    .qvcat-pane{display:none;}
    .qvcat-pane.active{display:block;animation:qvcatFade .25s ease;}
    @keyframes qvcatFade{from{opacity:0;transform:translateY(6px);}to{opacity:1;transform:none;}}

    .qvcat-group{margin-bottom:1.4rem;min-width:0;}
    .qvcat-group-head{display:flex;align-items:center;gap:0.65rem;margin-bottom:0.7rem;min-width:0;}
    .qvcat-group-badge{font-size:0.68rem;font-weight:800;text-transform:uppercase;letter-spacing:0.05em;color:#4f46e5;background:#ede9fe;padding:4px 11px;border-radius:20px;display:inline-flex;align-items:center;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex-shrink:1;}
    .qvcat-group-badge.sup{color:#0e7490;background:#cffafe;}
    .qvcat-group-line{flex:1;height:1px;background:linear-gradient(90deg,#e2e8f0,transparent);}
    .qvcat-group-n{font-size:0.7rem;font-weight:800;color:#94a3b8;}
    .qvcat-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:0.65rem;}
    @media (max-width:820px){.qvcat-grid{grid-template-columns:1fr;}}

    .qvcat-card{display:flex;align-items:center;gap:0.85rem;background:#fff;border:1.5px solid #e8edf3;border-radius:15px;padding:0.85rem 0.95rem;cursor:pointer;transition:transform .15s,box-shadow .15s,border-color .15s;min-width:0;overflow:hidden;}
    .qvcat-card:hover{border-color:#c7d2fe;box-shadow:0 10px 26px rgba(79,70,229,0.12);transform:translateY(-2px);}
    .qvcat-card.is-tour{border-left:3px solid #818cf8;}
    .qvcat-card-ico{width:44px;height:44px;border-radius:13px;flex-shrink:0;display:grid;place-items:center;font-size:1.05rem;color:#4f46e5;background:linear-gradient(135deg,#eef2ff,#e0e7ff);}
    .qvcat-card-ico.sup{color:#0e7490;background:linear-gradient(135deg,#ecfeff,#cffafe);}
    .qvcat-card-body{flex:1;min-width:0;}
    .qvcat-card-name{font-weight:700;font-size:0.88rem;color:#1e293b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
    .qvcat-card-meta{display:flex;flex-wrap:wrap;gap:5px;margin-top:5px;}
    .qvcat-chip{display:inline-flex;align-items:center;gap:4px;font-size:0.66rem;font-weight:700;color:#475569;background:#f1f5f9;border-radius:7px;padding:2px 7px;white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis;}
    .qvcat-chip i{font-size:0.6rem;color:#94a3b8;}
    .qvcat-chip.tour{color:#4338ca;background:#eef2ff;}
    .qvcat-chip.tour i{color:#6366f1;}
    .qvcat-chip.muted{color:#94a3b8;background:#f8fafc;}
    .qvcat-card-right{text-align:right;flex-shrink:0;display:flex;flex-direction:column;align-items:flex-end;gap:3px;}
    .qvcat-card-price{font-weight:800;font-size:0.95rem;color:#0f172a;white-space:nowrap;}
    .qvcat-card-price small{font-size:0.66rem;color:#94a3b8;font-weight:700;}
    .qvcat-card-price.muted{color:#cbd5e1;}
    .qvcat-card-cta{font-size:0.68rem;font-weight:800;color:#6366f1;display:inline-flex;align-items:center;gap:4px;}
    .qvcat-card-cta i{font-size:0.6rem;transition:transform .15s;}
    .qvcat-card:hover .qvcat-card-cta i{transform:translateX(3px);}

    .qvcat-empty{text-align:center;padding:2.6rem 1rem;color:#94a3b8;}
    .qvcat-empty i{font-size:2.2rem;opacity:0.35;display:block;margin-bottom:0.7rem;}
    .qvcat-empty p{font-weight:600;font-size:0.86rem;margin:0;}

    /* Tur tarihi drill-down */
    .qvcat-back{display:inline-flex;align-items:center;gap:7px;border:none;background:#eef2ff;color:#4f46e5;font-weight:800;font-size:0.76rem;border-radius:10px;padding:0.5rem 0.95rem;cursor:pointer;transition:.15s;margin-bottom:1rem;}
    .qvcat-back:hover{background:#4f46e5;color:#fff;}
    .qvcat-date-head{display:flex;align-items:center;gap:0.85rem;background:linear-gradient(135deg,#fffbeb,#fef3c7);border:1.5px solid #fde68a;border-radius:15px;padding:0.9rem 1.1rem;margin-bottom:1.1rem;}
    .qvcat-date-head-ico{width:44px;height:44px;border-radius:13px;flex-shrink:0;display:grid;place-items:center;font-size:1.15rem;color:#fff;background:linear-gradient(135deg,#f59e0b,#d97706);}
    .qvcat-date-head-name{font-weight:800;font-size:0.98rem;color:#78350f;}
    .qvcat-date-head-sub{font-size:0.74rem;color:#b45309;font-weight:600;margin-top:2px;}
    .qvcat-date-loading{text-align:center;padding:2rem;color:#94a3b8;font-size:0.85rem;font-weight:600;}
    .qvcat-date-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:0.7rem;}
    @media (max-width:820px){.qvcat-date-grid{grid-template-columns:1fr;}}
    .qvcat-date-card{background:#fff;border:1.5px solid #e8edf3;border-radius:15px;padding:0.9rem 1rem;cursor:pointer;transition:transform .15s,box-shadow .15s,border-color .15s;}
    .qvcat-date-card:hover{border-color:#fbbf24;box-shadow:0 10px 26px rgba(245,158,11,0.15);transform:translateY(-2px);}
    .qvcat-date-top{display:flex;align-items:center;justify-content:space-between;gap:0.5rem;margin-bottom:0.6rem;}
    .qvcat-date-when{font-weight:800;font-size:0.86rem;color:#1e293b;display:inline-flex;align-items:center;gap:6px;}
    .qvcat-date-when i{color:#f59e0b;font-size:0.78rem;}
    .qvcat-date-guar{font-size:0.64rem;font-weight:800;color:#16a34a;background:#dcfce7;border-radius:20px;padding:2px 8px;display:inline-flex;align-items:center;gap:4px;white-space:nowrap;}
    .qvcat-date-prices{display:flex;flex-wrap:wrap;gap:0.4rem;margin-bottom:0.65rem;}
    .qvcat-date-prices span{font-size:0.72rem;font-weight:600;color:#64748b;background:#f8fafc;border:1px solid #eef2f7;border-radius:8px;padding:3px 8px;}
    .qvcat-date-prices span.adult{color:#065f46;background:#ecfdf5;border-color:#a7f3d0;}
    .qvcat-date-prices b{font-weight:800;color:#0f172a;}
    .qvcat-date-prices span.adult b{color:#047857;}
    .qvcat-date-foot{display:flex;align-items:center;justify-content:space-between;gap:0.5rem;border-top:1px dashed #eef2f7;padding-top:0.6rem;}
    .qvcat-date-cap{font-size:0.72rem;font-weight:700;color:#64748b;display:inline-flex;align-items:center;gap:5px;}
    .qvcat-date-cap i{color:#94a3b8;}
    .qvcat-date-pick{font-size:0.7rem;font-weight:800;color:#f59e0b;display:inline-flex;align-items:center;gap:5px;}
    .qvcat-date-card:hover .qvcat-date-pick{color:#d97706;}

    .qvcat-date-card.sel{border-color:#f59e0b;box-shadow:0 0 0 3px rgba(245,158,11,0.18);background:#fffdf7;}
    .qvcat-date-none{font-size:0.8rem;font-weight:600;color:#b45309;background:#fffbeb;border:1px solid #fde68a;border-radius:12px;padding:0.7rem 0.9rem;margin-bottom:1rem;}

    /* Fiyat tipi paneli */
    .qvcat-fare-panel{margin-top:1.1rem;background:#fff;border:1.5px solid #e2e8f0;border-radius:16px;overflow:hidden;box-shadow:0 8px 24px rgba(15,23,42,0.06);}
    .qvcat-fare-head{display:flex;align-items:center;justify-content:space-between;gap:0.75rem;flex-wrap:wrap;padding:0.75rem 1rem;background:linear-gradient(135deg,#f8fafc,#eef2ff);border-bottom:1px solid #e2e8f0;font-size:0.8rem;font-weight:800;color:#334155;}
    .qvcat-fare-head i{color:#6366f1;margin-right:5px;}
    .qvcat-fare-total{color:#4338ca;}
    .qvcat-fare-total b{font-size:0.95rem;}
    .qvcat-fare-rows{padding:0.5rem 1rem;display:flex;flex-direction:column;gap:0.35rem;}
    .qvcat-fare-row{display:flex;align-items:center;gap:0.75rem;flex-wrap:wrap;padding:0.5rem 0;border-bottom:1px dashed #f1f5f9;}
    .qvcat-fare-row:last-child{border-bottom:none;}
    .qvcat-fare-label{font-weight:700;font-size:0.83rem;color:#1e293b;flex:1;min-width:120px;display:flex;align-items:center;gap:7px;}
    .qvcat-fare-label i{width:24px;height:24px;border-radius:7px;display:grid;place-items:center;font-size:0.7rem;color:#4f46e5;background:#eef2ff;flex-shrink:0;}
    .qvcat-fare-unit{font-size:0.78rem;font-weight:700;color:#64748b;white-space:nowrap;min-width:96px;text-align:right;}
    .qvcat-fare-qty{width:76px;flex-shrink:0;}
    .qvcat-fare-qty input{width:100%;border:1.5px solid #e2e8f0;border-radius:9px;padding:0.35rem 0.4rem;font-size:0.85rem;font-weight:700;text-align:center;color:#0f172a;}
    .qvcat-fare-qty input:focus{outline:none;border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,0.1);}
    .qvcat-fare-sub{font-size:0.82rem;font-weight:800;color:#047857;white-space:nowrap;min-width:110px;text-align:right;}
    .qvcat-fare-actions{display:flex;align-items:center;justify-content:flex-end;gap:0.6rem;padding:0.75rem 1rem;background:#f8fafc;border-top:1px solid #eef2f7;}
    .qvcat-fare-cancel{border:1.5px solid #e2e8f0;background:#fff;color:#64748b;font-weight:700;font-size:0.8rem;border-radius:10px;padding:0.45rem 1rem;cursor:pointer;transition:.15s;}
    .qvcat-fare-cancel:hover{background:#f1f5f9;color:#334155;}
    .qvcat-fare-confirm{border:none;background:linear-gradient(135deg,#16a34a,#15803d);color:#fff;font-weight:800;font-size:0.8rem;border-radius:10px;padding:0.45rem 1.1rem;cursor:pointer;box-shadow:0 4px 12px rgba(22,163,74,0.28);transition:transform .15s;}
    .qvcat-fare-confirm:hover{transform:translateY(-1px);}

    /* Özel tarih */
    .qvcat-customdate{margin-top:1.1rem;border:1.5px dashed #cbd5e1;border-radius:14px;overflow:hidden;}
    .qvcat-customdate-head{display:flex;align-items:center;justify-content:space-between;gap:0.5rem;padding:0.7rem 1rem;cursor:pointer;font-size:0.8rem;font-weight:700;color:#475569;background:#f8fafc;transition:background .15s;}
    .qvcat-customdate-head:hover{background:#f1f5f9;}
    .qvcat-customdate-head i.fa-calendar-plus{color:#6366f1;margin-right:6px;}
    .qvcat-customdate-body{padding:0.9rem 1rem;border-top:1px solid #eef2f7;}
    .qvcat-cd-fields{display:flex;align-items:flex-end;gap:0.6rem;flex-wrap:wrap;}
    .qvcat-cd-fld{display:flex;flex-direction:column;gap:4px;min-width:120px;flex:1;}
    .qvcat-cd-fld label{font-size:0.68rem;font-weight:800;text-transform:uppercase;letter-spacing:0.03em;color:#94a3b8;}
    .qvcat-cd-fld input,.qvcat-cd-fld select{border:1.5px solid #e2e8f0;border-radius:10px;padding:0.45rem 0.6rem;font-size:0.84rem;font-weight:600;color:#1e293b;}
    .qvcat-cd-fld input:focus,.qvcat-cd-fld select:focus{outline:none;border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,0.1);}
    .qvcat-cd-apply{border:none;background:linear-gradient(135deg,#6366f1,#4f46e5);color:#fff;font-weight:800;font-size:0.8rem;border-radius:10px;padding:0.5rem 1.1rem;cursor:pointer;white-space:nowrap;box-shadow:0 4px 12px rgba(79,70,229,0.28);}
    .qvcat-cd-hint{font-size:0.7rem;color:#94a3b8;margin-top:0.7rem;}
    .qvcat-cd-hint i{color:#6366f1;margin-right:4px;}

    .qvcat-footer{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:0.8rem 1.25rem;background:#fff;border-top:1px solid #e2e8f0;flex-shrink:0;}
    .qvcat-foot-hint{font-size:0.72rem;color:#94a3b8;font-weight:600;}
</style>

<script>
    window.exchangeRates = {
        @foreach($activeCurrencies as $curr)
            "{{ $curr->code }}": {{ (float)$curr->exchange_rate }},
        @endforeach
    };
    window.currencySymbols = {
        @foreach($activeCurrencies as $curr)
            "{{ $curr->code }}": "{{ $curr->symbol }}",
        @endforeach
    };
    // Tur kalkış tarihlerini (yetişkin/çocuk/bebek fiyatlı) getiren endpoint
    var URL_DATES = '{{ route("agency.sales.api.product-dates") }}';
    // Müşteri arama (server-side; binlerce müşteride hızlı bulma)
    var URL_CUSTOMER_SEARCH = '{{ route("agency.customers.search") }}';

    // ─── OTOMATİK KAYIT (submit yerine; her değişiklikte debounce'lu quick-update) ──
    var _qcSaleId = @json($sale?->id);
    var _qcSaveT = null;

    function qcSetSaveState(state) {
        const el = document.getElementById('qc-save-indicator');
        if (!el) return;
        el.dataset.state = state || '';
        if (state === 'saving') el.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Kaydediliyor…';
        else if (state === 'saved') el.innerHTML = '<i class="fas fa-circle-check"></i> Kaydedildi';
        else if (state === 'error') el.innerHTML = '<i class="fas fa-triangle-exclamation"></i> Kaydedilemedi';
        else el.innerHTML = '';
    }

    function qcBuildPayload() {
        const items = [];
        document.querySelectorAll('#qv-products-tbody .qv-product-row').forEach(row => {
            const name = row.querySelector('.qv-product-name').value.trim();
            if (!name) return;
            items.push({
                product_id    : row.querySelector('.row-product-id').value || null,
                itemable_type : row.querySelector('.row-itemable-type')?.value || null,
                itemable_id   : row.querySelector('.row-itemable-id')?.value || null,
                name          : name,
                quantity      : parseFloat(row.querySelector('.qv-product-qty').value) || 1,
                unit_price    : parseFloat(row.querySelector('.qv-product-price').value) || 0,
                tax_rate      : parseFloat(row.querySelector('.qv-product-tax').value) || 0,
                currency      : row.querySelector('.qv-product-currency').value
            });
        });
        return {
            customer_id     : document.getElementById('qc-customer-id').value || null,
            title           : document.getElementById('qc-title').value || null,
            start_date      : document.getElementById('qc-start-date').value || null,
            end_date        : document.getElementById('qc-end-date').value || null,
            product_type_id : document.getElementById('qc-product-type').value || null,
            product_id      : document.getElementById('qc-product-id').value || null,
            tour_date_id    : document.getElementById('qc-tour-date-id').value || null,
            assigned_to     : document.getElementById('qc-agent').value || null,
            adult_count     : document.getElementById('qc-adult').value || 1,
            child_count     : document.getElementById('qc-child').value || 0,
            infant_count    : document.getElementById('qc-infant').value || 0,
            total_amount    : document.getElementById('qc-total-amount').value || 0,
            paid_amount     : document.getElementById('qc-paid-amount').value || 0,
            currency        : document.getElementById('qc-currency').value,
            payment_status  : document.getElementById('qc-payment-status').value,
            status          : document.getElementById('qc-status-value').value,
            pickup_location : document.getElementById('qc-pickup').value || null,
            flight_number   : document.getElementById('qc-flight').value || null,
            customer_note   : document.getElementById('qc-customer-note').value || null,
            internal_note   : document.getElementById('qc-internal-note').value || null,
            items           : items
        };
    }

    function qcAutoSave() {
        if (!_qcSaleId) return;
        clearTimeout(_qcSaveT);
        qcSetSaveState('saving');
        _qcSaveT = setTimeout(() => {
            fetch(`/agency/sales/${_qcSaleId}/quick-update`, {
                method: 'POST',
                headers: { 'Content-Type':'application/json', 'Accept':'application/json', 'X-CSRF-TOKEN':'{{ csrf_token() }}' },
                body: JSON.stringify(qcBuildPayload())
            })
            .then(r => r.json())
            .then(d => qcSetSaveState(d.success ? 'saved' : 'error'))
            .catch(() => qcSetSaveState('error'));
        }, 650);
    }
    window.qcAutoSave = qcAutoSave;

    // "Kapat": çekmeceyi kapatır. Otomatik kayıt zaten her değişiklikte çalıştığı için
    // burada ekstra kayıt/yenileme YOK — sayfa asla reload edilmez.
    function qcClose() {
        closeQuickView();
    }
    window.qcClose = qcClose;

    // Drawer içindeki alan değişimlerinde otomatik kaydet (katalog modalı ve müşteri arama hariç)
    (function () {
        const bind = () => {
            const wrap = document.querySelector('.qv-sales-wrapper');
            if (!wrap || wrap.__qcAutoBound) return;
            wrap.__qcAutoBound = true;
            const handler = (e) => {
                const t = e.target;
                if (!t.matches || !t.matches('input, textarea, select')) return;
                if (t.closest('#qvProductCatalogModal') || t.closest('#qc-cust-dropdown')) return;
                qcAutoSave();
            };
            wrap.addEventListener('input', handler);
            wrap.addEventListener('change', handler);
        };
        bind();
        setTimeout(bind, 300);
    })();

    // ─── ZENGİN METİN (QUILL) NOT EDİTÖRLERİ ─────────────────────────────────────
    // Müşteri Notu ve Dahili Not alanları Quill ile zengin metin. İçerik gizli
    // textarea'ya senkronlanır (qcBuildPayload buradan okur) ve her değişimde
    // otomatik kayıt tetiklenir.
    (function initQcNoteEditors() {
        if (typeof Quill === 'undefined') return;
        function makeNoteQuill(editorId, hiddenId) {
            const el = document.getElementById(editorId);
            const hidden = document.getElementById(hiddenId);
            if (!el || !hidden || el.__quillInit) return null;
            el.__quillInit = true;
            const q = new Quill(el, {
                theme: 'snow',
                placeholder: el.dataset.placeholder || 'Buraya yazın...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline'],
                        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                        [{ 'header': [3, 4, false] }],
                        ['link', 'clean']
                    ]
                }
            });
            const sync = () => { hidden.value = q.getText().trim().length ? q.root.innerHTML : ''; };
            sync();
            q.on('text-change', () => { sync(); if (typeof qcAutoSave === 'function') qcAutoSave(); });
            return q;
        }
        window.qcCustomerNoteQuill = makeNoteQuill('qc-customer-note-editor', 'qc-customer-note');
        window.qcInternalNoteQuill = makeNoteQuill('qc-internal-note-editor', 'qc-internal-note');
    })();

    // ─── STATUS PIPELINE ────────────────────────────────────────────────────────
    var qcStatusLabels = @json(collect($statusSteps)->map(fn($v,$k)=>$v['label'])->toArray());

    function qcSelectStatus(key, el) {
        document.getElementById('qc-status-value').value = key;
        document.getElementById('qc-metric-status').textContent = qcStatusLabels[key] || key;

        const segs = document.querySelectorAll('#qc-pipeline .sqv-seg');
        const keys = Object.keys(qcStatusLabels);
        const selectedIdx = keys.indexOf(key);

        segs.forEach((seg, i) => {
            seg.classList.remove('done', 'current', 'future');
            if (i < selectedIdx)       seg.classList.add('done');
            else if (i === selectedIdx) seg.classList.add('current');
            else                        seg.classList.add('future');
        });
        if (typeof qcAutoSave === 'function') qcAutoSave();
    }

    // ─── METRICS UPDATE ──────────────────────────────────────────────────────────
    function qcUpdateMetrics() {
        const total  = parseFloat(document.getElementById('qc-total-amount').value) || 0;
        const paid   = parseFloat(document.getElementById('qc-paid-amount').value) || 0;
        const remaining = Math.max(0, total - paid);

        const adults   = parseInt(document.getElementById('qc-adult').value) || 0;
        const children = parseInt(document.getElementById('qc-child').value) || 0;
        const infants  = parseInt(document.getElementById('qc-infant').value) || 0;
        const people   = adults + children + infants;

        const saleCurrency = document.getElementById('qc-currency').value || 'TRY';
        const saleSymbol = (window.currencySymbols || {})[saleCurrency] || saleCurrency;

        const fmt = v => saleSymbol + v.toLocaleString('tr-TR', {minimumFractionDigits:2, maximumFractionDigits:2});
        document.getElementById('qc-metric-total').textContent     = fmt(total);
        document.getElementById('qc-metric-paid').textContent      = fmt(paid);
        document.getElementById('qc-metric-remaining').textContent  = fmt(remaining);
        document.getElementById('qc-metric-people').textContent    = people;
        document.getElementById('qc-remaining-display').value      = remaining.toFixed(2);

        // Auto payment status
        const ps = document.getElementById('qc-payment-status');
        if (paid === 0)       ps.value = 'unpaid';
        else if (paid >= total) ps.value = 'paid';
        else                    ps.value = 'partial';
    }

    // Sync product grand total to the total amount field
    // Kullanıcı toplam tutarı elle girdiyse otomatik senkron onu ezmez
    var _qcTotalManual = false;
    function qcTotalEdited() { _qcTotalManual = true; qcUpdateMetrics(); }

    function qcSyncProductTotals(silent, auto) {
        // auto=true → ürün eklendikçe otomatik senkron; kullanıcı tutarı elle girmişse dokunma
        if (auto === true && _qcTotalManual) { qcUpdateMetrics(); return; }
        const totalEl = document.getElementById('qv-summary-total');
        if (!totalEl) return;
        const text = totalEl.textContent.replace(/[^0-9,-]/g, '').replace(',', '.');
        const val  = parseFloat(text) || 0;
        document.getElementById('qc-total-amount').value = val.toFixed(2);
        if (auto !== true) _qcTotalManual = false; // elle "Toplamı Güncelle" → manuel bayrağı sıfırla
        qcUpdateMetrics();
        if (silent !== true && typeof Swal !== 'undefined') {
            Swal.fire({ icon:'success', title:'Toplam Güncellendi', text:'Ürün toplamı "Genel" sekmesine aktarıldı.', timer:1500, showConfirmButton:false });
        }
    }

    // Genel sekmesi alanlarını (yalnızca boşsa) ürün seçiminden doldur
    function qcAutofillGeneral(name, typeId) {
        const t = document.getElementById('qc-title');
        if (t && !t.value.trim() && name) {
            t.value = name;
            if (typeof qcUpdateHeaderSubtitle === 'function') qcUpdateHeaderSubtitle();
        }
        const pt = document.getElementById('qc-product-type');
        if (pt && !pt.value && typeId && [...pt.options].some(o => o.value == typeId)) {
            pt.value = String(typeId);
        }
    }

    // Kalem adını elle yazıp çıkınca, satış başlığı boşsa otomatik doldur
    function qcRowNameChanged(input) {
        const name = (input.value || '').trim();
        if (!name) return;
        const t = document.getElementById('qc-title');
        if (t && !t.value.trim()) { t.value = name; if (typeof qcUpdateHeaderSubtitle === 'function') qcUpdateHeaderSubtitle(); }
    }

    // ─── CUSTOMER (aranabilir seçici + hızlı ekleme) ─────────────────────────────
    function qcEsc(s){ return (s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
    function qcInitials(name){ return (name||'?').split(/\s+/).map(w=>w[0]||'').slice(0,2).join('').toUpperCase() || '?'; }
    function qcUpdateHeaderSubtitle() { /* başlık header'da gösterilmiyor; no-op */ }

    function qcToggleCustomerForm(forceOpen) {
        const f = document.getElementById('qc-quick-customer-form');
        const willOpen = (forceOpen === true) ? true : (forceOpen === false ? false : f.classList.contains('d-none'));
        f.classList.toggle('d-none', !willOpen);
        const err = document.getElementById('qc-newcust-error'); if (err) err.style.display = 'none';
        if (willOpen) {
            qcCustClose();
            const fn = document.getElementById('qc_new_first_name');
            // Arama kutusundaki metni ada/soyada ön-doldur
            const q = (document.getElementById('qc-cust-search-input')?.value || '').trim();
            if (q && fn && !fn.value) { const p = q.split(' '); fn.value = p[0]; if (p.length > 1) document.getElementById('qc_new_last_name').value = p.slice(1).join(' '); }
            setTimeout(() => fn && fn.focus(), 60);
        }
    }

    // ── Aranabilir müşteri seçici (server-side) ──
    var _qcCustT = null;
    function qcCustToggle(e) {
        if (e) e.stopPropagation();
        const dd = document.getElementById('qc-cust-dropdown');
        const open = !dd.classList.contains('open');
        dd.classList.toggle('open', open);
        document.getElementById('qc-cust-trigger').classList.toggle('open', open);
        if (open) {
            const si = document.getElementById('qc-cust-search-input');
            si.value = '';
            qcCustDoSearch('');
            setTimeout(() => si.focus(), 50);
        }
    }
    function qcCustClose() {
        document.getElementById('qc-cust-dropdown')?.classList.remove('open');
        document.getElementById('qc-cust-trigger')?.classList.remove('open');
    }
    function qcCustSearch(q) { clearTimeout(_qcCustT); _qcCustT = setTimeout(() => qcCustDoSearch(q), 220); }
    function qcCustDoSearch(q) {
        const list = document.getElementById('qc-cust-list');
        list.innerHTML = '<div class="qc-cust-loading"><i class="fas fa-spinner fa-spin me-1"></i> Aranıyor…</div>';
        fetch(URL_CUSTOMER_SEARCH + '?q=' + encodeURIComponent(q), { headers: { 'Accept': 'application/json' } })
            .then(r => r.json())
            .then(d => qcCustRender(Array.isArray(d) ? d : (d.results || d.data || [])))
            .catch(() => { list.innerHTML = '<div class="qc-cust-empty">Arama başarısız oldu.</div>'; });
    }
    function qcCustRender(items) {
        const list = document.getElementById('qc-cust-list');
        if (!items || !items.length) {
            list.innerHTML = '<div class="qc-cust-empty"><i class="fas fa-user-slash me-1"></i> Eşleşen müşteri yok.</div>';
            return;
        }
        list.innerHTML = items.map(c => {
            const txt = c.text || c.name || '';
            const parts = txt.split(' — ');
            const name = parts[0];
            const sub = parts.slice(1).join(' — ');
            const payload = qcEsc(JSON.stringify({ id: c.id, name: name, sub: sub }));
            return `<div class="qc-cust-row" data-c="${payload}" onclick="qcCustSelectEl(this)">
                <div class="qc-cust-av">${qcEsc(qcInitials(name))}</div>
                <div class="qc-cust-meta"><div class="qc-cust-name">${qcEsc(name)}</div>${sub ? '<div class="qc-cust-sub">'+qcEsc(sub)+'</div>' : ''}</div>
                <i class="fas fa-circle-check qc-cust-pick"></i>
            </div>`;
        }).join('');
    }
    function qcCustSelectEl(el) { let d = {}; try { d = JSON.parse(el.getAttribute('data-c')); } catch(e){} qcCustSelect(d.id, d.name, d.sub); }
    function qcCustSelect(id, name, sub) {
        document.getElementById('qc-customer-id').value = id || '';
        const ico = document.getElementById('qc-cust-tr-ico');
        const txt = document.getElementById('qc-cust-tr-txt');
        const trg = document.getElementById('qc-cust-trigger');
        if (id) {
            ico.innerHTML = qcEsc(qcInitials(name)); ico.classList.add('has');
            txt.innerHTML = `<b>${qcEsc(name)}</b>${sub ? ' <span class="qc-cust-tr-sub">'+qcEsc(sub)+'</span>' : ''}`;
            trg.classList.add('selected');
        } else {
            ico.innerHTML = '<i class="fas fa-magnifying-glass"></i>'; ico.classList.remove('has');
            txt.textContent = 'Müşteri seçin veya arayın…'; trg.classList.remove('selected');
        }
        const lbl = document.getElementById('qc-customer-label');
        if (lbl) lbl.innerHTML = id ? `<i class="fas fa-user"></i> ${qcEsc(name)}` : `<i class="fas fa-user"></i> Müşteri seçin`;
        qcCustClose();
        if (typeof qcAutoSave === 'function') qcAutoSave();
    }

    // Dropdown dışına tıklayınca kapat (bir kez bağla)
    if (!window.__qcCustOutsideBound) {
        window.__qcCustOutsideBound = true;
        document.addEventListener('click', function (e) {
            const picker = document.getElementById('qc-cust-picker');
            if (picker && !picker.contains(e.target)) qcCustClose();
        });
    }

    function qcSaveQuickCustomer() {
        const first = document.getElementById('qc_new_first_name').value.trim();
        const last  = document.getElementById('qc_new_last_name').value.trim();
        const phone = document.getElementById('qc_new_phone').value.trim();
        const email = document.getElementById('qc_new_email').value.trim();
        const national_id = document.getElementById('qc_new_national_id').value.trim();
        const gender = document.getElementById('qc_new_gender').value;
        const errBox = document.getElementById('qc-newcust-error');
        const showErr = (msg) => { errBox.innerHTML = msg; errBox.style.display = ''; };
        errBox.style.display = 'none';

        if (!first || !last) { showErr('<i class="fas fa-circle-exclamation me-1"></i> Ad ve soyad zorunludur.'); return; }
        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { showErr('<i class="fas fa-circle-exclamation me-1"></i> Geçerli bir e-posta girin ya da boş bırakın.'); return; }

        const btn = document.getElementById('qc-nc-save-btn');
        const reset = () => { btn.disabled = false; btn.querySelector('.qc-nc-save-txt').classList.remove('d-none'); btn.querySelector('.qc-nc-save-load').classList.add('d-none'); };
        btn.disabled = true; btn.querySelector('.qc-nc-save-txt').classList.add('d-none'); btn.querySelector('.qc-nc-save-load').classList.remove('d-none');

        fetch('{{ route("agency.sales.api.quick-customer") }}', {
            method: 'POST',
            headers: {'Content-Type':'application/json','Accept':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}'},
            body: JSON.stringify({ first_name:first, last_name:last, phone, email, national_id, gender })
        })
        .then(r => r.json())
        .then(d => {
            reset();
            if (d.success && d.customer) {
                qcCustSelect(d.customer.id, d.customer.full_name, d.customer.phone || d.customer.email || '');
                ['qc_new_first_name','qc_new_last_name','qc_new_phone','qc_new_email','qc_new_national_id'].forEach(id => document.getElementById(id).value = '');
                document.getElementById('qc_new_gender').value = '';
                qcToggleCustomerForm(false);
                if (typeof Swal !== 'undefined') Swal.fire({icon:'success', title:'Müşteri eklendi', text:d.customer.full_name + ' seçildi.', timer:1600, showConfirmButton:false});
            } else if (d.errors) {
                showErr('<i class="fas fa-circle-exclamation me-1"></i> ' + Object.values(d.errors).flat().map(qcEsc).join('<br>'));
            } else {
                showErr('<i class="fas fa-circle-exclamation me-1"></i> ' + qcEsc(d.message || 'Müşteri eklenemedi.'));
            }
        })
        .catch(() => { reset(); showErr('<i class="fas fa-triangle-exclamation me-1"></i> Sunucuya ulaşılamadı.'); });
    }

    // ─── KATALOG (ürün / tur tarihi / tedarikçi hizmeti) ─────────────────────────
    var _catalogTargetRow = null;
    var _catalogCurrentTour = null; // { id, name, currency, price } — tur tarihi drill sırasında
    var _catalogDates = [];          // getProductDates sonucu
    var _catalogSelectedDate = null; // fiyat tipi seçiciyi besleyen seçili tarih

    function fmtNum(v) { return (parseFloat(v) || 0).toLocaleString('tr-TR', { maximumFractionDigits: 0 }); }

    function openProductCatalog(row) {
        _catalogTargetRow = row || null;
        catalogSwitchTab('products', document.querySelector('.qvcat-tab[data-cat-tab="products"]'));
        catalogBackToGrid();
        const si = document.getElementById('catalogSearchInput'); if (si) si.value = '';
        const tf = document.getElementById('catalogTypeFilter'); if (tf) tf.value = '';
        const sf = document.getElementById('catalogSupplierFilter'); if (sf) sf.value = '';
        filterCatalog();
        new bootstrap.Modal(document.getElementById('qvProductCatalogModal'), { backdrop: true }).show();
    }

    function catalogSwitchTab(tab, el) {
        document.querySelectorAll('.qvcat-tab').forEach(t => t.classList.remove('active'));
        if (el) el.classList.add('active');
        const isProducts = tab === 'products';
        document.getElementById('catPaneProducts').classList.toggle('active', isProducts);
        document.getElementById('catPaneSuppliers').classList.toggle('active', !isProducts);
        document.getElementById('catalogTypeFilter').style.display = isProducts ? '' : 'none';
        document.getElementById('catalogSupplierFilter').style.display = isProducts ? 'none' : '';
        const ccf = document.getElementById('catalogCurrencyFilter');
        if (ccf) ccf.style.display = isProducts ? 'none' : '';
        const si = document.getElementById('catalogSearchInput');
        if (si) si.placeholder = isProducts ? 'Ara: tur veya ürün adı...' : 'Ara: hizmet, oda tipi veya tedarikçi...';
        if (!isProducts) catalogBackToGrid();
        filterCatalog();
    }

    function filterCatalog() {
        const q = (document.getElementById('catalogSearchInput')?.value || '').toLowerCase().trim();
        const suppliersActive = document.getElementById('catPaneSuppliers').classList.contains('active');
        if (suppliersActive) {
            const tf = document.getElementById('catalogSupplierFilter')?.value || '';
            const cf = document.getElementById('catalogCurrencyFilter')?.value || '';
            let vis = 0;
            document.querySelectorAll('#catalogSupplierGrid .catalog-supplier-item').forEach(it => {
                const show = (!q || (it.dataset.name || '').includes(q)) && (!tf || it.dataset.supType === tf) && (!cf || it.dataset.currency === cf);
                it.style.display = show ? '' : 'none';
                if (show) vis++;
            });
            document.querySelectorAll('#catalogSupplierGrid .qvcat-group').forEach(g => {
                g.style.display = g.querySelectorAll('.catalog-supplier-item:not([style*="none"])').length ? '' : 'none';
            });
            document.getElementById('catalogSupplierNoResults')?.classList.toggle('d-none', vis > 0);
        } else {
            const tf = document.getElementById('catalogTypeFilter')?.value || '';
            let vis = 0;
            document.querySelectorAll('#catalogProductGrid .catalog-product-item').forEach(it => {
                const show = (!q || (it.dataset.name || '').includes(q)) && (!tf || it.dataset.typeId === tf);
                it.style.display = show ? '' : 'none';
                if (show) vis++;
            });
            document.querySelectorAll('#catalogProductGrid .qvcat-group').forEach(g => {
                g.style.display = g.querySelectorAll('.catalog-product-item:not([style*="none"])').length ? '' : 'none';
            });
            document.getElementById('catalogNoResults')?.classList.toggle('d-none', vis > 0);
        }
    }

    function catalogBackToGrid() {
        const grid = document.getElementById('catalogProductGrid');
        const dv = document.getElementById('catalogDateView');
        if (grid) grid.style.display = '';
        if (dv) dv.style.display = 'none';
        catalogCloseFares();
    }

    // Ürün karta tıklama: tur ise tarih drill-down, değilse doğrudan seç
    function catalogPickProduct(el) {
        const hasDates = el.dataset.hasDates === '1';
        const id = el.dataset.id, name = el.dataset.pname, typeId = el.dataset.typeId || '';
        const price = parseFloat(el.dataset.price) || 0, currency = el.dataset.currency || 'TRY';
        if (hasDates) catalogShowDates(id, name, currency, price, typeId);
        else selectFromCatalog(id, name, price, currency, typeId);
    }

    // Tur tarihi drill-down: getProductDates ile fiyatlı tarihleri getir
    function catalogShowDates(productId, name, currency, basePrice, typeId) {
        _catalogCurrentTour = { id: productId, name: name, currency: currency, price: basePrice || 0, typeId: typeId || '' };
        document.getElementById('catalogProductGrid').style.display = 'none';
        document.getElementById('catalogDateView').style.display = '';
        document.getElementById('catalogDateTourName').textContent = name;
        catalogCloseFares();
        // Özel tarih bölümünü kapat + varsayılan fiyat/döviz doldur
        const cbody = document.getElementById('catalogCustomBody'); if (cbody) cbody.style.display = 'none';
        const cchev = document.getElementById('catalogCustomChevron'); if (cchev) cchev.style.transform = '';
        const cprice = document.getElementById('catalogCustomPrice'); if (cprice) cprice.value = basePrice ? basePrice : '';
        const ccur = document.getElementById('catalogCustomCurrency'); if (ccur && [...ccur.options].some(o => o.value === currency)) ccur.value = currency;

        const grid = document.getElementById('catalogDateGrid');
        const loading = document.getElementById('catalogDateLoading');
        const none = document.getElementById('catalogDateNoUpcoming');
        grid.innerHTML = ''; grid.style.display = 'none';
        none.classList.add('d-none');
        loading.style.display = '';
        _catalogDates = [];
        fetch(URL_DATES + '?product_id=' + encodeURIComponent(productId))
            .then(r => r.json())
            .then(d => {
                loading.style.display = 'none';
                if (!d.has_dates || !d.dates || !d.dates.length) {
                    none.classList.remove('d-none');
                    if (cbody) cbody.style.display = '';        // kayıtlı tarih yoksa özel tarihi otomatik aç
                    if (cchev) cchev.style.transform = 'rotate(180deg)';
                    return;
                }
                _catalogDates = d.dates;
                grid.style.display = '';
                grid.innerHTML = d.dates.map((dt, i) => catalogDateCardHTML(dt, i)).join('');
            })
            .catch(() => { loading.style.display = 'none'; none.classList.remove('d-none'); });
    }

    function catalogDateCardHTML(dt, i) {
        const cur = dt.currency || 'TRY';
        const cap = (dt.remaining_capacity === null || dt.remaining_capacity === undefined) ? '∞' : dt.remaining_capacity;
        const range = dt.start_date_display + ((dt.end_date_display && dt.end_date !== dt.start_date) ? ' – ' + dt.end_date_display : '');
        const guar = dt.guarantee_departure ? '<span class="qvcat-date-guar"><i class="fas fa-shield-halved"></i> Garantili</span>' : '';
        const child = (parseFloat(dt.child_price) > 0) ? `<span>Çocuk <b>${fmtNum(dt.child_price)}</b></span>` : '';
        const infant = (parseFloat(dt.infant_price) > 0) ? `<span>Bebek <b>${fmtNum(dt.infant_price)}</b></span>` : '';
        const single = (parseFloat(dt.single_supplement) > 0) ? `<span>Tek Kişi +<b>${fmtNum(dt.single_supplement)}</b></span>` : '';
        const bed = (parseFloat(dt.extra_bed_price) > 0) ? `<span>Ek Yatak <b>${fmtNum(dt.extra_bed_price)}</b></span>` : '';
        return `<div class="qvcat-date-card" data-date-idx="${i}" onclick="catalogSelectDate(${i})">
            <div class="qvcat-date-top">
                <div class="qvcat-date-when"><i class="fas fa-calendar-day"></i> ${range}</div>
                ${guar}
            </div>
            <div class="qvcat-date-prices">
                <span class="adult">Yetişkin <b>${fmtNum(dt.adult_price)} ${cur}</b></span>
                ${child}${infant}${single}${bed}
            </div>
            <div class="qvcat-date-foot">
                <span class="qvcat-date-cap"><i class="fas fa-users"></i> ${cap} kişilik yer</span>
                <span class="qvcat-date-pick">Fiyat tipi seç <i class="fas fa-arrow-right"></i></span>
            </div>
        </div>`;
    }

    // Bir tarih seçilince fiyat tipi panelini aç
    function catalogSelectDate(i) {
        const dt = _catalogDates[i];
        if (!dt) return;
        _catalogSelectedDate = dt;
        document.querySelectorAll('#catalogDateGrid .qvcat-date-card').forEach(c => c.classList.toggle('sel', c.dataset.dateIdx == i));
        catalogRenderFares(dt);
        const panel = document.getElementById('catalogFarePanel');
        panel.style.display = '';
        panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    // Seçili tarihte mevcut fiyat tipleri (0 olanlar gizlenir; adet Genel sekmesinden ön dolu)
    function catalogFareDefs(dt) {
        const a = parseInt(document.getElementById('qc-adult').value) || 1;
        const c = parseInt(document.getElementById('qc-child').value) || 0;
        const inf = parseInt(document.getElementById('qc-infant').value) || 0;
        const defs = [{ key: 'adult', label: 'Yetişkin', icon: 'fa-user', price: parseFloat(dt.adult_price) || 0, qty: a }];
        if (parseFloat(dt.child_price) > 0) defs.push({ key: 'child', label: 'Çocuk', icon: 'fa-child', price: parseFloat(dt.child_price), qty: c });
        if (parseFloat(dt.infant_price) > 0) defs.push({ key: 'infant', label: 'Bebek', icon: 'fa-baby', price: parseFloat(dt.infant_price), qty: inf });
        if (parseFloat(dt.single_supplement) > 0) defs.push({ key: 'single', label: 'Tek Kişilik Farkı', icon: 'fa-bed', price: parseFloat(dt.single_supplement), qty: 0 });
        if (parseFloat(dt.extra_bed_price) > 0) defs.push({ key: 'extra_bed', label: 'Ek Yatak', icon: 'fa-bed-pulse', price: parseFloat(dt.extra_bed_price), qty: 0 });
        return defs;
    }

    function catalogRenderFares(dt) {
        const cur = dt.currency || (_catalogCurrentTour && _catalogCurrentTour.currency) || 'TRY';
        document.getElementById('catalogFareDate').textContent = dt.start_date_display + ((dt.end_date_display && dt.end_date !== dt.start_date) ? ' – ' + dt.end_date_display : '');
        document.getElementById('catalogFareRows').innerHTML = catalogFareDefs(dt).map(f => `
            <div class="qvcat-fare-row" data-fare-key="${f.key}" data-fare-label="${f.label}" data-fare-price="${f.price}">
                <span class="qvcat-fare-label"><i class="fas ${f.icon}"></i> ${f.label}</span>
                <span class="qvcat-fare-unit">${fmtNum(f.price)} ${cur}</span>
                <span class="qvcat-fare-qty"><input type="number" min="0" step="1" value="${f.qty}" oninput="catalogRecalcFares()"></span>
                <span class="qvcat-fare-sub">0 ${cur}</span>
            </div>`).join('');
        catalogRecalcFares();
    }

    function catalogRecalcFares() {
        const cur = (_catalogSelectedDate && _catalogSelectedDate.currency) || (_catalogCurrentTour && _catalogCurrentTour.currency) || 'TRY';
        let total = 0;
        document.querySelectorAll('#catalogFareRows .qvcat-fare-row').forEach(r => {
            const price = parseFloat(r.dataset.farePrice) || 0;
            const qty = parseInt(r.querySelector('input').value) || 0;
            const sub = price * qty;
            total += sub;
            r.querySelector('.qvcat-fare-sub').textContent = fmtNum(sub) + ' ' + cur;
        });
        document.getElementById('catalogFareTotal').textContent = fmtNum(total) + ' ' + cur;
    }

    function catalogApplyFares() {
        const dt = _catalogSelectedDate;
        if (!dt) return;
        const fares = [];
        document.querySelectorAll('#catalogFareRows .qvcat-fare-row').forEach(r => {
            fares.push({ key: r.dataset.fareKey, label: r.dataset.fareLabel, qty: parseInt(r.querySelector('input').value) || 0, price: parseFloat(r.dataset.farePrice) || 0 });
        });
        if (!fares.some(f => f.qty > 0)) { if (typeof Swal !== 'undefined') Swal.fire({ icon: 'warning', title: 'Adet girin', text: 'En az bir fiyat tipi için adet girmelisiniz.' }); return; }
        applyTourDate(dt, fares);
    }

    function catalogCloseFares() {
        const p = document.getElementById('catalogFarePanel');
        if (p) p.style.display = 'none';
        _catalogSelectedDate = null;
        document.querySelectorAll('#catalogDateGrid .qvcat-date-card.sel').forEach(c => c.classList.remove('sel'));
    }

    // Tur + tarih + seçili fiyat tipleri uygula: satışı kalkışa bağla + kalemleri üret
    function applyTourDate(dt, fares) {
        const tour = _catalogCurrentTour;
        if (!tour) return;

        document.getElementById('qc-product-id').value = tour.id;
        document.getElementById('qc-tour-date-id').value = dt.id;
        document.getElementById('qc-tour-date-type').value = dt.date_type || '';
        if (dt.start_date) document.getElementById('qc-start-date').value = dt.start_date;
        if (dt.end_date) document.getElementById('qc-end-date').value = dt.end_date;

        const cur = dt.currency || tour.currency || 'TRY';
        const curSel = document.getElementById('qc-currency');
        if (curSel && [...curSel.options].some(o => o.value === cur)) curSel.value = cur;

        // Katılımcı sayılarını seçilen fiyat tiplerinden Genel sekmesine yansıt
        const byKey = {}; fares.forEach(f => { if (f.key) byKey[f.key] = f.qty; });
        if (byKey.adult != null) document.getElementById('qc-adult').value = byKey.adult || 1;
        if (byKey.child != null) document.getElementById('qc-child').value = byKey.child;
        if (byKey.infant != null) document.getElementById('qc-infant').value = byKey.infant;

        // Yalnızca önceki tur satırlarını + boş satırları temizle; elle eklenenler kalsın.
        // Tur fiyatları kişi-başı ve KDV-dahil kabul edilir → satır KDV'si 0 (çifte vergi olmasın).
        removeTourRows();
        fares.filter(f => f.qty > 0).forEach(f => addBlankQvProductRow({ name: tour.name + ' · ' + f.label, qty: f.qty, price: f.price, currency: cur, productId: tour.id, tax: 0, tourLine: true }));

        calculateQvProductTotals();
        qcSyncProductTotals(true, true);
        qcAutofillGeneral(tour.name, tour.typeId);
        showDepartureBanner(tour.name, dt, cur, false);

        bootstrap.Modal.getInstance(document.getElementById('qvProductCatalogModal'))?.hide();
        const tabEl = document.querySelector('.qv-tab[onclick*="qcproducts"]');
        if (tabEl && typeof switchQvTab === 'function') switchQvTab('qcproducts', tabEl);
        if (typeof qcAutoSave === 'function') qcAutoSave();
    }

    // Özel tarih: turu seç, kayıtlı kalkışa bağlanmadan özel tarih + fiyatla sat
    function applyCustomTourDate() {
        const tour = _catalogCurrentTour;
        if (!tour) return;
        const start = document.getElementById('catalogCustomStart').value;
        const end = document.getElementById('catalogCustomEnd').value;
        const price = parseFloat(document.getElementById('catalogCustomPrice').value) || 0;
        const cur = document.getElementById('catalogCustomCurrency').value || 'TRY';
        if (!start) { if (typeof Swal !== 'undefined') Swal.fire({ icon: 'warning', title: 'Tarih gerekli', text: 'Başlangıç tarihi girin.' }); return; }

        document.getElementById('qc-product-id').value = tour.id;   // ürüne bağla (reservable)
        document.getElementById('qc-tour-date-id').value = '';      // belirli bir kalkışa bağlama
        document.getElementById('qc-tour-date-type').value = '';
        document.getElementById('qc-start-date').value = start;
        if (end) document.getElementById('qc-end-date').value = end;
        const curSel = document.getElementById('qc-currency');
        if (curSel && [...curSel.options].some(o => o.value === cur)) curSel.value = cur;

        const adults = parseInt(document.getElementById('qc-adult').value) || 1;
        const children = parseInt(document.getElementById('qc-child').value) || 0;
        const infants = parseInt(document.getElementById('qc-infant').value) || 0;

        removeTourRows();
        addBlankQvProductRow({ name: tour.name + ' · Yetişkin (özel tarih)', qty: adults, price: price, currency: cur, productId: tour.id, tax: 0, tourLine: true });
        if (children > 0) addBlankQvProductRow({ name: tour.name + ' · Çocuk (özel tarih)', qty: children, price: 0, currency: cur, productId: tour.id, tax: 0, tourLine: true });
        if (infants > 0) addBlankQvProductRow({ name: tour.name + ' · Bebek (özel tarih)', qty: infants, price: 0, currency: cur, productId: tour.id, tax: 0, tourLine: true });

        calculateQvProductTotals();
        qcSyncProductTotals(true, true);
        qcAutofillGeneral(tour.name, tour.typeId);
        showDepartureBanner(tour.name, { start_date_display: catalogFmtDate(start), end_date_display: end ? catalogFmtDate(end) : null, end_date: end, start_date: start, adult_price: price, remaining_capacity: null }, cur, true);

        bootstrap.Modal.getInstance(document.getElementById('qvProductCatalogModal'))?.hide();
        const tabEl = document.querySelector('.qv-tab[onclick*="qcproducts"]');
        if (tabEl && typeof switchQvTab === 'function') switchQvTab('qcproducts', tabEl);
        if (typeof qcAutoSave === 'function') qcAutoSave();
    }

    function catalogToggleCustomDate() {
        const body = document.getElementById('catalogCustomBody');
        const chev = document.getElementById('catalogCustomChevron');
        if (!body) return;
        const open = body.style.display !== 'none';
        body.style.display = open ? 'none' : '';
        if (chev) chev.style.transform = open ? '' : 'rotate(180deg)';
    }

    function catalogFmtDate(s) {
        if (!s) return '';
        const d = new Date(s + 'T00:00:00');
        if (isNaN(d.getTime())) return s;
        return d.toLocaleDateString('tr-TR', { day: '2-digit', month: 'short', year: 'numeric' });
    }

    function showDepartureBanner(name, dt, cur, custom) {
        const b = document.getElementById('qc-departure-banner');
        if (!b) return;
        document.getElementById('qc-dep-title').textContent = name;
        const range = dt.start_date_display + ((dt.end_date_display && dt.end_date !== dt.start_date) ? ' – ' + dt.end_date_display : '');
        document.getElementById('qc-dep-sub').innerHTML = `<i class="fas fa-calendar-day me-1"></i>${range}` + (parseFloat(dt.adult_price) > 0 ? ` · Yetişkin ${fmtNum(dt.adult_price)} ${cur}` : '');
        document.getElementById('qc-dep-cap').innerHTML = custom
            ? '<i class="fas fa-pen me-1"></i>Özel tarih'
            : `<i class="fas fa-users me-1"></i>${(dt.remaining_capacity === null || dt.remaining_capacity === undefined) ? '∞' : dt.remaining_capacity} yer`;
        b.style.display = '';
    }

    function clearTourDeparture() {
        document.getElementById('qc-product-id').value = '';
        document.getElementById('qc-tour-date-id').value = '';
        document.getElementById('qc-tour-date-type').value = '';
        const b = document.getElementById('qc-departure-banner');
        if (b) b.style.display = 'none';
        _catalogCurrentTour = null;
        if (typeof qcAutoSave === 'function') qcAutoSave();
    }

    function clearProductRows() {
        document.querySelectorAll('#qv-products-tbody .qv-product-row').forEach(r => r.remove());
        const empty = document.getElementById('qv-no-products-row');
        if (empty) empty.remove();
    }

    // Yalnızca otomatik üretilen tur satırlarını ve tamamen boş satırları kaldır (elle eklenenler kalsın)
    function removeTourRows() {
        document.querySelectorAll('#qv-products-tbody .qv-product-row').forEach(r => {
            const isTourLine = r.dataset.tourLine === '1';
            const nameEmpty = !r.querySelector('.qv-product-name').value.trim();
            if (isTourLine || nameEmpty) r.remove();
        });
        const empty = document.getElementById('qv-no-products-row');
        if (empty) empty.remove();
    }

    // Katalog seçimi için doldurulacak satır: hedef satır → mevcut boş satır → yeni satır
    function catGetFillableRow() {
        if (_catalogTargetRow) return _catalogTargetRow;
        const rows = document.querySelectorAll('#qv-products-tbody .qv-product-row');
        for (const r of rows) { if (!r.querySelector('.qv-product-name').value.trim()) return r; }
        return addBlankQvProductRow();
    }

    // Basit ürün seçimi (tur değil) — hedef satır yoksa yeni satır aç
    function selectFromCatalog(id, name, price, currency, typeId) {
        const row = catGetFillableRow();
        if (!row) return;
        row.querySelector('.row-product-id').value = id || '';
        row.querySelector('.row-itemable-type').value = '';
        row.querySelector('.row-itemable-id').value = '';
        row.querySelector('.qv-product-name').value = name;
        row.querySelector('.qv-product-price').value = price;
        const ce = row.querySelector('.qv-product-currency');
        if (ce && [...ce.options].some(o => o.value === currency)) ce.value = currency;
        calculateQvProductTotals();
        qcSyncProductTotals(true, true);
        qcAutofillGeneral(name, typeId);
        bootstrap.Modal.getInstance(document.getElementById('qvProductCatalogModal'))?.hide();
        _catalogTargetRow = null;
        if (typeof qcAutoSave === 'function') qcAutoSave();
    }

    // Tedarikçi hizmeti seçimi — itemable (SupplierPriceItem) bağı + satış fiyatı + KDV
    function catalogPickSupplier(el) {
        const row = catGetFillableRow();
        if (!row) return;
        const title = el.dataset.title || '';
        const supplier = el.dataset.supplier || '';
        const price = parseFloat(el.dataset.price) || 0;
        const currency = el.dataset.currency || 'TRY';
        const tax = parseFloat(el.dataset.tax) || 0;
        row.querySelector('.row-product-id').value = '';
        row.querySelector('.row-itemable-type').value = 'App\\Models\\Supplier\\SupplierPriceItem';
        row.querySelector('.row-itemable-id').value = el.dataset.id || '';
        row.querySelector('.qv-product-name').value = (supplier && supplier !== '—') ? (title + ' — ' + supplier) : title;
        row.querySelector('.qv-product-price').value = price;
        const ce = row.querySelector('.qv-product-currency');
        if (ce && [...ce.options].some(o => o.value === currency)) ce.value = currency;
        const te = row.querySelector('.qv-product-tax');
        if (te) { let opt = [...te.options].find(o => parseFloat(o.value) === tax); if (!opt) { opt = new Option('%' + tax, tax); te.add(opt); } te.value = opt.value; }
        calculateQvProductTotals();
        qcSyncProductTotals(true, true);
        qcAutofillGeneral(title, null);
        bootstrap.Modal.getInstance(document.getElementById('qvProductCatalogModal'))?.hide();
        _catalogTargetRow = null;
        if (typeof qcAutoSave === 'function') qcAutoSave();
    }

    function addBlankQvProductRow(prefill) {
        const tbody = document.getElementById('qv-products-tbody');
        if (!tbody) return null;
        const emptyRow = document.getElementById('qv-no-products-row');
        if (emptyRow) emptyRow.remove();
        // Yeni satır dövizi: bir önceki satırın dövizi, hiç satır yoksa TRY
        const _prevRows = tbody.querySelectorAll('.qv-product-row');
        const prevCurrency = _prevRows.length ? (_prevRows[_prevRows.length - 1].querySelector('.qv-product-currency')?.value || 'TRY') : 'TRY';
        const tr = document.createElement('tr');
        tr.className = 'qv-product-row';
        tr.innerHTML = `
            <td>
                <input type="hidden" class="row-id" value="">
                <input type="hidden" class="row-product-id" value="">
                <input type="hidden" class="row-itemable-type" value="">
                <input type="hidden" class="row-itemable-id" value="">
                <div class="qv-product-name-cell">
                    <input type="text" class="form-control bg-transparent fw-bold text-dark qv-product-name" value="" placeholder="Ürün / hizmet adını yazın..." autocomplete="off" onchange="qcRowNameChanged(this)">
                    <button type="button" class="btn-catalog-pick" onclick="openProductCatalog(this.closest('.qv-product-row'))" title="Katalogdan seç">
                        <i class="fas fa-layer-group"></i><span>Katalog</span>
                    </button>
                </div>
            </td>
            <td>
                <input type="number" class="form-control bg-transparent text-center fw-bold qv-product-qty" value="1" min="0.01" step="any" oninput="calculateQvProductTotals()">
            </td>
            <td>
                <div class="input-group input-group-sm">
                    <input type="number" class="form-control bg-transparent text-end fw-semibold qv-product-price" value="0" min="0" step="any" oninput="calculateQvProductTotals()">
                    <select class="form-select bg-transparent text-muted qv-product-currency" style="max-width:70px;border:none;font-size:0.72rem;" onchange="calculateQvProductTotals()">
                        @foreach($activeCurrencies as $curr)
                            <option value="{{ $curr->code }}">{{ $curr->code }}</option>
                        @endforeach
                    </select>
                </div>
            </td>
            <td>
                <select class="form-select bg-transparent text-center fw-bold qv-product-tax" onchange="calculateQvProductTotals()">
                    @foreach($taxRates as $tax)
                        <option value="{{ (float) $tax->rate }}" @selected($tax->is_default)>%{{ rtrim(rtrim(number_format((float) $tax->rate, 2, '.', ''), '0'), '.') }}</option>
                    @endforeach
                </select>
            </td>
            <td class="text-end text-muted fw-bold"><span class="qv-row-tax-amount">₺0,00</span></td>
            <td class="text-end fw-bold text-primary"><span class="qv-row-total-price">₺0,00</span></td>
            <td class="text-end">
                <button type="button" class="btn btn-link btn-sm text-danger p-0 shadow-none border-0" onclick="removeQvProductRow(this)">
                    <i class="fas fa-trash"></i>
                </button>
            </td>`;
        tbody.appendChild(tr);
        // Döviz varsayılanı: prefill.currency öncelikli, yoksa önceki satırın dövizi / TRY
        const _ce = tr.querySelector('.qv-product-currency');
        if (_ce) { const want = (prefill && prefill.currency) ? prefill.currency : prevCurrency; if ([..._ce.options].some(o => o.value === want)) _ce.value = want; }
        if (prefill) {
            if (prefill.tourLine) tr.dataset.tourLine = '1';
            if (prefill.name != null) tr.querySelector('.qv-product-name').value = prefill.name;
            if (prefill.qty != null) tr.querySelector('.qv-product-qty').value = prefill.qty;
            if (prefill.price != null) tr.querySelector('.qv-product-price').value = prefill.price;
            if (prefill.productId != null) tr.querySelector('.row-product-id').value = prefill.productId;
            if (prefill.tax != null) { const te = tr.querySelector('.qv-product-tax'); if (te) { let opt = [...te.options].find(o => parseFloat(o.value) === parseFloat(prefill.tax)); if (!opt) { opt = new Option('%' + prefill.tax, prefill.tax); te.add(opt); } te.value = opt.value; } }
            calculateQvProductTotals();
        } else {
            tr.querySelector('.qv-product-name').focus();
        }
        return tr;
    }

    function removeQvProductRow(btn) {
        btn.closest('.qv-product-row').remove();
        calculateQvProductTotals();
        if (typeof qcAutoSave === 'function') qcAutoSave();
    }

    // Acentede tanımlı TÜM para birimleriyle çalışır (kurlar currencies tablosundan;
    // exchange_rate = 1 birimin TRY karşılığı, TRY baz = 1).
    function convertAmount(amount, fromCurr, toCurr) {
        if (fromCurr === toCurr) return amount;
        const rates = window.exchangeRates || {};
        const fromRate = fromCurr === 'TRY' ? 1 : (parseFloat(rates[fromCurr]) || 1);
        const toRate   = toCurr   === 'TRY' ? 1 : (parseFloat(rates[toCurr])   || 1);
        return amount * fromRate / toRate;
    }

    // ─── TOPLAM PARA BİRİMİ (tek birim → otomatik, karışık → kullanıcı seçer) ────
    // Kayıtlı seçim kalem dövizinden farklıysa "manuel" olarak başlar (bkz. @php başlığı)
    var _qcCurrencyManual = @json((bool) ($currencyIsManual ?? false));

    function qcOnSaleCurrencyChange(code) {
        _qcCurrencyManual = true;
        const ss = document.getElementById('qv-summary-currency');
        if (ss && [...ss.options].some(o => o.value === code)) ss.value = code;
        calculateQvProductTotals();
        qcUpdateMetrics();
        if (typeof qcAutoSave === 'function') qcAutoSave(); // seçim kalıcı olsun (currency + çevrilen toplam)
    }
    function qcOnSummaryCurrencyChange(code) {
        _qcCurrencyManual = true;
        const cs = document.getElementById('qc-currency');
        if (cs && [...cs.options].some(o => o.value === code)) cs.value = code;
        calculateQvProductTotals();
        qcUpdateMetrics();
        if (typeof qcAutoSave === 'function') qcAutoSave(); // seçim kalıcı olsun (currency + çevrilen toplam)
    }

    // Kalem para birimlerine göre satış dövizini yönet
    function qcAutoFollowCurrency() {
        const curs = new Set();
        document.querySelectorAll('#qv-products-tbody .qv-product-row').forEach(r => {
            const c = r.querySelector('.qv-product-currency')?.value; if (c) curs.add(c);
        });
        const saleSel = document.getElementById('qc-currency');
        const sumSel = document.getElementById('qv-summary-currency');
        // Tek para birimi + kullanıcı elle seçmediyse → o birime geç
        if (curs.size === 1 && !_qcCurrencyManual && saleSel) {
            const only = [...curs][0];
            if (saleSel.value !== only && [...saleSel.options].some(o => o.value === only)) saleSel.value = only;
        }
        // Karışık uyarısı
        const warn = document.getElementById('qv-summary-mixed');
        if (warn) warn.style.display = curs.size > 1 ? '' : 'none';
        // Özet select'i satış dövizi ile eşitle
        if (sumSel && saleSel && sumSel.value !== saleSel.value && [...sumSel.options].some(o => o.value === saleSel.value)) sumSel.value = saleSel.value;
    }

    function calculateQvProductTotals() {
        qcAutoFollowCurrency();
        let subtotal = 0, taxTotal = 0, grand = 0;
        const saleCurrency = document.getElementById('qc-currency').value || 'TRY';
        const currencySymbols = window.currencySymbols || {};

        document.querySelectorAll('#qv-products-tbody .qv-product-row').forEach(row => {
            const qty  = parseFloat(row.querySelector('.qv-product-qty').value) || 0;
            const price= parseFloat(row.querySelector('.qv-product-price').value) || 0;
            const tax  = parseFloat(row.querySelector('.qv-product-tax').value) || 0;
            const rowCurrency = row.querySelector('.qv-product-currency').value || 'TRY';

            const rs   = qty * price;
            const rt   = rs * (tax / 100);
            const rt2  = rs + rt;

            subtotal += convertAmount(rs, rowCurrency, saleCurrency);
            taxTotal += convertAmount(rt, rowCurrency, saleCurrency);
            grand += convertAmount(rt2, rowCurrency, saleCurrency);

            const rowSymbol = currencySymbols[rowCurrency] || rowCurrency;
            row.querySelector('.qv-row-tax-amount').textContent = rowSymbol + rt.toLocaleString('tr-TR',{minimumFractionDigits:2,maximumFractionDigits:2});
            row.querySelector('.qv-row-total-price').textContent= rowSymbol + rt2.toLocaleString('tr-TR',{minimumFractionDigits:2,maximumFractionDigits:2});
        });

        const saleSymbol = currencySymbols[saleCurrency] || saleCurrency;
        const fmt = v => saleSymbol + v.toLocaleString('tr-TR',{minimumFractionDigits:2,maximumFractionDigits:2});
        document.getElementById('qv-summary-subtotal').textContent = fmt(subtotal);
        document.getElementById('qv-summary-tax').textContent      = fmt(taxTotal);
        document.getElementById('qv-summary-total').textContent    = fmt(grand);

        // "Toplamı Güncelle"ye basmadan Genel toplam + üst metrikler canlı güncellensin
        // (kullanıcı toplamı elle girdiyse korunur — auto=true)
        qcSyncProductTotals(true, true);
    }

    // ─── SUBMIT ──────────────────────────────────────────────────────────────────
    function submitQuickCreate() {
        const customerId = document.getElementById('qc-customer-id').value;
        const startDate  = document.getElementById('qc-start-date').value;
        const totalAmt   = document.getElementById('qc-total-amount').value;
        const adults     = document.getElementById('qc-adult').value;

        if (!customerId) {
            Swal.fire({icon:'warning', title:'Uyarı', text:'Lütfen bir müşteri seçin.'}); return;
        }
        if (!startDate) {
            Swal.fire({icon:'warning', title:'Uyarı', text:'Başlangıç tarihi zorunludur.'}); return;
        }

        // Collect products
        const items = [];
        document.querySelectorAll('#qv-products-tbody .qv-product-row').forEach(row => {
            const name = row.querySelector('.qv-product-name').value.trim();
            if (!name) return;
            items.push({
                product_id    : row.querySelector('.row-product-id').value || null,
                itemable_type : row.querySelector('.row-itemable-type')?.value || null,
                itemable_id   : row.querySelector('.row-itemable-id')?.value || null,
                name          : name,
                quantity      : parseFloat(row.querySelector('.qv-product-qty').value) || 1,
                unit_price    : parseFloat(row.querySelector('.qv-product-price').value) || 0,
                tax_rate      : parseFloat(row.querySelector('.qv-product-tax').value) || 0,
                currency      : row.querySelector('.qv-product-currency').value
            });
        });

        const payload = {
            _token          : '{{ csrf_token() }}',
            customer_id     : customerId,
            title           : document.getElementById('qc-title').value || null,
            start_date      : startDate,
            end_date        : document.getElementById('qc-end-date').value || null,
            product_type_id : document.getElementById('qc-product-type').value || null,
            product_id      : document.getElementById('qc-product-id').value || null,
            tour_date_id    : document.getElementById('qc-tour-date-id').value || null,
            assigned_to     : document.getElementById('qc-agent').value || null,
            adult_count     : adults || 1,
            child_count     : document.getElementById('qc-child').value || 0,
            infant_count    : document.getElementById('qc-infant').value || 0,
            total_amount    : totalAmt || 0,
            paid_amount     : document.getElementById('qc-paid-amount').value || 0,
            currency        : document.getElementById('qc-currency').value,
            payment_status  : document.getElementById('qc-payment-status').value,
            status          : document.getElementById('qc-status-value').value,
            pickup_location : document.getElementById('qc-pickup').value || null,
            flight_number   : document.getElementById('qc-flight').value || null,
            customer_note   : document.getElementById('qc-customer-note').value || null,
            internal_note   : document.getElementById('qc-internal-note').value || null,
            items           : items
        };

        const btn = document.getElementById('qc-submit-btn');
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Kaydediliyor...';

        fetch('{{ route("agency.sales.store") }}', {
            method : 'POST',
            headers: { 'Content-Type':'application/json', 'Accept':'application/json', 'X-CSRF-TOKEN':'{{ csrf_token() }}' },
            body   : JSON.stringify(payload)
        })
        .then(r => r.json())
        .then(d => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-save me-2"></i>Satışı Oluştur';

            if (d.success && d.sale_id) {
                // Close create drawer and open the new sale's quick-view
                closeQuickView();
                if (typeof openSaleDrawer === 'function') {
                    openSaleDrawer(d.sale_id);
                } else if (typeof openQuickView === 'function') {
                    openQuickView(`/agency/sales/${d.sale_id}/quick-view`);
                }
                Swal.fire({
                    icon: 'success',
                    title: 'Satış Oluşturuldu!',
                    text: `Rezervasyon başarıyla kaydedildi.`,
                    timer: 2000,
                    showConfirmButton: false
                });
            } else {
                let msg = 'Satış kaydedilirken bir hata oluştu.';
                if (d.errors) msg = Object.values(d.errors).flat().join('<br>');
                else if (d.message) msg = d.message;
                Swal.fire({icon:'error', title:'Hata', html: msg});
            }
        })
        .catch(err => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-save me-2"></i>Satışı Oluştur';
            console.error(err);
            Swal.fire({icon:'error', title:'Hata', text:'Sunucu ile bağlantı kurulamadı.'});
        });
    }

    // Mevcut satışın kalemlerini yükle + metrikleri/toplamları hesapla
    var _qcInitItems = @json($saleItems);
    setTimeout(() => {
        const tbody = document.getElementById('qv-products-tbody');
        if (tbody && _qcInitItems.length) {
            _qcInitItems.forEach(it => {
                const row = addBlankQvProductRow({ name: it.name, qty: it.quantity, price: it.unit_price, currency: it.currency, productId: it.product_id, tax: it.tax_rate, tourLine: !!it.tour_line });
                if (row) {
                    if (it.itemable_type) row.querySelector('.row-itemable-type').value = it.itemable_type;
                    if (it.itemable_id) row.querySelector('.row-itemable-id').value = it.itemable_id;
                }
            });
            calculateQvProductTotals();
        } else if (tbody && tbody.querySelectorAll('.qv-product-row').length === 0) {
            addBlankQvProductRow();
        }
        if (typeof qcUpdateMetrics === 'function') qcUpdateMetrics();
    }, 300);
</script>
