@extends('agency.layouts.app')

@section('title', 'Yeni Tur Oluştur')
@section('page_title', 'Yeni Tur Oluştur')

@php
    $breadcrumbs = [
        ['title' => 'Ana Sayfa', 'url' => route('agency.dashboard')],
        ['title' => 'Yurt Dışı Turları', 'url' => route('agency.products.yurtdisi-turlari.index')],
        ['title' => 'Yeni Tur', 'url' => '']
    ];
    $productType = \App\Models\Product\ProductType::where('slug', 'yurtdisi-turu')->first();
    $productTypeId = $productType ? $productType->id : null;
    $parentCategories = $productTypeId ? \App\Models\Product\ProductCategory::where('product_type_id', $productTypeId)->whereNull('parent_id')->where('agency_id', auth()->user()->agency->id)->get() : collect();
    $languages = \App\Models\Definition\Language::all();
    $currencies = auth()->user()->agency->getActiveCurrencies();
@endphp

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

        .form-card {
            background: white;
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-xl);
            padding: 2rem;
            box-shadow: var(--shadow-sm);
        }

        .form-header {
            text-align: center;
            margin-bottom: 2rem;
        }

        .form-header h2 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 0.5rem;
        }

        .form-header p {
            color: var(--gray-600);
            font-size: 14px;
        }

        .form-section {
            margin-bottom: 2rem;
            padding-bottom: 2rem;
            border-bottom: 1px solid var(--gray-200);
        }

        .form-section:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
        }

        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .section-icon {
            width: 20px;
            height: 20px;
            color: var(--primary-color);
        }

        .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;
        }

        .duration-fields {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 1rem;
            align-items: end;
        }

        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: space-between;
            margin-top: 2rem;
            padding-top: 2rem;
            border-top: 1px solid var(--gray-200);
        }

        .btn-group {
            display: flex;
            gap: 0.75rem;
        }

        .progress-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 2rem;
        }

        .progress-step {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--gray-400);
            font-size: 12px;
            font-weight: 500;
        }

        .progress-step.active {
            color: var(--primary-color);
        }

        .progress-step:not(:last-child)::after {
            content: '→';
            margin-left: 1rem;
            color: var(--gray-300);
        }

        .categories-tree {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-lg);
            padding: 1rem;
            background: #f8f9fa;
        }

        .category-group {
            background: white;
            border-radius: var(--radius-md);
            padding: 0.75rem;
            border: 1px solid var(--gray-200);
        }

        .category-icon {
            width: 32px;
            height: 32px;
            border-radius: var(--radius-md);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }

        .category-children {
            border-left: 2px solid var(--gray-200);
            padding-left: 1rem;
            margin-top: 0.5rem;
        }

        .category-checkbox {
            border-radius: var(--radius-sm);
            cursor: pointer;
        }

        .form-check-label {
            cursor: pointer;
            user-select: none;
        }

        .alert {
            border-radius: var(--radius-lg);
            padding: 1rem;
            margin-bottom: 1.5rem;
            border: 1px solid;
        }

        .alert-info {
            background: #06b6d410;
            border-color: #06b6d430;
            color: #0c4a6e;
        }

        .alert-icon {
            margin-right: 0.5rem;
        }

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

            .form-card {
                padding: 1.5rem;
                border-radius: var(--radius-lg);
            }

            .duration-fields {
                grid-template-columns: 1fr;
            }

            .form-actions {
                flex-direction: column;
            }

            .btn-group {
                justify-content: stretch;
            }

            .btn-group .btn {
                flex: 1;
            }
        }

        /* Modern Marketplace Selector */
        .marketplace-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 1.25rem;
            margin-top: 1rem;
        }

        .marketplace-card {
            border: 2px solid var(--gray-200);
            border-radius: var(--radius-xl);
            padding: 1.25rem;
            background: white;
            cursor: pointer;
            transition: all 0.25s ease;
            position: relative;
            display: block;
            margin-bottom: 0;
            user-select: none;
        }

        .marketplace-card:hover {
            border-color: var(--primary-light);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .marketplace-card.selected {
            border-color: var(--primary-color);
            background: rgba(37, 99, 235, 0.03);
            box-shadow: 0 0 0 1px var(--primary-color), var(--shadow-sm);
        }

        .marketplace-card.selected .marketplace-icon-wrapper {
            background-color: var(--primary-color);
            color: white;
        }

        .marketplace-card.selected .marketplace-status-indicator {
            color: var(--primary-color);
            opacity: 1;
            transform: scale(1);
        }

        .marketplace-header-row {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-bottom: 1rem;
            position: relative;
        }

        .marketplace-icon-wrapper {
            width: 40px;
            height: 40px;
            border-radius: var(--radius-lg);
            background-color: var(--gray-100);
            color: var(--gray-600);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            transition: all 0.2s ease;
        }

        .marketplace-title-wrapper {
            display: flex;
            flex-direction: column;
            flex: 1;
        }

        .marketplace-name {
            font-weight: 700;
            font-size: 15px;
            color: var(--gray-900);
        }

        .marketplace-slug {
            font-size: 11px;
            margin-top: 0.1rem;
            color: var(--gray-500);
        }

        .marketplace-status-indicator {
            color: var(--gray-300);
            font-size: 18px;
            opacity: 0.5;
            transition: all 0.2s ease;
            transform: scale(0.9);
        }

        .marketplace-details {
            border-top: 1px dashed var(--gray-200);
            padding-top: 0.75rem;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .detail-item {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
        }

        .detail-label {
            font-size: 12px;
            font-weight: 600;
            color: var(--gray-500);
            display: flex;
            align-items: center;
        }

        .detail-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 0.25rem;
        }

        .detail-tags .badge {
            font-size: 10px;
            font-weight: 600;
            padding: 0.2rem 0.5rem;
            border-radius: var(--radius-sm);
        }
        
        .badge.bg-secondary-subtle {
            background-color: var(--gray-100) !important;
            color: var(--gray-700) !important;
            border: 1px solid var(--gray-200);
        }
        
        .badge.bg-primary-subtle {
            background-color: rgba(37, 99, 235, 0.1) !important;
            color: var(--primary-color) !important;
            border: 1px solid rgba(37, 99, 235, 0.2);
        }
    </style>
@endpush

@section('content')
    <div class="create-tour-container">
        <!-- Progress Indicator -->
        <div class="progress-indicator">
            <div class="progress-step active">
                <i class="fas fa-plus-circle"></i>
                Temel Bilgiler
            </div>
            <div class="progress-step">
                <i class="fas fa-edit"></i>
                Detay Düzenleme
            </div>
            <div class="progress-step">
                <i class="fas fa-check-circle"></i>
                Tamamlandı
            </div>
        </div>

        <div class="form-card">
            <!-- Form Header -->
            <div class="form-header">
                <h2>Yeni Tur Oluştur</h2>
                <p>Turunuzun temel bilgilerini girin. Detay bilgileri sonraki adımda ekleyebilirsiniz.</p>
            </div>

            <!-- Alert -->
            <div class="alert alert-info">
                <i class="fas fa-info-circle alert-icon"></i>
                Bu adımda sadece zorunlu bilgileri girmeniz yeterlidir. Tur oluşturulduktan sonra detay sayfasında tüm
                bilgileri düzenleyebilirsiniz.
            </div>

            <!-- Form -->
            <form method="POST" action="{{ route('agency.products.yurtdisi-turlari.store') }}" id="createTourForm">
                @csrf

                <!-- Marketplace Selection Section -->
                <div class="form-section">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h3 class="section-title mb-0">
                            <i class="fas fa-store section-icon"></i>
                            Pazar Seçimi
                        </h3>
                        <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#quickAddMarketplaceModal">
                            <i class="fas fa-plus me-1"></i> Hızlı Pazar Ekle
                        </button>
                    </div>
                    <div class="form-group">
                        <label class="form-label required">Aktif Pazarlar</label>
                        <div class="alert alert-info mb-3">
                            <i class="fas fa-info-circle alert-icon"></i>
                            <small>Bu turun yayınlanacağı ve satışa sunulacağı pazarlarını seçin. Pazarın desteklediği diller ve para birimleri aşağıda listelenmiştir.</small>
                        </div>
                        
                        <div class="marketplace-grid" id="marketplaceGrid">
                            @forelse($marketplaces as $mp)
                                <label class="marketplace-card" for="mp_{{ $mp->id }}" id="mpCard{{ $mp->id }}">
                                    <input class="marketplace-checkbox d-none" type="checkbox" name="marketplaces[]" value="{{ $mp->id }}" id="mp_{{ $mp->id }}" {{ in_array($mp->id, old('marketplaces', [])) ? 'checked' : '' }}>
                                    <div class="marketplace-card-content">
                                        <div class="marketplace-header-row">
                                            <div class="marketplace-icon-wrapper">
                                                <i class="fas fa-store"></i>
                                            </div>
                                            <div class="marketplace-title-wrapper">
                                                <span class="marketplace-name">{{ $mp->name }}</span>
                                                @if($mp->slug)
                                                    <span class="marketplace-slug">{{ $mp->slug }}</span>
                                                @endif
                                            </div>
                                            <div class="marketplace-status-indicator">
                                                <i class="fas fa-check-circle"></i>
                                            </div>
                                        </div>
                                        
                                        <div class="marketplace-details">
                                            <div class="detail-item">
                                                <span class="detail-label"><i class="fas fa-language me-1"></i> Desteklenen Diller:</span>
                                                <div class="detail-tags">
                                                    @forelse($mp->languages as $lang)
                                                        <span class="badge bg-secondary-subtle">{{ $lang->name }}</span>
                                                    @empty
                                                        <span class="text-muted small" style="font-size: 10px;">Belirtilmemiş</span>
                                                    @endforelse
                                                </div>
                                            </div>
                                            
                                            <div class="detail-item">
                                                <span class="detail-label"><i class="fas fa-money-bill-wave me-1"></i> Desteklenen Para Birimi:</span>
                                                <div class="detail-tags">
                                                    @if($mp->defaultCurrency)
                                                        <span class="badge bg-primary-subtle">{{ $mp->defaultCurrency->code }}</span>
                                                    @else
                                                        <span class="text-muted small" style="font-size: 10px;">Belirtilmemiş</span>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </label>
                            @empty
                                <div class="alert alert-warning w-100 mb-0" id="noMarketplacesAlert">
                                    <i class="fas fa-exclamation-triangle alert-icon"></i>
                                    Tanımlı aktif pazar bulunamadı. Lütfen önce pazar tanımlayın.
                                </div>
                            @endforelse
                        </div>

                        @error('marketplaces')
                            <div class="text-danger small mt-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>

                <!-- Categories Section -->
                <div class="form-section">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h3 class="section-title mb-0">
                            <i class="fas fa-tags section-icon"></i>
                            Kategoriler
                        </h3>
                        <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#quickAddCategoryModal">
                            <i class="fas fa-plus me-1"></i> Hızlı Kategori Ekle
                        </button>
                    </div>

                    <div id="categoriesContainer">
                        @if($categories->count() > 0)
                            <div class="form-group">
                                <label class="form-label">Tur Kategorileri <span class="text-muted">(Opsiyonel)</span></label>
                                <div class="alert alert-info mb-3">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <small>Kategori seçmezseniz tur doğrudan hizmet türüne eklenecektir.</small>
                                </div>
                                <div class="categories-tree" id="categoriesTree">
                                    @foreach($categories as $category)
                                        @if($category->parent_id)
                                            {{-- Alt kategorileri üst kategorileri altında listeliyoruz --}}
                                        @else
                                            <div class="category-group mb-3" id="categoryGroup{{ $category->id }}">
                                                <div class="category-master">
                                                    <div class="d-flex align-items-center mb-2">
                                                        <div class="category-icon me-2" style="background-color: {{ $category->color_code ?: '#3b82f6' }}15;">
                                                            <i class="fas {{ $category->icon ?: 'fa-folder' }}" style="color: {{ $category->color_code ?: '#3b82f6' }};"></i>
                                                        </div>
                                                        <div class="flex-grow-1">
                                                            <div class="form-check">
                                                                <input type="checkbox" name="categories[]" value="{{ $category->id }}"
                                                                       class="form-check-input category-checkbox"
                                                                       id="category{{ $category->id }}"
                                                                    {{ in_array($category->id, old('categories', [])) ? 'checked' : '' }}>
                                                                <label class="form-check-label fw-semibold" for="category{{ $category->id }}">
                                                                    {{ $category->name }}
                                                                </label>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <!-- Alt Kategoriler -->
                                                    <div class="category-children ms-4" id="categoryChildren{{ $category->id }}">
                                                        @foreach($categories->where('parent_id', $category->id) as $child)
                                                            <div class="form-check mb-2" id="categoryGroup{{ $child->id }}">
                                                                <input type="checkbox" name="categories[]" value="{{ $child->id }}"
                                                                       class="form-check-input category-checkbox"
                                                                       id="category{{ $child->id }}"
                                                                    {{ in_array($child->id, old('categories', [])) ? 'checked' : '' }}>
                                                                <label class="form-check-label" for="category{{ $child->id }}">
                                                                    <i class="fas fa-arrow-right text-muted me-1" style="font-size: 0.75rem;"></i>
                                                                    {{ $child->name }}
                                                                </label>
                                                            </div>
                                                        @endforeach
                                                    </div>
                                                </div>
                                            </div>
                                        @endif
                                    @endforeach
                                </div>
                                <div class="form-text text-muted">İsterseniz kategorisiz oluşturabilirsiniz</div>
                                @error('categories')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        @else
                            <div class="alert alert-warning" id="noCategoriesAlert">
                                <i class="fas fa-exclamation-triangle alert-icon"></i>
                                Henüz kategori oluşturmadınız.
                            </div>
                        @endif
                    </div>
                </div>

                <!-- Basic Information Section -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-info-circle section-icon"></i>
                        Temel Bilgiler
                    </h3>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-group">
                                <label class="form-label required">Tur Adı</label>
                                <input type="text" name="name" class="form-control"
                                       value="{{ old('name') }}"
                                       placeholder="Örn: İstanbul Şehir Turu" required>
                                <div class="form-text">Turunuzun çekici ve açıklayıcı bir adını girin</div>
                                @error('name')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label required">Tur Tipi</label>
                                <select name="tour_type" class="form-select" required>
                                    <option value="">Seçiniz</option>
                                    <option value="domestic" {{ old('tour_type') === 'domestic' ? 'selected' : '' }}>Yurt İçi
                                    </option>
                                    <option
                                        value="international" {{ old('tour_type') === 'international' ? 'selected' : '' }}>
                                        Yurt Dışı
                                    </option>
                                </select>
                                @error('tour_type')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label required">Kısa Açıklama</label>
                        <textarea name="short_description" class="form-control" rows="3"
                                  placeholder="Turunuzun kısa ve öz açıklamasını yazın..."
                                  required>{{ old('short_description') }}</textarea>
                        <div class="form-text">Maksimum 500 karakter</div>
                        @error('short_description')
                        <div class="text-danger small mt-1">{{ $message }}</div>
                        @enderror
                    </div>

                    <div class="form-group">
                        <label class="form-label required">Detaylı Açıklama</label>
                        <textarea name="description" class="form-control" rows="5"
                                  placeholder="Turunuzun detaylı açıklamasını yazın..."
                                  required>{{ old('description') }}</textarea>
                        <div class="form-text">Turunuzun tüm özelliklerini ve deneyimlerini açıklayın</div>
                        @error('description')
                        <div class="text-danger small mt-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>

                <!-- Location Section -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-map-marker-alt section-icon"></i>
                        Konum Bilgileri
                    </h3>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label required">Kalkış Şehri</label>
                                <select name="departure_city_id" class="form-select" required>
                                    <option value="">Şehir Seçiniz</option>
                                    @foreach($cities as $city)
                                        <option
                                            value="{{ $city->id }}" {{ old('departure_city_id') == $city->id ? 'selected' : '' }}>
                                            {{ $city->city }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('departure_city_id')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label required">Varış Şehri</label>
                                <select name="arrival_city_id" class="form-select" required>
                                    <option value="">Şehir Seçiniz</option>
                                    @foreach($cities as $city)
                                        <option
                                            value="{{ $city->id }}" {{ old('arrival_city_id') == $city->id ? 'selected' : '' }}>
                                            {{ $city->city }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('arrival_city_id')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Duration Section -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-clock section-icon"></i>
                        Süre Bilgileri
                    </h3>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label required">Gün Sayısı</label>
                                <input type="number" name="days" class="form-control"
                                       value="{{ old('days', 1) }}" min="1" required id="daysInput">
                                <div class="form-text">Turun toplam gün sayısını giriniz</div>
                                @error('days')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Gece Sayısı</label>
                                <input type="number" name="nights" class="form-control"
                                       value="{{ old('nights', 0) }}" min="0" id="nightsInput">
                                <div class="form-text">Otomatik hesaplanır, elle de değiştirebilirsiniz</div>
                                @error('nights')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Capacity Section -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-users section-icon"></i>
                        Kapasite Bilgileri
                    </h3>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label required">Minimum Katılımcı</label>
                                <input type="number" name="min_participants" class="form-control"
                                       value="{{ old('min_participants', 1) }}" min="1" required>
                                @error('min_participants')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Maksimum Katılımcı</label>
                                <input type="number" name="max_participants" class="form-control"
                                       value="{{ old('max_participants') }}" min="1">
                                <div class="form-text">Boş bırakırsanız sınırsız olur</div>
                                @error('max_participants')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Form Actions -->
                <div class="form-actions">
                    <div>
                        <a href="{{ route('agency.products.yurtdisi-turlari.index') }}" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left"></i> Geri Dön
                        </a>
                    </div>
                    <div class="btn-group">
                        <button type="submit" class="btn btn-primary" id="createBtn">
                            <i class="fas fa-save"></i> Tur Oluştur
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Quick Add Category Modal -->
    <div class="modal fade" id="quickAddCategoryModal" tabindex="-1" aria-labelledby="quickAddCategoryModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="quickAddCategoryForm">
                    @csrf
                    <input type="hidden" name="product_type_id" value="{{ $productTypeId }}">
                    <div class="modal-header">
                        <h5 class="modal-title" id="quickAddCategoryModalLabel">Hızlı Yeni Kategori Ekle</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Kapat"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="modal_category_name" class="form-label required">Kategori Adı</label>
                            <input type="text" class="form-control" id="modal_category_name" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="modal_parent_id" class="form-label">Üst Kategori</label>
                            <select class="form-select" id="modal_parent_id" name="parent_id">
                                <option value="">Ana Kategori (Üst Kategori Yok)</option>
                                @foreach($parentCategories as $parent)
                                    <option value="{{ $parent->id }}">{{ $parent->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="row">
                            <div class="col-6 mb-3">
                                <label for="modal_icon" class="form-label">İkon (Font Awesome)</label>
                                <input type="text" class="form-control" id="modal_icon" name="icon" value="fa-folder">
                            </div>
                            <div class="col-6 mb-3">
                                <label for="modal_color_code" class="form-label">Renk Kodu</label>
                                <input type="color" class="form-control form-control-color w-100" id="modal_color_code" name="color_code" value="#3b82f6">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                        <button type="submit" class="btn btn-primary" id="saveQuickCategoryBtn">
                            <i class="fas fa-save me-1"></i> Kaydet
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Quick Add Marketplace Modal -->
    <div class="modal fade" id="quickAddMarketplaceModal" tabindex="-1" aria-labelledby="quickAddMarketplaceModalLabel" aria-hidden="true" style="z-index: 1060;">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content" style="border-radius: 20px; border: none; box-shadow: 0 10px 30px rgba(0,0,0,0.15);">
                <div class="modal-header border-0 bg-light py-3" style="border-radius: 20px 20px 0 0;">
                    <h5 class="modal-title fw-bold text-dark" id="quickAddMarketplaceModalLabel"><i class="fas fa-plus-circle text-info me-2"></i>Hızlı Yeni Pazar Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="quickAddMarketplaceForm">
                    @csrf
                    <div class="modal-body p-4">
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label small fw-bold text-muted mb-1" style="font-size:0.75rem; text-transform:uppercase;">Pazar Adı *</label>
                                <input type="text" name="name" class="form-control" placeholder="Örn: Avrupa Pazarı" required style="border-radius: 8px;">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label small fw-bold text-muted mb-1" style="font-size:0.75rem; text-transform:uppercase;">Varsayılan Dil *</label>
                                <select name="default_language_id" class="form-select" required style="border-radius: 8px;">
                                    <option value="">Seçin...</option>
                                    @foreach($languages as $lang)
                                        <option value="{{ $lang->id }}">{{ $lang->name }} ({{ $lang->code }})</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label small fw-bold text-muted mb-1" style="font-size:0.75rem; text-transform:uppercase;">Para Birimi *</label>
                                <select name="default_currency_id" class="form-select" required style="border-radius: 8px;">
                                    <option value="">Seçin...</option>
                                    @foreach($currencies as $curr)
                                        <option value="{{ $curr->id }}">{{ $curr->code }} ({{ $curr->symbol }})</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="row mt-2">
                            <div class="col-md-12 mb-3">
                                <label class="form-label small fw-bold text-muted mb-2 d-block" style="font-size:0.75rem; text-transform:uppercase;">Hizmet Verilecek Diller *</label>
                                <div class="border p-3" style="border-radius: 8px; background: #fafafa;">
                                    <div class="input-group input-group-sm mb-2 shadow-sm" style="border-radius: 6px; overflow: hidden; border: 1px solid #dee2e6;">
                                        <span class="input-group-text border-0 bg-white"><i class="fas fa-search text-muted small"></i></span>
                                        <input type="text" class="form-control border-0 ps-0" id="quick_lang_search" placeholder="Dil ara..." style="font-size: 0.8rem; outline: none; box-shadow: none; background: #fff;">
                                    </div>
                                    <div class="quick-lang-list-container" style="max-height: 150px; overflow-y: auto; padding-right: 5px;">
                                        @foreach($languages as $lang)
                                            <div class="form-check mb-2 quick-lang-item">
                                                <input class="form-check-input" type="checkbox" name="languages[]" value="{{ $lang->id }}" id="quick_lang_{{ $lang->id }}">
                                                <label class="form-check-label text-dark small" for="quick_lang_{{ $lang->id }}">
                                                    {{ $lang->name }} ({{ $lang->code }})
                                                </label>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-check form-switch mt-2">
                            <input class="form-check-input" type="checkbox" name="is_active" id="quick_active" checked value="1">
                            <label class="form-check-label small fw-bold text-muted" for="quick_active">Pazarı Aktifleştir</label>
                        </div>
                    </div>
                    <div class="modal-footer border-0 bg-light py-3" style="border-radius: 0 0 20px 20px;">
                        <button type="button" class="btn btn-sm btn-secondary fw-bold px-3 py-2" data-bs-dismiss="modal" style="border-radius: 8px;">Vazgeç</button>
                        <button type="submit" class="btn btn-sm btn-primary fw-bold px-4 py-2" id="saveQuickMarketplaceBtn" style="border-radius: 8px; background: linear-gradient(135deg, #0ea5e9, #0284c7); border: none;">
                            <i class="fas fa-save me-1"></i> Kaydet
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const daysInput = document.getElementById('daysInput');
            const nightsInput = document.getElementById('nightsInput');
            const form = document.getElementById('createTourForm');

            // Gece sayısını otomatik hesapla (kullanıcı elle değiştirmediyse)
            let nightsManuallyChanged = false;

            nightsInput.addEventListener('input', function() {
                nightsManuallyChanged = true;
            });

            daysInput.addEventListener('input', function () {
                const days = parseInt(this.value) || 0;

                // Sadece kullanıcı elle değiştirmediyse otomatik hesapla
                if (!nightsManuallyChanged) {
                    const nights = Math.max(0, days - 1);
                    nightsInput.value = nights;
                }
            });

            // Kalkış şehrinden varış şehrini otomatik doldur
            const departureCitySelect = document.querySelector('select[name="departure_city_id"]');
            const arrivalCitySelect = document.querySelector('select[name="arrival_city_id"]');
            let arrivalCityManuallyChanged = false;

            if (arrivalCitySelect) {
                arrivalCitySelect.addEventListener('change', function() {
                    if (this.value) {
                        arrivalCityManuallyChanged = true;
                    }
                });
            }

            if (departureCitySelect) {
                departureCitySelect.addEventListener('change', function() {
                    // Sadece varış şehri elle değiştirilmediyse otomatik doldur
                    if (!arrivalCityManuallyChanged && this.value) {
                        arrivalCitySelect.value = this.value;
                    }
                });
            }

            // Form gönderim durumu
            const createBtn = document.getElementById('createBtn');
            form.addEventListener('submit', function (e) {
                // HTML5 form doğrulaması
                if (!form.checkValidity()) {
                    return;
                }

                // Doğrulama geçerse butonu devre dışı bırak
                createBtn.disabled = true;
                createBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Oluşturuluyor...';
            });

            // Sayfa yüklendiğinde gece sayısını hesapla
            if (daysInput.value) {
                daysInput.dispatchEvent(new Event('input'));
            }

            // Marketplace card selection styling toggle
            function initMarketplaceCard(card) {
                const checkbox = card.querySelector('.marketplace-checkbox');
                if (!checkbox) return;
                
                // Set initial state
                if (checkbox.checked) {
                    card.classList.add('selected');
                }
                
                checkbox.addEventListener('change', function() {
                    if (this.checked) {
                        card.classList.add('selected');
                    } else {
                        card.classList.remove('selected');
                    }
                });
            }
            document.querySelectorAll('.marketplace-card').forEach(initMarketplaceCard);

            // Quick Add Category Ajax
            const quickAddForm = document.getElementById('quickAddCategoryForm');
            if (quickAddForm) {
                quickAddForm.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    
                    const saveBtn = document.getElementById('saveQuickCategoryBtn');
                    const originalBtnHtml = saveBtn.innerHTML;
                    
                    // Show loading
                    saveBtn.disabled = true;
                    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Kaydediliyor...';
                    
                    const formData = new FormData(this);
                    
                    try {
                        const response = await fetch('{{ route("agency.categories.store") }}', {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest'
                            }
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            const newCategory = result.category;
                            
                            // 1. Close modal
                            const modalEl = document.getElementById('quickAddCategoryModal');
                            const modal = bootstrap.Modal.getInstance(modalEl);
                            modal.hide();
                            
                            // 2. Clear form
                            quickAddForm.reset();
                            
                            // 3. Make sure container exists (if list was empty)
                            let categoriesTree = document.getElementById('categoriesTree');
                            const categoriesContainer = document.getElementById('categoriesContainer');
                            const noCategoriesAlert = document.getElementById('noCategoriesAlert');
                            
                            if (noCategoriesAlert) {
                                noCategoriesAlert.classList.add('d-none');
                            }
                            
                            if (!categoriesTree) {
                                // If categories tree did not exist because count was 0
                                const treeHtml = `
                                    <div class="form-group">
                                        <label class="form-label">Tur Kategorileri <span class="text-muted">(Opsiyonel)</span></label>
                                        <div class="alert alert-info mb-3">
                                            <i class="fas fa-info-circle me-2"></i>
                                            <small>Kategori seçmezseniz tur doğrudan hizmet türüne eklenecektir.</small>
                                        </div>
                                        <div class="categories-tree" id="categoriesTree"></div>
                                        <div class="form-text text-muted">İsterseniz kategorisiz oluşturabilirsiniz</div>
                                    </div>
                                `;
                                categoriesContainer.innerHTML = treeHtml;
                                categoriesTree = document.getElementById('categoriesTree');
                            }
                            
                            // 4. Inject new category element into HTML
                            if (newCategory.parent_id) {
                                // Subcategory
                                const parentChildrenContainer = document.getElementById(`categoryChildren${newCategory.parent_id}`);
                                if (parentChildrenContainer) {
                                    const childHtml = `
                                        <div class="form-check mb-2" id="categoryGroup${newCategory.id}">
                                            <input type="checkbox" name="categories[]" value="${newCategory.id}"
                                                   class="form-check-input category-checkbox"
                                                   id="category${newCategory.id}" checked>
                                            <label class="form-check-label" for="category${newCategory.id}">
                                                <i class="fas fa-arrow-right text-muted me-1" style="font-size: 0.75rem;"></i>
                                                ${newCategory.name}
                                            </label>
                                        </div>
                                    `;
                                    parentChildrenContainer.insertAdjacentHTML('beforeend', childHtml);
                                }
                            } else {
                                // Root category
                                const rootHtml = `
                                    <div class="category-group mb-3" id="categoryGroup${newCategory.id}">
                                        <div class="category-master">
                                            <div class="d-flex align-items-center mb-2">
                                                <div class="category-icon me-2" style="background-color: ${newCategory.color_code || '#3b82f6'}15;">
                                                    <i class="fas ${newCategory.icon || 'fa-folder'}" style="color: ${newCategory.color_code || '#3b82f6'};"></i>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <div class="form-check">
                                                        <input type="checkbox" name="categories[]" value="${newCategory.id}"
                                                               class="form-check-input category-checkbox"
                                                               id="category${newCategory.id}" checked>
                                                        <label class="form-check-label fw-semibold" for="category${newCategory.id}">
                                                            ${newCategory.name}
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="category-children ms-4" id="categoryChildren${newCategory.id}"></div>
                                        </div>
                                    </div>
                                `;
                                categoriesTree.insertAdjacentHTML('beforeend', rootHtml);
                                
                                // Add to parent dropdown in modal for future quick adds
                                const parentSelect = document.getElementById('modal_parent_id');
                                if (parentSelect) {
                                    const option = document.createElement('option');
                                    option.value = newCategory.id;
                                    option.textContent = newCategory.name;
                                    parentSelect.appendChild(option);
                                }
                            }
                        } else {
                            alert(result.message || 'Kategori oluşturulurken bir hata oluştu.');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('Bir ağ hatası oluştu. Lütfen tekrar deneyin.');
                    } finally {
                        saveBtn.disabled = false;
                        saveBtn.innerHTML = originalBtnHtml;
                    }
                });
            }
            // Quick Add Marketplace Ajax
            const quickAddMarketplaceForm = document.getElementById('quickAddMarketplaceForm');
            if (quickAddMarketplaceForm) {
                quickAddMarketplaceForm.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    
                    const saveBtn = document.getElementById('saveQuickMarketplaceBtn');
                    const originalBtnHtml = saveBtn.innerHTML;
                    
                    // Show loading
                    saveBtn.disabled = true;
                    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Kaydediliyor...';
                    
                    const formData = new FormData(this);
                    
                    try {
                        const response = await fetch('{{ route("agency.settings.marketplaces.store") }}', {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest'
                            }
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            const mp = result.marketplace;
                            
                            // 1. Close modal
                            const modalEl = document.getElementById('quickAddMarketplaceModal');
                            const modal = bootstrap.Modal.getInstance(modalEl);
                            modal.hide();
                            
                            // 2. Clear form
                            quickAddMarketplaceForm.reset();
                            
                            // 3. Remove "no marketplaces" alert if exists
                            const noMpAlert = document.getElementById('noMarketplacesAlert');
                            if (noMpAlert) {
                                noMpAlert.remove();
                            }
                            
                            // 4. Build details tags for languages
                            let langTags = '';
                            if (mp.languages && mp.languages.length > 0) {
                                mp.languages.forEach(l => {
                                    langTags += `<span class="badge bg-secondary-subtle me-1">${l.name}</span>`;
                                });
                            } else {
                                langTags = '<span class="text-muted small" style="font-size: 10px;">Belirtilmemiş</span>';
                            }
                            
                            // 5. Build details tags for currency
                            let currTags = '';
                            if (mp.default_currency) {
                                currTags = `<span class="badge bg-primary-subtle me-1">${mp.default_currency.code}</span>`;
                            } else {
                                currTags = '<span class="text-muted small" style="font-size: 10px;">Belirtilmemiş</span>';
                            }
                            
                            // 6. Inject new card
                            const mpCardHtml = `
                                <label class="marketplace-card" for="mp_${mp.id}" id="mpCard${mp.id}">
                                    <input class="marketplace-checkbox d-none" type="checkbox" name="marketplaces[]" value="${mp.id}" id="mp_${mp.id}" checked>
                                    <div class="marketplace-card-content">
                                        <div class="marketplace-header-row">
                                            <div class="marketplace-icon-wrapper">
                                                <i class="fas fa-store"></i>
                                            </div>
                                            <div class="marketplace-title-wrapper">
                                                <span class="marketplace-name">${mp.name}</span>
                                                ${mp.slug ? `<span class="marketplace-slug">${mp.slug}</span>` : ''}
                                            </div>
                                            <div class="marketplace-status-indicator">
                                                <i class="fas fa-check-circle"></i>
                                            </div>
                                        </div>
                                        
                                        <div class="marketplace-details">
                                            <div class="detail-item">
                                                <span class="detail-label"><i class="fas fa-language me-1"></i> Desteklenen Diller:</span>
                                                <div class="detail-tags">${langTags}</div>
                                            </div>
                                            
                                            <div class="detail-item">
                                                <span class="detail-label"><i class="fas fa-money-bill-wave me-1"></i> Desteklenen Para Birimi:</span>
                                                <div class="detail-tags">${currTags}</div>
                                            </div>
                                        </div>
                                    </div>
                                </label>
                            `;
                            
                            const grid = document.getElementById('marketplaceGrid');
                            if (grid) {
                                grid.insertAdjacentHTML('beforeend', mpCardHtml);
                                
                                // 7. Initialize toggle style behavior on new card
                                const newCard = document.getElementById(`mpCard${mp.id}`);
                                initMarketplaceCard(newCard);
                            }
                        } else {
                            alert(result.message || 'Pazar oluşturulurken bir hata oluştu.');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('Bir ağ hatası oluştu. Lütfen tekrar deneyin.');
                    } finally {
                        saveBtn.disabled = false;
                        saveBtn.innerHTML = originalBtnHtml;
                    }
                });
                
                // Add modal search implementation
                const quickLangSearch = document.getElementById('quick_lang_search');
                if (quickLangSearch) {
                    quickLangSearch.addEventListener('input', function() {
                        const query = this.value.toLowerCase().trim();
                        document.querySelectorAll('.quick-lang-item').forEach(item => {
                            const label = item.querySelector('label').textContent.toLowerCase();
                            item.style.display = label.includes(query) ? 'block' : 'none';
                        });
                    });
                }
            }
        });
    </script>
@endpush
