@extends('agency.layouts.app')

@section('title', $tour->name . ' - Tarihler')
@section('page_title', 'Tur Tarihleri')

@php
    $breadcrumbs = [
        ['title' => 'Ana Sayfa', 'url' => route('agency.dashboard')],
        ['title' => 'Yurt Dışı Turları', 'url' => route('agency.products.yurtdisi-turlari.index')],
        ['title' => $tour->name, 'url' => route('agency.products.yurtdisi-turlari.show', $tour)],
        ['title' => 'Tarihler', 'url' => '']
    ];
@endphp

@push('styles')
    <style>
        .tour-detail-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .tour-header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: white;
            padding: 2rem;
            border-radius: var(--radius-xl);
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }

        .tour-header::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 200px;
            height: 200px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            transform: translate(50%, -50%);
        }

        .tour-header-content {
            position: relative;
            z-index: 2;
        }

        .tour-title {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .tour-code {
            font-size: 14px;
            opacity: 0.9;
            margin-bottom: 1rem;
        }

        .tour-meta {
            display: flex;
            gap: 2rem;
            flex-wrap: wrap;
        }

        .tour-meta-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 14px;
        }

        .tour-meta-icon {
            font-size: 16px;
            opacity: 0.8;
        }

        .tabs-container {
            background: white;
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-xl);
            overflow: hidden;
            margin-bottom: 2rem;
        }

        .nav-tabs {
            background: var(--gray-50);
            border-bottom: 1px solid var(--gray-200);
            padding: 0 1rem;
            margin: 0;
        }

        .nav-tabs .nav-link {
            border: none;
            border-radius: 0;
            color: var(--gray-600);
            font-weight: 500;
            padding: 1rem 1.5rem;
            position: relative;
            transition: var(--transition);
        }

        .nav-tabs .nav-link:hover {
            color: var(--primary-color);
            background: transparent;
            border-color: transparent;
        }

        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            background: transparent;
            border-color: transparent;
            font-weight: 600;
        }

        .nav-tabs .nav-link.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: var(--primary-color);
            border-radius: 3px 3px 0 0;
        }

        .tab-content {
            padding: 2rem;
        }

        .dates-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        .dates-stats {
            display: flex;
            gap: 1rem;
            font-size: 13px;
            color: var(--gray-600);
        }

        .dates-stat {
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .dates-table-wrapper {
            background: white;
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-xl);
            overflow: hidden;
        }

        .dates-table {
            width: 100%;
            border-collapse: collapse;
        }

        .dates-table thead {
            background: var(--gray-50);
            border-bottom: 1px solid var(--gray-200);
        }

        .dates-table th {
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            color: var(--gray-700);
            font-size: 13px;
            white-space: nowrap;
        }

        .dates-table td {
            padding: 1rem;
            border-bottom: 1px solid var(--gray-100);
            font-size: 14px;
        }

        .dates-table tbody tr:hover {
            background: var(--gray-50);
        }

        .dates-table tbody tr:last-child td {
            border-bottom: none;
        }

        .date-code {
            font-weight: 600;
            color: var(--gray-900);
            font-size: 12px;
            display: block;
            margin-bottom: 4px;
        }

        .date-range {
            font-weight: 600;
            color: var(--gray-900);
            display: block;
            margin-bottom: 2px;
        }

        .date-time {
            font-size: 12px;
            color: var(--gray-600);
        }

        .date-capacity {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .capacity-main {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .capacity-bar {
            width: 100px;
            height: 6px;
            background: var(--gray-200);
            border-radius: 3px;
            overflow: hidden;
        }

        .capacity-fill {
            height: 100%;
            background: var(--success-color);
            transition: width 0.3s ease;
        }

        .capacity-fill.warning {
            background: var(--warning-color);
        }

        .capacity-fill.danger {
            background: var(--danger-color);
        }

        .capacity-text {
            font-size: 12px;
            color: var(--gray-600);
        }

        .capacity-details {
            font-size: 11px;
            color: var(--gray-500);
        }

        .date-price {
            text-align: right;
        }

        .price-main {
            font-weight: 700;
            color: var(--gray-900);
            font-size: 16px;
        }

        .price-currency {
            font-size: 12px;
            color: var(--gray-600);
        }

        .price-details {
            font-size: 12px;
            color: var(--gray-600);
            margin-top: 4px;
        }

        .date-status {
            text-align: center;
            vertical-align: middle;
        }

        .date-status .d-flex {
            align-items: center;
            justify-content: center;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 10px;
            border-radius: var(--radius-md);
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            white-space: nowrap;
        }

        .status-badge.active {
            background: var(--success-light);
            color: var(--success-dark);
        }

        .status-badge.inactive {
            background: var(--gray-100);
            color: var(--gray-600);
        }

        .status-badge.completed {
            background: var(--info-light);
            color: var(--info-dark);
        }

        .status-badge.cancelled {
            background: var(--danger-light);
            color: var(--danger-dark);
        }

        .date-actions {
            text-align: left;
            vertical-align: middle;
        }

        .date-actions .btn-group {
            display: inline-flex;
            gap: 0.25rem;
        }

        .empty-dates {
            text-align: center;
            padding: 3rem;
            color: var(--gray-500);
            background: white;
            border: 2px dashed var(--gray-200);
            border-radius: var(--radius-xl);
        }

        .empty-dates-icon {
            font-size: 48px;
            color: var(--gray-300);
            margin-bottom: 1rem;
        }

        .modal-content {
            border-radius: var(--radius-xl);
            border: none;
            box-shadow: var(--shadow-xl);
        }

        .modal-header {
            border-bottom: 1px solid var(--gray-200);
            border-radius: var(--radius-xl) var(--radius-xl) 0 0;
            background: var(--gray-50);
        }

        .modal-body {
            padding: 2rem;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
            display: block;
        }

        .form-label.required::after {
            content: '*';
            color: var(--danger-color);
            margin-left: 4px;
        }

        .form-control {
            border: 1px solid var(--gray-300);
            border-radius: var(--radius-lg);
            padding: 0.75rem 1rem;
            font-size: 14px;
            transition: var(--transition);
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
            outline: none;
        }

        .form-text {
            font-size: 12px;
            color: var(--gray-500);
            margin-top: 0.25rem;
        }

        .pricing-section {
            background: var(--gray-50);
            padding: 1.5rem;
            border-radius: var(--radius-lg);
            margin-top: 1.5rem;
        }

        .pricing-section-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .use-default-btn {
            font-size: 13px;
            font-weight: 500;
            color: var(--primary-color);
            background: none;
            border: none;
            cursor: pointer;
            transition: var(--transition);
        }

        .use-default-btn:hover {
            color: var(--primary-dark);
        }

        .guarantee-badge {
            display: inline-flex;
            align-items: center;
            padding: 2px 6px;
            background: var(--warning-light);
            color: var(--warning-dark);
            border-radius: var(--radius-sm);
            font-size: 10px;
            font-weight: 600;
            margin-top: 4px;
        }

        @media (max-width: 768px) {
            .tour-detail-container {
                margin: 0;
            }

            .tour-header {
                padding: 1.5rem;
                margin-bottom: 1rem;
            }

            .tour-title {
                font-size: 22px;
            }

            .tour-meta {
                gap: 1rem;
            }

            .tab-content {
                padding: 1.5rem;
            }

            .dates-header {
                flex-direction: column;
                gap: 1rem;
                align-items: flex-start;
            }

            .dates-table-wrapper {
                overflow-x: auto;
            }

            .dates-table {
                min-width: 800px;
            }
        }
    </style>
@endpush

@section('content')
    <div class="tour-detail-container">
        <!-- Tour Header -->
        <div class="tour-header">
            <div class="tour-header-content">
                <div class="tour-code">Tur Kodu: {{ $tour->code }}</div>
                <h1 class="tour-title">{{ $tour->name }}</h1>
                <div class="tour-meta">
                    <div class="tour-meta-item">
                        <i class="fas fa-map-marker-alt tour-meta-icon"></i>
                        {{ $tour->departureCity->city ?? 'Belirtilmemiş' }}
                        → {{ $tour->arrivalCity->city ?? 'Belirtilmemiş' }}
                    </div>
                    <div class="tour-meta-item">
                        <i class="fas fa-clock tour-meta-icon"></i>
                        {{ $tour->days }} Gün / {{ $tour->nights }} Gece
                    </div>
                    <div class="tour-meta-item">
                        <i class="fas fa-calendar tour-meta-icon"></i>
                        {{ $dates->count() }} Tarih
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabs Container -->
        <div class="tabs-container">
            <!-- Tab Navigation -->
            @include('agency.products.yurtdisi-turlari._nav', ['active' => 'dates'])

            <!-- Tab Content -->
            <div class="tab-content">
                <!-- Dates Header -->
                <div class="dates-header">
                    <div>
                        <h3>Tur Tarihleri</h3>
                        <p class="text-muted mb-0">Turunuzun gerçekleşeceği tarihleri ve kapasitelerini yönetin</p>
                    </div>
                    <div class="dates-stats">
                        <div class="dates-stat">
                            <i class="fas fa-calendar-check"></i>
                            {{ $dates->count() }} Tarih
                        </div>
                        <div class="dates-stat">
                            <i class="fas fa-check-circle"></i>
                            {{ $dates->where('is_active', true)->count() }} Aktif
                        </div>
                        <div class="dates-stat">
                            <i class="fas fa-users"></i>
                            {{ $dates->sum('sold_count') }} Satış
                        </div>
                    </div>
                </div>

                <!-- Add Date Button -->
                <div class="mb-3">
                    <button type="button" class="btn btn-primary" onclick="addDate()">
                        <i class="fas fa-plus"></i> Yeni Tarih Ekle
                    </button>
                </div>

                <!-- Dates Table -->
                @if($dates->count() > 0)
                    <div class="dates-table-wrapper">
                        <table class="dates-table">
                            <thead>
                            <tr>
                                <th>Tarih Bilgileri</th>
                                <th>Kapasite</th>
                                <th>Fiyatlandırma</th>
                                <th width="150">Durum</th>
                                <th width="120">İşlemler</th>
                            </tr>
                            </thead>
                            <tbody>
                            @foreach($dates as $date)
                                <tr>
                                    <td>
                                        <span class="date-code">{{ $date->code }}</span>
                                        <span class="date-range">{{ $date->formatted_date_range }}</span>
                                        @if($date->guarantee_departure)
                                            <span class="guarantee-badge">
                                                    <i class="fas fa-shield-alt me-1"></i>
                                                    Garanti Kalkış
                                                </span>
                                        @endif
                                    </td>
                                    <td>
                                        <div class="date-capacity">
                                            <div class="capacity-main">
                                                <div class="capacity-bar">
                                                    @php
                                                        $percentage = $date->total_capacity > 0
                                                            ? ($date->sold_count / $date->total_capacity) * 100
                                                            : 0;
                                                        $class = '';
                                                        if($percentage >= 90) $class = 'danger';
                                                        elseif($percentage >= 70) $class = 'warning';
                                                    @endphp
                                                    <div class="capacity-fill {{ $class }}"
                                                         style="width: {{ $percentage }}%"></div>
                                                </div>
                                                <span class="capacity-text">
                                                        {{ $date->remaining_capacity }}/{{ $date->total_capacity }}
                                                    </span>
                                            </div>
                                            <div class="capacity-details">
                                                {{ $date->sold_count }} satış
                                                @if($date->reserved_count > 0)
                                                    , {{ $date->reserved_count }} rezerve
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                    <td class="date-price">
                                        <div>
                                                <span class="price-main">
                                                    {{ number_format($date->adult_price, 0) }}
                                                </span>
                                            <span class="price-currency">{{ $date->currency }}</span>
                                        </div>
                                        <div class="price-details">
                                            @if($date->single_supplement)
                                                <span class="me-2">SNG +{{ number_format($date->single_supplement, 0) }}</span>
                                            @endif
                                            @if($date->child_price_1)
                                                <span>Çocuk {{ number_format($date->child_price_1, 0) }}</span>
                                            @endif
                                        </div>
                                    </td>
                                    <td class="date-status">
                                        <div class="d-flex flex-column gap-1">
                                                <span
                                                    class="status-badge {{ $date->is_active ? 'active' : 'inactive' }}">
                                                    {{ $date->is_active ? 'AKTİF' : 'PASİF' }}
                                                </span>
                                            <span class="status-badge {{ strtolower($date->status) }}">
                                                    {{ $date->status_display_name }}
                                                </span>
                                        </div>
                                    </td>
                                    <td class="date-actions">
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-primary"
                                                    onclick="editDate({{ $date->id }})" title="Düzenle">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-info"
                                                    onclick="duplicateDate({{ $date->id }})" title="Kopyala">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary"
                                                    onclick="toggleStatus({{ $date->id }})"
                                                    title="{{ $date->is_active ? 'Pasif Yap' : 'Aktif Yap' }}">
                                                <i class="fas {{ $date->is_active ? 'fa-eye-slash' : 'fa-eye' }}"></i>
                                            </button>
                                            @if($date->sold_count == 0)
                                                <button type="button" class="btn btn-sm btn-outline-danger"
                                                        onclick="deleteDate({{ $date->id }})" title="Sil">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                @else
                    <div class="empty-dates">
                        <div class="empty-dates-icon">
                            <i class="fas fa-calendar-times"></i>
                        </div>
                        <h5>Henüz tur tarihi eklenmemiş</h5>
                        <p class="mb-3">Turunuzun gerçekleşeceği tarihleri eklemeye başlayın</p>
                        <button type="button" class="btn btn-primary" onclick="addDate()">
                            <i class="fas fa-plus"></i> İlk Tarihi Ekle
                        </button>
                    </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Add/Edit Date Modal -->
    <div class="modal fade" id="dateModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="dateModalTitle">Yeni Tarih Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="dateForm">
                        @csrf
                        <input type="hidden" name="tour_id" value="{{ $tour->id }}">
                        <input type="hidden" name="date_id" id="dateId">

                        <!-- Tarih -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label required">Başlangıç Tarihi</label>
                                    <input type="date" name="start_date" id="start_date" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label required">Bitiş Tarihi</label>
                                    <input type="date" name="end_date" id="end_date" class="form-control" required>
                                </div>
                            </div>
                        </div>

                        <!-- Kapasite -->
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label required">Toplam Kapasite</label>
                                    <input type="number" name="total_capacity" id="total_capacity" class="form-control"
                                           required>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">Yetişkin Kapasitesi</label>
                                    <input type="number" name="adult_capacity" id="adult_capacity" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">Çocuk Kapasitesi</label>
                                    <input type="number" name="child_capacity" id="child_capacity" class="form-control">
                                </div>
                            </div>
                            @if($tour->infant_allowed)
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">Bebek Kapasitesi</label>
                                    <input type="number" name="infant_capacity" id="infant_capacity"
                                           class="form-control">
                                </div>
                            </div>
                            @endif
                        </div>

                        <!-- Fiyatlandırma (Oda Bazlı) -->
                        <div class="pricing-section">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h5 class="pricing-section-title mb-0">Fiyatlandırma (Konaklamalı / Oda Bazlı)</h5>
                                @if($dates->count() > 0)
                                    <div class="d-flex align-items-center gap-2">
                                        <label class="form-label mb-0 small text-muted">Fiyatları şu tarihten kopyala:</label>
                                        <select id="copy_from_date" class="form-select form-select-sm" style="width:auto"
                                                onchange="copyPricesFromDate(this.value)">
                                            <option value="">— Seçin —</option>
                                            @foreach($dates as $d)
                                                <option value="{{ $d->id }}">{{ $d->code }} — {{ $d->start_date?->format('d.m.Y') }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                @endif
                            </div>

                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label" title="{{ \App\Support\TourFareCatalog::FARES['adult']['hint'] }}">{{ \App\Support\TourFareCatalog::label('adult') }}</label>
                                        <input type="number" name="adult_price" id="adult_price" class="form-control"
                                               step="0.01" placeholder="2 kişilik odada kişi başı">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label" title="{{ \App\Support\TourFareCatalog::FARES['single']['hint'] }}">{{ \App\Support\TourFareCatalog::label('single') }}</label>
                                        <input type="number" name="single_supplement" id="single_supplement" class="form-control"
                                               step="0.01" placeholder="Kişi başı fiyata eklenir">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label" title="{{ \App\Support\TourFareCatalog::FARES['extra_bed']['hint'] }}">{{ \App\Support\TourFareCatalog::label('extra_bed') }}</label>
                                        <input type="number" name="extra_bed_price" id="extra_bed_price" class="form-control"
                                               step="0.01" placeholder="İlave yatakla giren kişi">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Para Birimi</label>
                                        <select name="currency" id="currency" class="form-select">
                                            @foreach($activeCurrencies as $currency)
                                                <option value="{{ $currency->code }}">{{ $currency->code }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label" title="{{ \App\Support\TourFareCatalog::FARES['child1']['hint'] }}">{{ \App\Support\TourFareCatalog::label('child1') }}</label>
                                        <input type="number" name="child_price_1" id="child_price_1" class="form-control"
                                               step="0.01">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label" title="{{ \App\Support\TourFareCatalog::FARES['child2']['hint'] }}">{{ \App\Support\TourFareCatalog::label('child2') }}</label>
                                        <input type="number" name="child_price_2" id="child_price_2" class="form-control"
                                               step="0.01">
                                    </div>
                                </div>
                                @if($tour->infant_allowed)
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label" title="{{ \App\Support\TourFareCatalog::FARES['infant']['hint'] }}">{{ \App\Support\TourFareCatalog::label('infant') }}</label>
                                        <input type="number" name="infant_price" id="infant_price" class="form-control"
                                               step="0.01">
                                    </div>
                                </div>
                                @endif
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Oda Kapasitesi</label>
                                        <input type="number" name="room_capacity" id="room_capacity" class="form-control"
                                               min="1" placeholder="1 odada maks kişi">
                                    </div>
                                </div>
                            </div>

                            <!-- Yaş Aralıkları -->
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Çocuk Min Yaş</label>
                                        <input type="number" name="child_min_age" id="child_min_age" class="form-control" placeholder="2">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Çocuk Max Yaş</label>
                                        <input type="number" name="child_max_age" id="child_max_age" class="form-control" placeholder="12">
                                    </div>
                                </div>
                                @if($tour->infant_allowed)
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Bebek Min Yaş</label>
                                        <input type="number" name="infant_min_age" id="infant_min_age" class="form-control" placeholder="0">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Bebek Max Yaş</label>
                                        <input type="number" name="infant_max_age" id="infant_max_age" class="form-control" placeholder="2">
                                    </div>
                                </div>
                                @endif
                            </div>
                        </div>

                        <!-- İndirimler -->
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">Erken Rezervasyon İndirimi (%)</label>
                                    <input type="number" name="early_booking_discount" id="early_booking_discount"
                                           class="form-control" step="0.01">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">Son Dakika İndirimi (%)</label>
                                    <input type="number" name="last_minute_discount" id="last_minute_discount"
                                           class="form-control" step="0.01">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">Grup İndirimi (%)</label>
                                    <input type="number" name="group_discount" id="group_discount" class="form-control"
                                           step="0.01">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">Özel İndirim (%)</label>
                                    <input type="number" name="special_discount" id="special_discount"
                                           class="form-control" step="0.01">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">Grup Min Kişi</label>
                                    <input type="number" name="min_group_size" id="min_group_size" class="form-control" min="0">
                                </div>
                            </div>
                            <div class="col-md-9">
                                <div class="form-group">
                                    <label class="form-label">Özel İndirim Açıklaması</label>
                                    <input type="text" name="discount_reason" id="discount_reason" class="form-control">
                                </div>
                            </div>
                        </div>

                        <!-- Geçerlilik & Rezervasyon Zamanları -->
                        <div class="pricing-section mt-2">
                            <h5 class="pricing-section-title"><i class="fas fa-hourglass-half"></i> Geçerlilik & Rezervasyon Zamanları</h5>
                            @include('agency.products._dp-rule', ['name' => 'early_booking_rule', 'label' => 'Erken Rez. indirimi — bu ana kadar geçerli', 'anchors' => ['departure' => 'Kalkış', 'publish' => 'Yayın Tarihi']])
                            @include('agency.products._dp-rule', ['name' => 'last_minute_rule', 'label' => 'Son Dakika indirimi — bu andan itibaren', 'anchors' => ['departure' => 'Kalkış', 'booking_close' => 'Rez. Kapanışı']])
                            @include('agency.products._dp-rule', ['name' => 'booking_deadline_rule', 'label' => 'Son Rezervasyon — bu ana kadar açık', 'anchors' => ['departure' => 'Kalkış', 'publish' => 'Yayın Tarihi']])
                        </div>

                        <!-- Sezon ve Durum -->
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="form-label">Sezon Tipi</label>
                                    <select name="season_type" id="season_type" class="form-select">
                                        <option value="low">Düşük Sezon</option>
                                        <option value="medium" selected>Orta Sezon</option>
                                        <option value="high">Yüksek Sezon</option>
                                        <option value="peak">Zirve Sezon</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="form-label required">Durum</label>
                                    <select name="status" id="status" class="form-select" required>
                                        <option value="draft">Taslak</option>
                                        <option value="published">Yayınlandı</option>
                                        <option value="booking_open" selected>Rezervasyon Açık</option>
                                        <option value="booking_closed">Rezervasyon Kapalı</option>
                                        <option value="confirmed">Onaylandı</option>
                                        <option value="in_progress">Devam Ediyor</option>
                                        <option value="completed">Tamamlandı</option>
                                        <option value="cancelled">İptal Edildi</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="form-label">Min Katılımcı</label>
                                    <input type="number" name="min_participants" id="min_participants"
                                           class="form-control">
                                </div>
                            </div>
                        </div>

                        <!-- Checkboxlar -->
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-check">
                                    <input type="checkbox" name="guarantee_departure" id="guarantee_departure"
                                           class="form-check-input">
                                    <label class="form-check-label">Kesin Kalkış</label>
                                </div>
                            </div>
                            <div class="col-md-5">
                                <div class="form-check">
                                    <input type="checkbox" name="auto_guarantee_on_min" id="auto_guarantee_on_min"
                                           class="form-check-input">
                                    <label class="form-check-label">Min katılımcıya ulaşınca otomatik kesin kalkış</label>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-check">
                                    <input type="checkbox" name="is_active" id="is_active" class="form-check-input"
                                           checked>
                                    <label class="form-check-label">Aktif</label>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-check">
                                    <input type="checkbox" name="is_bookable" id="is_bookable" class="form-check-input"
                                           checked>
                                    <label class="form-check-label">Rez. Açık</label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group mt-3">
                            <label class="form-label">Özel Notlar</label>
                            <textarea name="special_notes" id="special_notes" class="form-control" rows="2"></textarea>
                        </div>

                        <!-- Bu tarihe özel kademeli ödeme planı (tur planını override eder) -->
                        <div class="pricing-section mt-3">
                            <div class="form-check mb-2">
                                <input type="checkbox" name="use_custom_payment_plan" id="use_custom_payment_plan"
                                       class="form-check-input" onchange="toggleCustomPaymentPlan()">
                                <label class="form-check-label">Bu tarih için özel kademeli ödeme planı kullan</label>
                            </div>
                            <div id="custom_payment_plan_wrap" style="display:none;">
                                <p class="text-muted small mb-2">Aşamalar (toplam %100 olmalı). Boş bırakılırsa turun genel ödeme planı geçerlidir.</p>
                                <div class="pp-order-note"><i class="fas fa-circle-info"></i> Ödemeler, aşamaları <strong>eklediğiniz sıraya göre</strong> (1, 2, 3…) tahsil edilir. Yandaki numaralar ödeme sırasını gösterir.</div>
                                <div id="date_payment_stages"></div>
                                <button type="button" class="btn btn-sm btn-outline-primary mt-1" onclick="addDateStage()">
                                    <i class="fas fa-plus"></i> Aşama Ekle
                                </button>
                            </div>
                        </div>

                        <!-- Seri Tarih Oluşturma (yalnızca yeni tarih eklerken) -->
                        <div class="pricing-section mt-3" id="series_section">
                            <div class="form-check mb-2">
                                <input type="checkbox" name="__series_enabled" id="series_enabled"
                                       class="form-check-input" onchange="toggleSeries()">
                                <label class="form-check-label">Seri oluştur (aynı fiyatlarla birden çok tarih)</label>
                            </div>
                            <div id="series_wrap" style="display:none;">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label class="form-label">Tekrar Sıklığı</label>
                                            <select id="repeat_frequency" class="form-select">
                                                <option value="weekly">Haftalık</option>
                                                <option value="biweekly">2 Haftada bir</option>
                                                <option value="monthly">Aylık</option>
                                                <option value="interval">Her N günde bir</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label class="form-label">Gün Aralığı (N)</label>
                                            <input type="number" id="repeat_interval_days" class="form-control" min="1" placeholder="Örn: 10">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label class="form-label">Kaç Adet Tarih?</label>
                                            <input type="number" id="repeat_count" class="form-control" min="1" max="52" placeholder="Örn: 8">
                                        </div>
                                    </div>
                                </div>
                                <p class="text-muted small mb-0">İlk tarih yukarıdaki başlangıç/bitiş tarihidir; sonrakiler seçilen sıklıkla ötelenir.</p>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="button" class="btn btn-primary" onclick="saveDate()">Kaydet</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        // Tur süresine göre bitiş tarihini hesapla
        document.getElementById('start_date').addEventListener('change', function () {
            const startDate = new Date(this.value);
            const duration = {{ $tour->days ?? 1 }};

            if (startDate && duration) {
                const endDate = new Date(startDate);
                // Kültür turları gün bazında olduğu için gün ekle
                endDate.setDate(endDate.getDate() + duration - 1);

                document.getElementById('end_date').value = endDate.toISOString().split('T')[0];
                document.getElementById('end_date').min = this.value;
            }
        });

        function addDate() {
            document.getElementById('dateModalTitle').textContent = 'Yeni Tarih Ekle';
            document.getElementById('dateForm').reset();
            document.getElementById('dateId').value = '';

            document.getElementById('series_section').style.display = '';
            document.getElementById('series_enabled').checked = false;
            toggleSeries();
            document.getElementById('date_payment_stages').innerHTML = '';
            toggleCustomPaymentPlan();

            // Tur ayarındaki "min katılımcıda otomatik kesin kalkış" varsayılanını uygula
            document.getElementById('auto_guarantee_on_min').checked = {{ $tour->auto_guarantee_on_min ? 'true' : 'false' }};

            resetRules();

            new bootstrap.Modal(document.getElementById('dateModal')).show();
        }

        // ── Esnek deadline kuralları (tam sayfa modal) ───────────────────────
        function applyRule(name, rule) {
            const modeEl = document.getElementById(name + '_mode');
            if (!modeEl) return;
            rule = rule || {};
            modeEl.value = rule.mode || '';
            const set = (suffix, val) => { const el = document.getElementById(name + suffix); if (el && val !== undefined && val !== null && val !== '') el.value = val; };
            const clear = (suffix) => { const el = document.getElementById(name + suffix); if (el) el.value = (el.tagName === 'SELECT' ? el.options[0].value : ''); };
            clear('_at'); clear('_amount');
            set('_at', rule.at);
            set('_amount', rule.amount);
            set('_unit', rule.unit);
            set('_direction', rule.direction);
            set('_anchor', rule.anchor);
            const wrap = modeEl.closest('.dp-rule');
            if (wrap) {
                const at = wrap.querySelector('.dp-rule-at');
                const rel = wrap.querySelector('.dp-rule-rel');
                if (at) at.style.display = modeEl.value === 'datetime' ? '' : 'none';
                if (rel) rel.style.display = modeEl.value === 'relative' ? '' : 'none';
            }
        }

        function resetRules() {
            ['early_booking_rule', 'last_minute_rule', 'booking_deadline_rule'].forEach(n => applyRule(n, {}));
        }

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

        const DATES_BASE_URL = `{{ route('agency.products.yurtdisi-turlari.dates', $tour) }}`;

        function editDate(dateId) {
            document.getElementById('dateModalTitle').textContent = 'Tarihi Düzenle';
            document.getElementById('dateId').value = dateId;

            document.getElementById('series_enabled').checked = false;
            toggleSeries();
            document.getElementById('series_section').style.display = 'none';

            const modal = new bootstrap.Modal(document.getElementById('dateModal'));
            modal.show();

            fetch(`${DATES_BASE_URL}/${dateId}`, {
                method: 'GET',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value,
                    'Accept': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        const date = data.date;

                        const setFieldValue = (fieldId, value) => {
                            const field = document.getElementById(fieldId);
                            if (field) {
                                field.value = value || '';
                            }
                        };

                        const setCheckboxValue = (fieldId, value) => {
                            const field = document.getElementById(fieldId);
                            if (field) {
                                field.checked = Boolean(value);
                            }
                        };

                        setFieldValue('start_date', date.start_date);
                        setFieldValue('end_date', date.end_date);
                        setFieldValue('total_capacity', date.total_capacity);
                        setFieldValue('adult_price', date.adult_price);
                        setFieldValue('single_supplement', date.single_supplement);
                        setFieldValue('extra_bed_price', date.extra_bed_price);
                        setFieldValue('child_price_1', date.child_price_1);
                        setFieldValue('child_price_2', date.child_price_2);
                        setFieldValue('infant_price', date.infant_price);
                        setFieldValue('room_capacity', date.room_capacity);
                        setFieldValue('currency', date.currency);
                        setFieldValue('status', date.status); // Status seçimi
                        setFieldValue('special_notes', date.special_notes);
                        setCheckboxValue('guarantee_departure', date.guarantee_departure);
                        setCheckboxValue('is_bookable', date.is_bookable);
                        setFieldValue('adult_capacity', date.adult_capacity);
                        setFieldValue('child_capacity', date.child_capacity);
                        setFieldValue('infant_capacity', date.infant_capacity);
                        setFieldValue('child_min_age', date.child_min_age);
                        setFieldValue('child_max_age', date.child_max_age);
                        setFieldValue('infant_min_age', date.infant_min_age);
                        setFieldValue('infant_max_age', date.infant_max_age);
                        setFieldValue('early_booking_discount', date.early_booking_discount);
                        setFieldValue('last_minute_discount', date.last_minute_discount);
                        setFieldValue('group_discount', date.group_discount);
                        setFieldValue('min_group_size', date.min_group_size);
                        setFieldValue('special_discount', date.special_discount);
                        setFieldValue('discount_reason', date.discount_reason);
                        applyRule('early_booking_rule', date.early_booking_rule);
                        applyRule('last_minute_rule', date.last_minute_rule);
                        applyRule('booking_deadline_rule', date.booking_deadline_rule);
                        setFieldValue('season_type', date.season_type);
                        setFieldValue('min_participants', date.min_participants);
                        setCheckboxValue('is_active', date.is_active);
                        setCheckboxValue('auto_guarantee_on_min', date.auto_guarantee_on_min);

                        setCheckboxValue('use_custom_payment_plan', date.use_custom_payment_plan);
                        document.getElementById('date_payment_stages').innerHTML = '';
                        if (Array.isArray(date.payment_schedule)) {
                            date.payment_schedule.forEach(st => addDateStage(st));
                        }
                        toggleCustomPaymentPlan();

                    } else {
                        alert('Tarih bilgileri alınamadı: ' + (data.message || 'Bilinmeyen hata'));
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    alert('Tarih bilgileri yüklenemedi: ' + error.message);
                });
        }

        // Fiyatları mevcut başka bir tarihten kopyala
        function copyPricesFromDate(dateId) {
            if (!dateId) return;

            fetch(`${DATES_BASE_URL}/${dateId}`, {
                method: 'GET',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value,
                    'Accept': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.date) {
                        const d = data.date;
                        const fields = ['adult_price', 'single_supplement', 'extra_bed_price',
                            'child_price_1', 'child_price_2', 'infant_price', 'room_capacity',
                            'currency', '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'];
                        fields.forEach(f => {
                            const el = document.getElementById(f);
                            if (el && d[f] !== null && d[f] !== undefined) el.value = d[f];
                        });
                    }
                })
                .catch(error => console.error('Error:', error))
                .finally(() => { document.getElementById('copy_from_date').value = ''; });
        }

        // Bir tarihi kopyalayarak yeni taslak oluştur
        function duplicateDate(dateId) {
            fetch(`${DATES_BASE_URL}/${dateId}/duplicate`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value,
                    'Accept': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        alert(data.message || 'Kopyalama başarısız.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Bir hata oluştu.');
                });
        }

        // ── Kademeli ödeme override aşamaları ────────────────────────────────
        function toggleCustomPaymentPlan() {
            const on = document.getElementById('use_custom_payment_plan').checked;
            document.getElementById('custom_payment_plan_wrap').style.display = on ? '' : 'none';
        }

        function addDateStage(stage = {}) {
            const wrap = document.getElementById('date_payment_stages');
            const row = document.createElement('div');
            row.className = 'row g-2 align-items-end mb-2 payment-stage-row';
            row.innerHTML = `
                <div class="col-md-3">
                    <label class="form-label small">Etiket</label>
                    <input type="text" class="form-control form-control-sm stage-label" value="${stage.label ?? ''}" placeholder="Ör: Kapora">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">Yüzde %</label>
                    <input type="number" class="form-control form-control-sm stage-percent" min="0" max="100" value="${stage.percent ?? ''}">
                </div>
                <div class="col-md-4">
                    <label class="form-label small">Tetikleyici</label>
                    <select class="form-select form-select-sm stage-trigger">
                        <option value="at_booking">Rezervasyonda</option>
                        <option value="days_before_departure">Kalkıştan X gün önce</option>
                        <option value="on_departure">Kalkışta</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">Gün (X)</label>
                    <input type="number" class="form-control form-control-sm stage-offset" min="0" value="${stage.offset_days ?? ''}">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('.payment-stage-row').remove()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>`;
            wrap.appendChild(row);
            if (stage.trigger) row.querySelector('.stage-trigger').value = stage.trigger;
        }

        // ── Seri oluşturma ───────────────────────────────────────────────────
        function toggleSeries() {
            const on = document.getElementById('series_enabled').checked;
            document.getElementById('series_wrap').style.display = on ? '' : 'none';
        }

        function appendPaymentStages(formData) {
            if (document.getElementById('use_custom_payment_plan').checked) {
                document.querySelectorAll('#date_payment_stages .payment-stage-row').forEach((row, i) => {
                    formData.append(`payment_schedule[${i}][label]`, row.querySelector('.stage-label').value);
                    formData.append(`payment_schedule[${i}][percent]`, row.querySelector('.stage-percent').value);
                    formData.append(`payment_schedule[${i}][trigger]`, row.querySelector('.stage-trigger').value);
                    formData.append(`payment_schedule[${i}][offset_days]`, row.querySelector('.stage-offset').value);
                });
            }
        }

        function saveDate() {
            const form = document.getElementById('dateForm');
            const formData = new FormData(form);
            const dateId = document.getElementById('dateId').value;
            const seriesOn = document.getElementById('series_enabled').checked && !dateId;

            appendPaymentStages(formData);

            let url = '{{ route('agency.products.yurtdisi-turlari.dates.store', $tour) }}';

            if (seriesOn) {
                url = '{{ route('agency.products.yurtdisi-turlari.dates.bulk', $tour) }}';
                formData.append('repeat_frequency', document.getElementById('repeat_frequency').value);
                formData.append('repeat_interval_days', document.getElementById('repeat_interval_days').value);
                formData.append('repeat_count', document.getElementById('repeat_count').value);
            } else if (dateId) {
                url = `${DATES_BASE_URL}/${dateId}`;
                formData.append('_method', 'PUT');
            }

            fetch(url, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        bootstrap.Modal.getInstance(document.getElementById('dateModal')).hide();
                        window.location.reload();
                    } else {
                        if (data.errors) {
                            let errorMsg = 'Validasyon hataları:\n';
                            Object.values(data.errors).forEach(error => {
                                errorMsg += '- ' + error[0] + '\n';
                            });
                            alert(errorMsg);
                        } else {
                            alert(data.message || 'Bir hata oluştu.');
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Sunucu hatası: ' + error.message);
                });
        }

        function toggleStatus(dateId) {
            fetch(`{{ route('agency.products.yurtdisi-turlari.dates', $tour) }}/${dateId}/toggle-status`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value,
                    'Content-Type': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        alert(data.message || 'İşlem başarısız.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Bir hata oluştu.');
                });
        }

        function deleteDate(dateId) {
            if (!confirm('Bu tarihi silmek istediğinizden emin misiniz?')) {
                return;
            }

            fetch(`{{ route('agency.products.yurtdisi-turlari.dates', $tour) }}/${dateId}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value,
                    'Content-Type': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        alert(data.message || 'Silme işlemi başarısız.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Bir hata oluştu.');
                });
        }
    </script>
@endpush
