{{-- Kültür/Yurtdışı turu tarih formu alanları (ekle/düzenle ortak) — SADE DEFTER DÜZENİ.

     Her alan tek satır (etiket + kompakt kontrol), bölümler ince başlıklarla
     ayrılır; sık kullanılanlar açık, nadir kullanılanlar katlanır. Görünüm
     _qv-date-form-ui'de; alan adları ve JS kancaları (data-qd-*) DEĞİŞMEDİ.

     Opsiyonel: $d (TourDate|null), $copyDates (Collection), $suggestStart, $suggestEnd --}}
@php
    $d = $d ?? null;
    $copyDates = $copyDates ?? collect();
    $suggestStart = $suggestStart ?? null;
    $suggestEnd = $suggestEnd ?? null;
    $startVal = $d && $d->start_date ? \Carbon\Carbon::parse($d->start_date)->format('Y-m-d') : ($suggestStart ?? '');
    $endVal = $d && $d->end_date ? \Carbon\Carbon::parse($d->end_date)->format('Y-m-d') : ($suggestEnd ?? '');
    // Tarih-seviyesi (pazaryeri-dışı) kopyalanabilir alanlar
    $priceFields = ['room_capacity','child_min_age','child_max_age','infant_min_age','infant_max_age','early_booking_discount','last_minute_discount','group_discount','special_discount','min_group_size','discount_reason'];

    // Pazaryeri fiyat matrisi alanları — etiketler TEK kaynaktan (App\Support\TourFareCatalog).
    // Bebek kabul edilmiyorsa bebek fiyatı hiç sorulmaz (forTour bunu eler).
    $mpFields = collect(\App\Support\TourFareCatalog::forTour((bool) $tour->infant_allowed))
        ->map(fn ($f) => ['key' => $f['column'], 'label' => $f['label'], 'short' => $f['short']])->all();
    $mpList = $tour->product?->marketplaces ?? collect();
    // Mevcut fiyatlar: [marketplace_id][classKey] => satır
    $mpExisting = [];
    if ($d) {
        foreach ($d->marketplacePrices as $mpp) {
            $ck = $mpp->tour_class_id ?? 'none';
            $mpExisting[$mpp->marketplace_id][$ck] = $mpp;
        }
    }
    $mpClasses = $pricingClasses ?? collect();
    $mpUseClasses = (bool) ($tour->use_pricing_classes ?? false);
    // Seri üretim yalnızca yeni tarih eklerken anlamlı (statik dates.blade ile aynı kural).
    $isNew = !$d;

    // ── Yaş aralıkları: yeni tarihte turun genel ayarından otomatik çekilir ──
    $ageFields = ['child_min_age', 'child_max_age', 'infant_min_age', 'infant_max_age'];
    $ageVals = [];
    foreach ($ageFields as $af) {
        $ageVals[$af] = $d ? $d->{$af} : ($tour->{$af} ?? null);
    }
    $agesEmpty = collect($ageVals)->every(fn ($v) => $v === null);
    $agesMatchTour = collect($ageFields)->every(fn ($af) => (string) ($ageVals[$af] ?? '') === (string) ($tour->{$af} ?? ''));
    $fmtAge = fn ($min, $max) => ($min === null && $max === null) ? '—' : (($min ?? '?') . '–' . ($max ?? '?') . ' yaş');
    $ageSummary = 'Çocuk ' . $fmtAge($ageVals['child_min_age'], $ageVals['child_max_age'])
        . ($tour->infant_allowed ? ' · Bebek ' . $fmtAge($ageVals['infant_min_age'], $ageVals['infant_max_age']) : '');
    $ageChip = $agesEmpty ? ['Tanımsız', 'empty'] : ($agesMatchTour ? ['Turun genel ayarı', 'auto'] : ['Bu tarihe özel', 'custom']);

    $cppOn = (bool) ($d?->use_custom_payment_plan);
    $stages = is_array($d?->payment_schedule ?? null) ? $d->payment_schedule : [];
    $stageTriggers = ['at_booking' => 'Rezervasyonda', 'days_before_departure' => 'Kalkıştan X gün önce', 'on_departure' => 'Kalkışta'];

    // Katlanır bölümlerin kapalı başlık özetleri
    $discFields = ['early_booking_discount' => 'Erken', 'last_minute_discount' => 'Son dakika', 'group_discount' => 'Grup', 'special_discount' => 'Özel'];
    $discParts = [];
    foreach ($discFields as $df => $dl) {
        if ($d && $d->$df !== null && (float) $d->$df > 0) $discParts[] = $dl . ' %' . rtrim(rtrim(number_format((float) $d->$df, 2, ',', ''), '0'), ',');
    }
    $discSummary = $discParts ? implode(' · ', $discParts) : 'İndirim tanımlanmadı';

    $ruleNames = ['early_booking_rule' => 'Erken rez.', 'last_minute_rule' => 'Son dakika', 'booking_deadline_rule' => 'Son rezervasyon'];
    $ruleParts = [];
    foreach ($ruleNames as $rn => $rl) {
        $rv = $d?->$rn;
        if (is_array($rv) && !empty($rv['mode'])) $ruleParts[] = $rl;
    }
    $ruleSummary = $ruleParts ? implode(' · ', $ruleParts) . ' tanımlı' : 'Turun genel kuralları geçerli';

    $cppSummary = $cppOn
        ? (count($stages) ? count($stages) . ' aşama tanımlı' : 'Açık — henüz aşama yok')
        : 'Turun genel ödeme planı geçerli';
@endphp

@include('agency.products._qv-date-form-ui')

<div class="qdf">

    @if($copyDates->count())
        <label class="qdf-copy">
            <i class="fas fa-wand-magic-sparkles"></i>
            <span>Başka tarihten doldur</span>
            <select data-qd-copyfrom>
                <option value="">— Tarih seçin, fiyatlar ve ayarlar kopyalansın —</option>
                @foreach($copyDates as $cd)
                    @if(!$d || $cd->id !== $d->id)
                        <option value="{{ $cd->id }}"
                                data-prices='@json(collect($priceFields)->mapWithKeys(fn ($f) => [$f => $cd->$f])->toArray())'
                                data-mp-prices='@json($cd->marketplacePrices->reduce(function ($acc, $p) use ($mpFields) { $ck = $p->tour_class_id ?? 'none'; $acc[$p->marketplace_id][$ck] = collect($mpFields)->mapWithKeys(fn ($f) => [$f['key'] => $p->{$f['key']}])->toArray(); return $acc; }, []))'>
                            #{{ $cd->code }} · {{ $cd->start_date?->format('d.m.Y') }} · {{ $cd->adult_price !== null ? number_format($cd->adult_price, 0, ',', '.') . ' ' . $cd->currency : 'fiyatsız' }}
                        </option>
                    @endif
                @endforeach
            </select>
        </label>
    @endif

    {{-- ══ TARİH ══ --}}
    <div class="qdf-fold open" data-qd-fold>
        <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="true">
            <i class="fas fa-calendar-day"></i>
            <span class="qdf-fold-t">Tarih</span>
            <span class="qdf-fold-s">Başlangıç seçilince bitiş tur süresine göre otomatik dolar</span>
            <i class="fas fa-chevron-down qdf-fold-chev"></i>
        </button>
        <div class="qdf-fold-b" data-qd-fold-body>
        <div class="qdf-rows">
            <label class="qdf-row">
                <span class="qdf-l">Başlangıç <b>*</b></span>
                <span class="qdf-v"><input type="date" name="start_date" value="{{ $startVal }}" data-qd-start required></span>
            </label>
            <label class="qdf-row">
                <span class="qdf-l">Bitiş <em>otomatik</em></span>
                <span class="qdf-v"><input type="date" name="end_date" value="{{ $endVal }}" data-qd-end required></span>
            </label>
        </div>
        </div>
    </div>

    {{-- ══ KAPASİTE ══ --}}
    <div class="qdf-fold open" data-qd-fold>
        <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="true">
            <i class="fas fa-users"></i>
            <span class="qdf-fold-t">Kapasite</span>
            <span class="qdf-fold-s">Toplam kapasite, bu tarihte satışa açılacak kişi sayısıdır</span>
            <i class="fas fa-chevron-down qdf-fold-chev"></i>
        </button>
        <div class="qdf-fold-b" data-qd-fold-body>
        <div class="qdf-rows">
            <label class="qdf-row">
                <span class="qdf-l">Toplam Kapasite <b>*</b></span>
                <span class="qdf-v"><input type="number" min="1" name="total_capacity" value="{{ $d?->total_capacity }}" placeholder="Örn. 30" required></span>
            </label>
            <label class="qdf-row">
                <span class="qdf-l">Min. Katılımcı</span>
                <span class="qdf-v"><input type="number" min="0" name="min_participants" value="{{ $d?->min_participants }}" placeholder="Kesin kalkış eşiği"></span>
            </label>
            <label class="qdf-row">
                <span class="qdf-l">Oda Kapasitesi</span>
                <span class="qdf-v"><input type="number" min="1" name="room_capacity" value="{{ $d?->room_capacity }}" placeholder="1 odada maks. kişi"></span>
            </label>
            <label class="qdf-row">
                <span class="qdf-l">Yetişkin Kont.</span>
                <span class="qdf-v"><input type="number" min="0" name="adult_capacity" value="{{ $d?->adult_capacity }}" placeholder="Sınırsız"></span>
            </label>
            <label class="qdf-row">
                <span class="qdf-l">Çocuk Kont.</span>
                <span class="qdf-v"><input type="number" min="0" name="child_capacity" value="{{ $d?->child_capacity }}" placeholder="Sınırsız"></span>
            </label>
            @if($tour->infant_allowed)
                <label class="qdf-row">
                    <span class="qdf-l">Bebek Kont.</span>
                    <span class="qdf-v"><input type="number" min="0" name="infant_capacity" value="{{ $d?->infant_capacity }}" placeholder="Sınırsız"></span>
                </label>
            @endif
        </div>
        </div>
    </div>

    {{-- ══ FİYATLAR — günübirlikteki minimal matris ══ --}}
    <div class="qdf-fold open" data-qd-fold>
        <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="true">
            <i class="fas fa-tags"></i>
            <span class="qdf-fold-t">Pazaryeri Fiyatları</span>
            <span class="qdf-fold-s">Satır: pazaryeri · Sütun: fiyat tipi</span>
            <i class="fas fa-chevron-down qdf-fold-chev"></i>
        </button>
        <div class="qdf-fold-b" data-qd-fold-body>
            @include('agency.products._qv-date-prices-mini', [
                'marketplaces' => $mpList,
                'existing' => $mpExisting,
                'fields' => $mpFields,
                'classes' => $mpClasses,
                'useClasses' => $mpUseClasses,
            ])
        </div>
    </div>

    {{-- ══ SEZON & DURUM ══ --}}
    <div class="qdf-fold open" data-qd-fold>
        <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="true">
            <i class="fas fa-toggle-on"></i>
            <span class="qdf-fold-t">Sezon &amp; Durum</span>
            <span class="qdf-fold-s">Yayın durumu, kesin kalkış ve tarihe özel not</span>
            <i class="fas fa-chevron-down qdf-fold-chev"></i>
        </button>
        <div class="qdf-fold-b" data-qd-fold-body>
        <div class="qdf-rows">
            <label class="qdf-row">
                <span class="qdf-l">Sezon</span>
                <span class="qdf-v">
                    <select name="season_type">
                        @foreach(['low' => 'Düşük', 'medium' => 'Orta', 'high' => 'Yüksek', 'peak' => 'Zirve'] as $v => $l)
                            <option value="{{ $v }}" @selected(($d->season_type ?? 'medium') === $v)>{{ $l }}</option>
                        @endforeach
                    </select>
                </span>
            </label>
            <label class="qdf-row">
                <span class="qdf-l">Durum</span>
                <span class="qdf-v">
                    <select name="status">
                        @foreach(['draft' => 'Taslak', 'published' => 'Yayında', 'booking_open' => 'Rez. Açık', 'booking_closed' => 'Rez. Kapalı', 'confirmed' => 'Onaylı', 'in_progress' => 'Devam Ediyor', 'completed' => 'Tamamlandı', 'cancelled' => 'İptal'] as $v => $l)
                            <option value="{{ $v }}" @selected(($d->status ?? 'booking_open') === $v)>{{ $l }}</option>
                        @endforeach
                    </select>
                </span>
            </label>
            <div class="qdf-row wide top">
                <span class="qdf-l">Notlar</span>
                <span class="qdf-v"><textarea name="special_notes" placeholder="Bu tarihe özel iç not">{{ $d?->special_notes }}</textarea></span>
            </div>
        </div>
        <div class="qdf-switches">
            <label class="qdf-sw"><input type="checkbox" name="is_active" value="1" {{ !$d || $d->is_active ? 'checked' : '' }}><span>Aktif</span></label>
            <label class="qdf-sw"><input type="checkbox" name="is_bookable" value="1" {{ !$d || $d->is_bookable ? 'checked' : '' }}><span>Rezervasyona Açık</span></label>
            <label class="qdf-sw"><input type="checkbox" name="guarantee_departure" value="1" {{ $d && $d->guarantee_departure ? 'checked' : '' }}><span>Kesin Kalkış</span></label>
            <label class="qdf-sw"><input type="checkbox" name="auto_guarantee_on_min" value="1" {{ $d ? ($d->auto_guarantee_on_min ? 'checked' : '') : (($tour->auto_guarantee_on_min ?? false) ? 'checked' : '') }}><span>Min. katılımcıda otomatik kesin kalkış</span></label>
        </div>
        </div>
    </div>

    {{-- ══ YAŞ ARALIKLARI (kapalı başlar) ══ --}}
    <div class="qdf-fold" data-qd-fold>
        <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="false">
            <i class="fas fa-child-reaching"></i>
            <span class="qdf-fold-t">Yaş Aralıkları</span>
            <span class="qdf-fold-s" data-qd-ages-summary>{{ $ageSummary }}</span>
            <span class="qd-fold-chip is-{{ $ageChip[1] }}" data-qd-ages-chip>{{ $ageChip[0] }}</span>
            <i class="fas fa-chevron-down qdf-fold-chev"></i>
        </button>
        <div class="qdf-fold-b" data-qd-fold-body hidden>
            <p class="qdf-hint"><i class="fas fa-circle-info"></i> Boş bırakılan alanlarda turun genel ayarı geçerlidir; buradaki değerler yalnızca bu tarihe uygulanır.</p>
            <div class="qdf-rows">
                <label class="qdf-row">
                    <span class="qdf-l">Çocuk Min Yaş</span>
                    <span class="qdf-v"><input type="number" name="child_min_age" value="{{ $ageVals['child_min_age'] }}" placeholder="{{ $tour->child_min_age ?? 2 }}" data-qd-age="cmin"></span>
                </label>
                <label class="qdf-row">
                    <span class="qdf-l">Çocuk Max Yaş</span>
                    <span class="qdf-v"><input type="number" name="child_max_age" value="{{ $ageVals['child_max_age'] }}" placeholder="{{ $tour->child_max_age ?? 12 }}" data-qd-age="cmax"></span>
                </label>
                @if($tour->infant_allowed)
                    <label class="qdf-row">
                        <span class="qdf-l">Bebek Min Yaş</span>
                        <span class="qdf-v"><input type="number" name="infant_min_age" value="{{ $ageVals['infant_min_age'] }}" placeholder="{{ $tour->infant_min_age ?? 0 }}" data-qd-age="imin"></span>
                    </label>
                    <label class="qdf-row">
                        <span class="qdf-l">Bebek Max Yaş</span>
                        <span class="qdf-v"><input type="number" name="infant_max_age" value="{{ $ageVals['infant_max_age'] }}" placeholder="{{ $tour->infant_max_age ?? 2 }}" data-qd-age="imax"></span>
                    </label>
                @endif
            </div>
        </div>
    </div>

    {{-- ══ İNDİRİMLER (katlanır) ══ --}}
    <div class="qdf-fold" data-qd-fold>
        <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="false">
            <i class="fas fa-percent"></i>
            <span class="qdf-fold-t">İndirimler</span>
            <span class="qdf-fold-s">{{ $discSummary }}</span>
            <i class="fas fa-chevron-down qdf-fold-chev"></i>
        </button>
        <div class="qdf-fold-b" data-qd-fold-body hidden>
            <div class="qdf-rows">
                <label class="qdf-row">
                    <span class="qdf-l">Erken Rezervasyon</span>
                    <span class="qdf-v qdf-suffix"><input type="number" step="0.01" min="0" name="early_booking_discount" value="{{ $d?->early_booking_discount }}" placeholder="0"><small>%</small></span>
                </label>
                <label class="qdf-row">
                    <span class="qdf-l">Son Dakika</span>
                    <span class="qdf-v qdf-suffix"><input type="number" step="0.01" min="0" name="last_minute_discount" value="{{ $d?->last_minute_discount }}" placeholder="0"><small>%</small></span>
                </label>
                <label class="qdf-row">
                    <span class="qdf-l">Grup</span>
                    <span class="qdf-v qdf-suffix"><input type="number" step="0.01" min="0" name="group_discount" value="{{ $d?->group_discount }}" placeholder="0"><small>%</small></span>
                </label>
                <label class="qdf-row">
                    <span class="qdf-l">Grup Min Kişi</span>
                    <span class="qdf-v"><input type="number" min="0" name="min_group_size" value="{{ $d?->min_group_size }}" placeholder="Örn. 10"></span>
                </label>
                <label class="qdf-row">
                    <span class="qdf-l">Özel İndirim</span>
                    <span class="qdf-v qdf-suffix"><input type="number" step="0.01" min="0" name="special_discount" value="{{ $d?->special_discount }}" placeholder="0"><small>%</small></span>
                </label>
                <label class="qdf-row">
                    <span class="qdf-l">Özel İnd. Nedeni</span>
                    <span class="qdf-v"><input type="text" name="discount_reason" value="{{ $d?->discount_reason }}" placeholder="Kampanya adı"></span>
                </label>
            </div>
        </div>
    </div>

    {{-- ══ ZAMAN KURALLARI (katlanır) ══ --}}
    <div class="qdf-fold" data-qd-fold>
        <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="false">
            <i class="fas fa-hourglass-half"></i>
            <span class="qdf-fold-t">Zaman Kuralları</span>
            <span class="qdf-fold-s">{{ $ruleSummary }}</span>
            <i class="fas fa-chevron-down qdf-fold-chev"></i>
        </button>
        <div class="qdf-fold-b" data-qd-fold-body hidden>
            @include('agency.products._qv-deadline-rule', ['name' => 'early_booking_rule', 'label' => 'Erken rezervasyon indirimi — şu ana kadar geçerli', 'rule' => $d?->early_booking_rule, 'anchors' => ['departure' => 'Kalkış', 'publish' => 'Yayın Tarihi']])
            @include('agency.products._qv-deadline-rule', ['name' => 'last_minute_rule', 'label' => 'Son dakika indirimi — şu andan itibaren geçerli', 'rule' => $d?->last_minute_rule, 'anchors' => ['departure' => 'Kalkış', 'booking_close' => 'Rez. Kapanışı']])
            @include('agency.products._qv-deadline-rule', ['name' => 'booking_deadline_rule', 'label' => 'Son rezervasyon — rezervasyon şu ana kadar açık', 'rule' => $d?->booking_deadline_rule, 'anchors' => ['departure' => 'Kalkış', 'publish' => 'Yayın Tarihi']])
        </div>
    </div>

    {{-- ══ BU TARİHE ÖZEL ÖDEME PLANI (katlanır) ══ --}}
    <div class="qdf-fold" data-qd-fold>
        <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="false">
            <i class="fas fa-money-check-dollar"></i>
            <span class="qdf-fold-t">Ödeme Planı</span>
            <span class="qdf-fold-s">{{ $cppSummary }}</span>
            <i class="fas fa-chevron-down qdf-fold-chev"></i>
        </button>
        <div class="qdf-fold-b" data-qd-fold-body hidden>
            <div class="qdf-switches">
                <label class="qdf-sw"><input type="checkbox" name="use_custom_payment_plan" value="1" data-qd-cpp-toggle @checked($cppOn)><span>Bu tarih için özel kademeli ödeme planı kullan</span></label>
            </div>
            <div data-qd-cpp-wrap style="{{ $cppOn ? '' : 'display:none' }}">
                <p class="qdf-hint"><i class="fas fa-circle-info"></i> Aşamalar <b>eklendikleri sırayla</b> (1, 2, 3…) tahsil edilir ve toplamları %100 olmalıdır.</p>
                <div data-qd-stage-rows>
                    @foreach($stages as $i => $st)
                        <div class="qd-form qd-stage-row">
                            <div class="qd-fld"><label>Etiket</label><input type="text" name="payment_schedule[{{ $i }}][label]" value="{{ $st['label'] ?? '' }}" class="qd-inp" placeholder="Ör: Kapora" @disabled(!$cppOn)></div>
                            <div class="qd-fld"><label>Yüzde %</label><input type="number" min="0" max="100" name="payment_schedule[{{ $i }}][percent]" value="{{ $st['percent'] ?? '' }}" class="qd-inp" @disabled(!$cppOn)></div>
                            <div class="qd-fld"><label>Tetikleyici</label><select name="payment_schedule[{{ $i }}][trigger]" class="qd-inp" @disabled(!$cppOn)>@foreach($stageTriggers as $v => $l)<option value="{{ $v }}" @selected(($st['trigger'] ?? '') === $v)>{{ $l }}</option>@endforeach</select></div>
                            <div class="qd-fld"><label>Gün (X)</label><input type="number" min="0" name="payment_schedule[{{ $i }}][offset_days]" value="{{ $st['offset_days'] ?? '' }}" class="qd-inp" @disabled(!$cppOn)></div>
                            <div class="qd-fld qd-stage-act"><button type="button" class="pqv-iconbtn danger" data-qd-stage-remove title="Aşamayı sil"><i class="fas fa-times"></i></button></div>
                        </div>
                    @endforeach
                </div>
                <button type="button" class="qdf-addstage" data-qd-stage-add><i class="fas fa-plus"></i> Aşama Ekle</button>
            </div>
        </div>
    </div>

    @if($isNew)
        {{-- ══ SERİ TARİH (katlanır) — işaretlenirse form dates.bulk'a gider ══ --}}
        <div class="qdf-fold" data-qd-fold>
            <button type="button" class="qdf-fold-h" data-qd-fold-toggle aria-expanded="false">
                <i class="fas fa-repeat"></i>
                <span class="qdf-fold-t">Seri Tarih</span>
                <span class="qdf-fold-s">Aynı fiyatlarla birden çok tarih üret</span>
                <i class="fas fa-chevron-down qdf-fold-chev"></i>
            </button>
            <div class="qdf-fold-b" data-qd-fold-body hidden>
                <div class="qdf-switches">
                    <label class="qdf-sw"><input type="checkbox" name="__series_enabled" value="1" data-qd-series-toggle><span>Seri oluştur</span></label>
                </div>
                <div data-qd-series-wrap style="display:none">
                    <div class="qdf-rows">
                        <label class="qdf-row">
                            <span class="qdf-l">Tekrar Sıklığı</span>
                            <span class="qdf-v">
                                <select name="repeat_frequency" disabled>
                                    @foreach(['weekly' => 'Haftalık', 'biweekly' => '2 haftada bir', 'monthly' => 'Aylık', 'interval' => 'Her N günde bir'] as $v => $l)
                                        <option value="{{ $v }}">{{ $l }}</option>
                                    @endforeach
                                </select>
                            </span>
                        </label>
                        <label class="qdf-row">
                            <span class="qdf-l">Gün Aralığı (N)</span>
                            <span class="qdf-v"><input type="number" name="repeat_interval_days" min="1" max="365" placeholder="Örn. 10" disabled></span>
                        </label>
                        <label class="qdf-row">
                            <span class="qdf-l">Kaç Tarih?</span>
                            <span class="qdf-v"><input type="number" name="repeat_count" min="1" max="52" placeholder="Örn. 8" disabled></span>
                        </label>
                    </div>
                    <p class="qdf-hint"><i class="fas fa-circle-info"></i> İlk tarih yukarıdaki başlangıç/bitiş tarihidir; sonrakiler seçilen sıklıkla ötelenir.</p>
                </div>
            </div>
        </div>
    @endif
</div>
