@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');
@endphp

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

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

    {{-- ═══ HEADER ═══ --}}
    <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">Yeni Satış Oluştur</h3>
                <div class="sqv-subtitle">
                    <span class="sqv-code">— YENİ REZERVASYON —</span>
                    <span class="sqv-dot">•</span>
                    <span id="qc-customer-label"><i class="fas fa-user me-1"></i>Müşteri seçin</span>
                </div>
            </div>
        </div>
        <div class="sqv-header-right">
            <button class="qv-action-btn qv-close" onclick="closeQuickView()" title="Kapat"><i class="fas fa-times"></i></button>
        </div>
    </div>

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

    {{-- ═══ METRICS BAR ═══ --}}
    <div class="sqv-metrics-bar">
        <div class="sqv-metric-item">
            <span class="sqv-metric-label">TOPLAM</span>
            <span class="sqv-metric-val" id="qc-metric-total">₺0,00</span>
        </div>
        <div class="sqv-metric-divider"></div>
        <div class="sqv-metric-item">
            <span class="sqv-metric-label">ÖDENEN</span>
            <span class="sqv-metric-val text-success" id="qc-metric-paid">₺0,00</span>
        </div>
        <div class="sqv-metric-divider"></div>
        <div class="sqv-metric-item">
            <span class="sqv-metric-label">KALAN</span>
            <span class="sqv-metric-val text-danger" id="qc-metric-remaining">₺0,00</span>
        </div>
        <div class="sqv-metric-divider"></div>
        <div class="sqv-metric-item">
            <span class="sqv-metric-label">KİŞİ</span>
            <span class="sqv-metric-val" id="qc-metric-people">1</span>
        </div>
        <div class="sqv-metric-divider"></div>
        <div class="sqv-metric-item">
            <span class="sqv-metric-label">DURUM</span>
            <span class="sqv-metric-val" style="font-size:0.78rem;" id="qc-metric-status">Potansiyel</span>
        </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="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</h6>
                                <button type="button" class="btn btn-sm btn-outline-primary py-1 px-2 border-0"
                                    onclick="qcToggleCustomerForm()"
                                    style="font-size:0.72rem; border-radius:6px; font-weight:700;">
                                    <i class="fas fa-plus me-1"></i> Yeni Müşteri
                                </button>
                            </div>

                            {{-- Quick customer form --}}
                            <div id="qc-quick-customer-form" class="bg-light p-3 rounded mb-3 d-none" style="border:1px dashed #cbd5e1; border-radius:12px !important;">
                                <div class="row g-2">
                                    <div class="col-6">
                                        <label class="form-label" style="font-size:0.7rem;font-weight:700;color:#475569;text-transform:uppercase;">Adı *</label>
                                        <input type="text" id="qc_new_first_name" class="form-control form-control-sm" style="border-radius:8px;">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label" style="font-size:0.7rem;font-weight:700;color:#475569;text-transform:uppercase;">Soyadı *</label>
                                        <input type="text" id="qc_new_last_name" class="form-control form-control-sm" style="border-radius:8px;">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label" style="font-size:0.7rem;font-weight:700;color:#475569;text-transform:uppercase;">Telefon</label>
                                        <input type="text" id="qc_new_phone" class="form-control form-control-sm" style="border-radius:8px;">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label" style="font-size:0.7rem;font-weight:700;color:#475569;text-transform:uppercase;">E-Posta</label>
                                        <input type="email" id="qc_new_email" class="form-control form-control-sm" style="border-radius:8px;">
                                    </div>
                                    <div class="col-12 d-flex justify-content-end gap-2 mt-1">
                                        <button type="button" class="btn btn-sm btn-light" onclick="qcToggleCustomerForm()" style="border-radius:6px;font-size:0.72rem;font-weight:600;">İptal</button>
                                        <button type="button" class="btn btn-sm btn-primary" onclick="qcSaveQuickCustomer()" style="border-radius:6px;font-size:0.72rem;font-weight:700;">Kaydet ve Seç</button>
                                    </div>
                                </div>
                            </div>

                            <div>
                                <label class="sqv-form-label">Müşteri Seçin *</label>
                                <select id="qc-customer-select" class="form-select qc-form-select" required onchange="qcOnCustomerChange(this)">
                                    <option value="">— Müşteri Seçin —</option>
                                    @foreach($customers as $c)
                                        <option value="{{ $c->id }}">{{ $c->full_name }} ({{ $c->phone ?? ($c->emails[0] ?? 'İletişim Yok') }})</option>
                                    @endforeach
                                </select>
                            </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ış / Fırsat Başlığı</label>
                                    <input type="text" id="qc-title" class="form-control qc-form-control"
                                        placeholder="Örn: Kapadokya Balon Turu Satışı"
                                        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="{{ 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">
                                </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 }}">{{ $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 }}" {{ Auth::id() == $agent->id ? 'selected' : '' }}>{{ $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...">
                                </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...">
                                </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>
                                <textarea id="qc-customer-note" class="form-control border p-2 mt-1" rows="2"
                                    placeholder="Müşteriye iletilecek notlar..."
                                    style="font-size:0.85rem;background:#fafafa;border-radius:12px;resize:none;"></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>
                                <textarea id="qc-internal-note" class="form-control border p-2 mt-1" rows="2"
                                    placeholder="Sadece çalışanlar görebilir..."
                                    style="font-size:0.85rem;background:#fafafa;border-radius:12px;resize:none;"></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="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="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="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;"
                                        oninput="qcUpdateMetrics()">
                                </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="calculateQvProductTotals(); qcUpdateMetrics();">
                                        @foreach($activeCurrencies as $curr)
                                            <option value="{{ $curr->code }}">{{ $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="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">Ödenmedi</option>
                                        <option value="partial">Kısmi Ödeme</option>
                                        <option value="paid">Ödendi</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        {{-- KAYDET BUTTON --}}
                        <div class="d-grid gap-2">
                            <button type="button" id="qc-submit-btn" onclick="submitQuickCreate()"
                                class="btn btn-lg text-white fw-bold"
                                style="background:linear-gradient(135deg,#2563eb,#1e40af);border:none;border-radius:14px;font-size:0.95rem;padding:0.85rem;box-shadow:0 6px 20px rgba(37,99,235,0.35);transition:all 0.2s;">
                                <i class="fas fa-save me-2"></i>Satışı Oluştur
                            </button>
                            <button type="button" onclick="closeQuickView()"
                                class="btn btn-outline-secondary fw-bold"
                                style="border-radius:12px;font-size:0.85rem;">
                                İptal
                            </button>
                        </div>

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

        {{-- ─────────────────────── TAB: ÜRÜNLER ─────────────────────── --}}
        <div id="qv-tab-qcproducts" class="qv-tab-panel">
            <div class="p-4">
                <div class="d-flex justify-content-between align-items-center mb-4 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>Ürün Kataloğu & 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-th-large me-1 text-indigo"></i>veya <strong>Katalog</strong> butonuyla kayıtlı ürünlerinizden seçin
                        </p>
                    </div>
                    <div class="d-flex gap-2">
                        <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 Ekle
                        </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>

                <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>
                                    Ürün eklenmedi. "Satır Ekle" ile başlayın.
                                </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 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>

    {{-- ═══ PRODUCT CATALOG MODAL ═══ --}}
    <div class="modal fade" id="qvProductCatalogModal" tabindex="-1" aria-labelledby="qvProductCatalogModalLabel" aria-hidden="true" style="z-index:1065;">
        <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content" style="border-radius:20px;border:none;box-shadow:0 25px 60px rgba(0,0,0,0.18);overflow:hidden;">
                <div class="modal-header border-0 pb-0" style="background:linear-gradient(135deg,#1e293b 0%,#0f172a 100%);padding:1.5rem 1.75rem 1rem;">
                    <div class="d-flex align-items-center gap-3 flex-grow-1">
                        <div style="width:42px;height:42px;background:rgba(99,102,241,0.2);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                            <i class="fas fa-th-large" style="color:#818cf8;font-size:1.1rem;"></i>
                        </div>
                        <div>
                            <h5 class="modal-title mb-0" id="qvProductCatalogModalLabel" style="color:#fff;font-weight:800;font-size:1.05rem;">Ürün Kataloğu</h5>
                            <p class="mb-0" style="color:#94a3b8;font-size:0.72rem;margin-top:2px;">Kayıtlı ürün veya hizmetlerinizden seçin</p>
                        </div>
                    </div>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="border-0" style="background:linear-gradient(135deg,#1e293b 0%,#0f172a 100%);padding:0.75rem 1.75rem 1.25rem;">
                    <div class="d-flex gap-2">
                        <div class="position-relative flex-grow-1">
                            <i class="fas fa-search position-absolute" style="left:12px;top:50%;transform:translateY(-50%);color:#94a3b8;font-size:0.85rem;pointer-events:none;"></i>
                            <input type="text" id="catalogSearchInput" class="form-control" placeholder="Ürün adı ile ara..." oninput="filterCatalogProducts()" style="border-radius:12px;padding-left:36px;background:rgba(255,255,255,0.08);border:1px solid rgba(255,255,255,0.12);color:#fff;font-size:0.88rem;">
                        </div>
                        <select id="catalogTypeFilter" class="form-select" onchange="filterCatalogProducts()" style="max-width:180px;border-radius:12px;background:rgba(255,255,255,0.08);border:1px solid rgba(255,255,255,0.12);color:#fff;font-size:0.82rem;">
                            <option value="">Tüm Tipler</option>
                            @foreach($products->pluck('productType')->filter()->unique('id') as $pt)
                                <option value="{{ $pt->id }}">{{ $pt->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="modal-body p-0" style="background:#f8fafc;max-height:480px;overflow-y:auto;">
                    <div id="catalogProductGrid" class="p-3">
                        @forelse($productsByType as $typeName => $typeProducts)
                            <div class="catalog-type-group mb-4" data-type-name="{{ $typeName }}">
                                <div class="d-flex align-items-center gap-2 mb-2" style="padding:0 4px;">
                                    <span class="catalog-type-badge" style="font-size:0.68rem;font-weight:800;text-transform:uppercase;letter-spacing:0.06em;color:#6366f1;background:#ede9fe;padding:3px 10px;border-radius:20px;">{{ $typeName }}</span>
                                    <div style="flex:1;height:1px;background:#e2e8f0;"></div>
                                </div>
                                <div class="row g-2">
                                    @foreach($typeProducts as $p)
                                        <div class="col-md-6 catalog-product-item"
                                             data-name="{{ strtolower($p->name) }}"
                                             data-type-id="{{ $p->productType?->id }}"
                                             data-id="{{ $p->id }}"
                                             data-price="{{ $p->base_price }}"
                                             data-currency="{{ $p->currency }}">
                                            <div class="catalog-product-card" onclick="selectFromCatalog({{ $p->id }}, '{{ addslashes($p->name) }}', {{ $p->base_price ?? 0 }}, '{{ $p->currency }}')">
                                                <div class="d-flex align-items-start gap-3">
                                                    <div class="catalog-product-icon">
                                                        <i class="fas {{ $p->productType?->icon ?? 'fa-box' }}"></i>
                                                    </div>
                                                    <div class="flex-grow-1 min-width-0">
                                                        <div class="catalog-product-name">{{ $p->name }}</div>
                                                    </div>
                                                    <div class="text-end flex-shrink-0">
                                                        @if($p->base_price)
                                                            <div class="catalog-product-price">{{ number_format($p->base_price, 0, ',', '.') }} {{ $p->currency }}</div>
                                                        @else
                                                            <div class="catalog-product-price text-muted" style="font-size:0.72rem;">Fiyat Yok</div>
                                                        @endif
                                                        <div class="catalog-product-select-btn">Seç <i class="fas fa-arrow-right ms-1" style="font-size:0.65rem;"></i></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @empty
                            <div class="text-center py-5">
                                <i class="fas fa-box-open text-muted mb-3" style="font-size:2.5rem;opacity:0.4;"></i>
                                <p class="text-muted">Tanımlı ürün bulunamadı.</p>
                            </div>
                        @endforelse
                        <div id="catalogNoResults" class="text-center py-5 d-none">
                            <i class="fas fa-search text-muted mb-3" style="font-size:2rem;opacity:0.3;"></i>
                            <p class="text-muted fw-semibold">Arama kriterlerine uygun ürün bulunamadı.</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0" style="background:#f8fafc;padding:0.75rem 1.25rem;">
                    <p class="text-muted small mb-0 me-auto"><i class="fas fa-info-circle me-1"></i> Seçim yapmadan tabloya da direkt yazabilirsiniz.</p>
                    <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal" style="border-radius:10px;font-weight:600;">Kapat</button>
                </div>
            </div>
        </div>
    </div>

</x-quick-view.layout>

{{-- ═══ CSS ═══ --}}
<style>
    /* ═══ HEADER ═══ */
    .sqv-header{display:flex;align-items:center;justify-content:space-between;padding:1.5rem 2rem;background:linear-gradient(135deg,#0f172a 0%,#1e293b 100%);flex-shrink:0;gap:1rem;position:relative;overflow:hidden;}
    .sqv-header::before{content:'';position:absolute;top:-50%;right:-20%;width:300px;height:300px;background:radial-gradient(circle,rgba(99,102,241,0.15) 0%,transparent 70%);pointer-events:none;}
    .sqv-header-left{display:flex;align-items:center;gap:1rem;flex:1;min-width:0;}
    .sqv-icon{width:52px;height:52px;border-radius:16px;display:flex;align-items:center;justify-content:center;font-size:1.3rem;flex-shrink:0;background:rgba(255,255,255,0.1)!important;color:#fff!important;backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,0.15);}
    .sqv-title-group{min-width:0;}
    .sqv-title{font-size:1.35rem;font-weight:800;color:#fff;letter-spacing:-0.03em;margin:0;line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
    .sqv-subtitle{display:flex;align-items:center;gap:0.5rem;font-size:0.78rem;color:rgba(255,255,255,0.5);flex-wrap:wrap;margin-top:4px;}
    .sqv-code{font-weight:700;color:rgba(255,255,255,0.4);font-size:0.7rem;background:rgba(255,255,255,0.08);padding:2px 8px;border-radius:6px;font-family:monospace;}
    .sqv-dot{color:rgba(255,255,255,0.2);}
    .sqv-header-right{display:flex;align-items:center;gap:0.5rem;flex-shrink:0;}
    .qv-sales-wrapper .qv-action-btn{background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);color:rgba(255,255,255,0.5);}
    .qv-sales-wrapper .qv-action-btn:hover{background:rgba(255,255,255,0.12);color:#fff;}
    .qv-sales-wrapper .qv-action-btn.qv-close:hover{background:rgba(239,68,68,0.2);color:#f87171;border-color:rgba(239,68,68,0.3);}

    /* ═══ PIPELINE ═══ */
    .sqv-pipeline-wrap{background:#f8fafc;border-bottom:1px solid #e2e8f0;padding:0.6rem 1.5rem;flex-shrink:0;}
    .sqv-pipeline{display:flex;gap:5px;width:100%;}
    .sqv-seg{flex:1;display:flex;align-items:center;justify-content:center;padding:0.55rem 0.5rem;border-radius:10px;cursor:pointer;transition:all .3s cubic-bezier(.4,0,.2,1);position:relative;min-height:38px;border:1.5px solid transparent;overflow:hidden;}
    .sqv-seg::before{content:'';position:absolute;inset:0;opacity:0;transition:opacity .3s;background:linear-gradient(180deg,rgba(255,255,255,0.3),transparent);pointer-events:none;}
    .sqv-seg:hover::before{opacity:1;}
    .sqv-seg-label{font-size:0.68rem;font-weight:700;white-space:nowrap;letter-spacing:0.02em;position:relative;z-index:1;}
    .sqv-seg.done{background:linear-gradient(135deg,#818cf8,#6366f1);border-color:#6366f1;}
    .sqv-seg.done .sqv-seg-label{color:#fff;}
    .sqv-seg.done:hover{transform:translateY(-2px);box-shadow:0 6px 20px rgba(99,102,241,0.35);}
    .sqv-seg.current{background:linear-gradient(135deg,#34d399,#10b981);border-color:#059669;box-shadow:0 0 0 3px rgba(16,185,129,0.15);}
    .sqv-seg.current .sqv-seg-label{color:#fff;font-weight:800;text-shadow:0 1px 2px rgba(0,0,0,0.1);}
    .sqv-seg.current:hover{transform:translateY(-2px);box-shadow:0 6px 20px rgba(16,185,129,0.35);}
    .sqv-seg.future{background:rgba(241,245,249,0.8);border-color:#e2e8f0;}
    .sqv-seg.future .sqv-seg-label{color:#94a3b8;}
    .sqv-seg.future:hover{background:#e2e8f0;border-color:#cbd5e1;transform:translateY(-2px);}

    /* ═══ METRICS ═══ */
    .sqv-metrics-bar{display:flex;align-items:stretch;justify-content:center;gap:0;padding:0;background:#fff;border-bottom:1px solid #e2e8f0;flex-shrink:0;}
    .sqv-metric-item{flex:1;text-align:center;padding:0.85rem 0.5rem;display:flex;flex-direction:column;justify-content:center;gap:4px;}
    .sqv-metric-label{font-size:0.62rem;font-weight:800;color:#94a3b8;text-transform:uppercase;letter-spacing:0.06em;}
    .sqv-metric-val{font-size:1.05rem;font-weight:800;color:#1e293b;letter-spacing:-0.02em;}
    .sqv-metric-divider{width:1px;background:#f1f5f9;margin:0.5rem 0;flex-shrink:0;}

    /* ═══ 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);}

    /* ═══ CATALOG ═══ */
    .catalog-product-card{background:#fff;border:1.5px solid #e2e8f0;border-radius:14px;padding:1rem;cursor:pointer;transition:all 0.2s;height:100%;}
    .catalog-product-card:hover{border-color:#6366f1;box-shadow:0 4px 16px rgba(99,102,241,0.12);transform:translateY(-2px);}
    .catalog-product-icon{width:38px;height:38px;background:#ede9fe;border-radius:10px;display:flex;align-items:center;justify-content:center;color:#6366f1;font-size:1rem;flex-shrink:0;}
    .catalog-product-name{font-weight:700;font-size:0.88rem;color:#1e293b;}
    .catalog-product-price{font-weight:800;font-size:0.9rem;color:#1e293b;}
    .catalog-product-select-btn{font-size:0.68rem;font-weight:700;color:#6366f1;margin-top:4px;}
</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
    };
    // ─── STATUS PIPELINE ────────────────────────────────────────────────────────
    const 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');
        });
    }

    // ─── 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 currencySymbols = { 'TRY': '₺', 'USD': '$', 'EUR': '€' };
        const saleSymbol = currencySymbols[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
    function qcSyncProductTotals() {
        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);
        qcUpdateMetrics();
        // Give user feedback
        if (typeof Swal !== 'undefined') {
            Swal.fire({ icon:'success', title:'Toplam Güncellendi', text:'Ürün toplamı "Genel" sekmesine aktarıldı.', timer:1500, showConfirmButton:false });
        }
    }

    // ─── CUSTOMER ────────────────────────────────────────────────────────────────
    function qcToggleCustomerForm() {
        const f = document.getElementById('qc-quick-customer-form');
        f.classList.toggle('d-none');
        if (!f.classList.contains('d-none')) document.getElementById('qc_new_first_name').focus();
    }

    function qcOnCustomerChange(sel) {
        const opt  = sel.options[sel.selectedIndex];
        const lbl  = document.getElementById('qc-customer-label');
        if (opt.value) {
            lbl.innerHTML = `<i class="fas fa-user me-1"></i>${opt.textContent.split('(')[0].trim()}`;
        } else {
            lbl.innerHTML = `<i class="fas fa-user me-1"></i>Müşteri seçin`;
        }
    }

    function qcUpdateHeaderSubtitle() {
        // already handled by qcOnCustomerChange; title appears in header only if needed
    }

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

        if (!first || !last) {
            Swal.fire({icon:'warning', title:'Uyarı', text:'Ad ve soyad zorunludur.'});
            return;
        }

        fetch('{{ route("agency.sales.api.quick-customer") }}', {
            method: 'POST',
            headers: {'Content-Type':'application/json','Accept':'application/json'},
            body: JSON.stringify({ first_name:first, last_name:last, phone, email, _token:'{{ csrf_token() }}' })
        })
        .then(r => r.json())
        .then(d => {
            if (d.success && d.customer) {
                const sel = document.getElementById('qc-customer-select');
                const opt = document.createElement('option');
                opt.value       = d.customer.id;
                opt.textContent = d.customer.full_name + ' (' + (d.customer.phone || d.customer.email || 'İletişim Yok') + ')';
                opt.selected    = true;
                sel.appendChild(opt);
                qcOnCustomerChange(sel);
                qcToggleCustomerForm();
                Swal.fire({icon:'success', title:'Başarılı', text:'Müşteri oluşturuldu ve seçildi.', timer:1500, showConfirmButton:false});
            } else {
                alert(d.message || 'Müşteri eklenirken hata oluştu.');
            }
        })
        .catch(() => alert('Sunucu hatası oluştu.'));
    }

    // ─── PRODUCT TABLE (same as quick-view) ──────────────────────────────────────
    let _catalogTargetRow = null;

    function openProductCatalog(row) {
        _catalogTargetRow = row;
        const si = document.getElementById('catalogSearchInput');
        const tf = document.getElementById('catalogTypeFilter');
        if (si) si.value = '';
        if (tf) tf.value = '';
        filterCatalogProducts();
        new bootstrap.Modal(document.getElementById('qvProductCatalogModal'), {backdrop:true}).show();
    }

    function filterCatalogProducts() {
        const q  = (document.getElementById('catalogSearchInput')?.value || '').toLowerCase().trim();
        const ti = document.getElementById('catalogTypeFilter')?.value || '';
        let vis  = 0;
        document.querySelectorAll('.catalog-product-item').forEach(item => {
            const nm  = item.dataset.name || '';
            const tid = item.dataset.typeId || '';
            const show = (!q || nm.includes(q)) && (!ti || tid === ti);
            item.style.display = show ? '' : 'none';
            if (show) vis++;
        });
        document.querySelectorAll('.catalog-type-group').forEach(g => {
            g.style.display = g.querySelectorAll('.catalog-product-item:not([style*="none"])').length ? '' : 'none';
        });
        const nr = document.getElementById('catalogNoResults');
        if (nr) nr.classList.toggle('d-none', vis > 0);
    }

    function selectFromCatalog(id, name, price, currency) {
        if (!_catalogTargetRow) return;
        _catalogTargetRow.querySelector('.row-product-id').value = id;
        _catalogTargetRow.querySelector('.qv-product-name').value = name;
        _catalogTargetRow.querySelector('.qv-product-price').value = price;
        const ce = _catalogTargetRow.querySelector('.qv-product-currency');
        if (ce) ce.value = currency;
        calculateQvProductTotals();
        bootstrap.Modal.getInstance(document.getElementById('qvProductCatalogModal'))?.hide();
        _catalogTargetRow = null;
    }

    function addBlankQvProductRow() {
        const tbody = document.getElementById('qv-products-tbody');
        if (!tbody) return;
        const emptyRow = document.getElementById('qv-no-products-row');
        if (emptyRow) emptyRow.remove();
        const tr = document.createElement('tr');
        tr.className = 'qv-product-row';
        tr.innerHTML = `
            <input type="hidden" class="row-id" value="">
            <input type="hidden" class="row-product-id" value="">
            <td>
                <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">
                    <button type="button" class="btn-catalog-pick" onclick="openProductCatalog(this.closest('.qv-product-row'))" title="Katalogdan seç">
                        <i class="fas fa-th-large"></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()">
                    <option value="0">%0</option>
                    <option value="1">%1</option>
                    <option value="10">%10</option>
                    <option value="20" selected>%20</option>
                </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);
        tr.querySelector('.qv-product-name').focus();
    }

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

    function convertAmount(amount, fromCurr, toCurr) {
        if (fromCurr === toCurr) return amount;
        const rates = window.exchangeRates || { 'USD': 1, 'EUR': 1 };
        const usdRate = parseFloat(rates.USD) || 1;
        const eurRate = parseFloat(rates.EUR) || 1;

        let amountInTry = amount;
        if (fromCurr === 'USD') {
            amountInTry = amount * usdRate;
        } else if (fromCurr === 'EUR') {
            amountInTry = amount * eurRate;
        }

        if (toCurr === 'TRY') {
            return amountInTry;
        } else if (toCurr === 'USD') {
            return amountInTry / usdRate;
        } else if (toCurr === 'EUR') {
            return amountInTry / eurRate;
        }
        return amountInTry;
    }

    function calculateQvProductTotals() {
        let subtotal = 0, taxTotal = 0, grand = 0;
        const saleCurrency = document.getElementById('qc-currency').value || 'TRY';
        const currencySymbols = { 'TRY': '₺', 'USD': '$', 'EUR': '€' };

        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] || '₺';
            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] || '₺';
        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);
    }

    // ─── SUBMIT ──────────────────────────────────────────────────────────────────
    function submitQuickCreate() {
        const customerId = document.getElementById('qc-customer-select').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,
                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,
            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
                }).then(() => location.reload());
            } 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ı.'});
        });
    }

    // Ensure we have at least one blank row when loading if table is empty
    setTimeout(() => {
        const tbody = document.getElementById('qv-products-tbody');
        if (tbody && tbody.querySelectorAll('.qv-product-row').length === 0) {
            addBlankQvProductRow();
        }
    }, 400);
</script>
