@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' => 'Kültür Turları', 'url' => route('agency.products.kultur-turlari.index')],
        ['title' => 'Yeni Tur', 'url' => '']
    ];
@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;
            }
        }
    </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.kultur-turlari.store') }}" id="createTourForm">
                @csrf

                <!-- 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">Konaklama Türü</label>
                                <select name="accommodation_type" class="form-select" required id="accommodationType">
                                    <option value="">Seçiniz</option>
                                    <option
                                        value="day_trip" {{ old('accommodation_type') === 'day_trip' ? 'selected' : '' }}>
                                        Günübirlik
                                    </option>
                                    <option
                                        value="with_accommodation" {{ old('accommodation_type') === 'with_accommodation' ? 'selected' : '' }}>
                                        Konaklamalı
                                    </option>
                                </select>
                                @error('accommodation_type')
                                <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">Süre Türü</label>
                                <select name="duration_type" class="form-select" required id="durationType">
                                    <option value="">Seçiniz</option>
                                    <option value="hours" {{ old('duration_type') === 'hours' ? 'selected' : '' }}>
                                        Saat
                                    </option>
                                    <option value="days" {{ old('duration_type') === 'days' ? 'selected' : '' }}>Gün
                                    </option>
                                </select>
                                @error('duration_type')
                                <div class="text-danger small mt-1">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="duration-fields">
                        <div class="form-group">
                            <label class="form-label required">Süre</label>
                            <input type="number" name="duration" class="form-control"
                                   value="{{ old('duration') }}" min="1" required>
                            @error('duration')
                            <div class="text-danger small mt-1">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="form-group" id="daysField" style="display: none;">
                            <label class="form-label">Gün Sayısı</label>
                            <input type="number" name="days" class="form-control"
                                   value="{{ old('days') }}" min="1">
                            @error('days')
                            <div class="text-danger small mt-1">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="form-group" id="nightsField" style="display: none;">
                            <label class="form-label">Gece Sayısı</label>
                            <input type="number" name="nights" class="form-control"
                                   value="{{ old('nights') }}" min="0">
                            <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>

                <!-- 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>

                <!-- Categories Section -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-tags section-icon"></i>
                        Kategoriler
                    </h3>

                    @if($categories->count() > 0)
                        <div class="form-group">
                            <label class="form-label required">Tur Kategorileri</label>
                            <div class="alert alert-info mb-3">
                                <i class="fas fa-info-circle me-2"></i>
                                <small>Ana kategorilere ve kendi oluşturduğunuz alt kategorilere tur ekleyebilirsiniz.</small>
                            </div>
                            <div class="categories-tree">
                                @foreach($categories as $category)
                                    @if($category->is_master_category)
                                        <!-- Ana Kategori -->
                                        <div class="category-group mb-3">
                                            <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 }}15;">
                                                        <i class="fas fa-{{ $category->icon }}" style="color: {{ $category->color_code }};"></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-bold" for="category{{ $category->id }}">
                                                                {{ $category->name }}
                                                                <span class="badge bg-warning bg-opacity-75 text-dark ms-2" style="font-size: 0.65rem;">
                                                                    <i class="fas fa-star me-1"></i>Ana Kategori
                                                                </span>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Alt Kategoriler -->
                                                @if(isset($category->agencyChildren) && $category->agencyChildren->count() > 0)
                                                    <div class="category-children ms-4">
                                                        @foreach($category->agencyChildren as $child)
                                                            <div class="form-check mb-2">
                                                                <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>
                                                @endif
                                            </div>
                                        </div>
                                    @elseif(!$category->master_category_id)
                                        <!-- Bağımsız Acente Kategorisi -->
                                        <div class="category-group mb-3">
                                            <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 }}">
                                                    <i class="fas fa-folder text-primary me-2"></i>
                                                    {{ $category->name }}
                                                </label>
                                            </div>
                                        </div>
                                    @endif
                                @endforeach
                            </div>
                            <div class="form-text">En az bir kategori seçmelisiniz</div>
                            @error('categories')
                            <div class="text-danger small mt-1">{{ $message }}</div>
                            @enderror
                        </div>
                    @else
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle alert-icon"></i>
                            Henüz kategori oluşturmadınız. <a href="{{ route('agency.tour-categories.create') }}"
                                                              target="_blank">Buradan</a> kategori oluşturabilirsiniz.
                        </div>
                    @endif
                </div>

                <!-- Form Actions -->
                <div class="form-actions">
                    <div>
                        <a href="{{ route('agency.products.kultur-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>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const accommodationType = document.getElementById('accommodationType');
            const durationType = document.getElementById('durationType');
            const daysField = document.getElementById('daysField');
            const nightsField = document.getElementById('nightsField');
            const daysInput = document.querySelector('input[name="days"]');
            const nightsInput = document.querySelector('input[name="nights"]');
            const durationInput = document.querySelector('input[name="duration"]');

            // Show/hide fields based on accommodation type
            accommodationType.addEventListener('change', function () {
                if (this.value === 'with_accommodation') {
                    durationType.value = 'days';
                    durationType.dispatchEvent(new Event('change'));
                } else if (this.value === 'day_trip') {
                    durationType.value = 'hours';
                    durationType.dispatchEvent(new Event('change'));
                }
            });

            // Show/hide duration fields based on duration type
            durationType.addEventListener('change', function () {
                if (this.value === 'days') {
                    daysField.style.display = 'block';
                    nightsField.style.display = 'block';
                    daysInput.required = true;
                } else {
                    daysField.style.display = 'none';
                    nightsField.style.display = 'none';
                    daysInput.required = false;
                    daysInput.value = '';
                    nightsInput.value = '';
                }
            });

            // Auto-calculate nights (only if user hasn't manually changed it)
            let nightsManuallyChanged = false;

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

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

                // Only auto-calculate if user hasn't manually changed nights
                if (!nightsManuallyChanged) {
                    const nights = Math.max(0, days - 1);
                    nightsInput.value = nights;
                }

                if (durationType.value === 'days') {
                    durationInput.value = days;
                }
            });

            // Sync duration with days field
            durationInput.addEventListener('input', function () {
                if (durationType.value === 'days') {
                    daysInput.value = this.value;
                    nightsManuallyChanged = false; // Reset manual change flag
                    daysInput.dispatchEvent(new Event('input'));
                }
            });

            // Auto-fill arrival city from departure city
            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() {
                    // Only auto-fill if arrival city hasn't been manually changed
                    if (!arrivalCityManuallyChanged && this.value) {
                        arrivalCitySelect.value = this.value;
                    }
                });
            }

            // Category validation
            const categoryCheckboxes = document.querySelectorAll('input[name="categories[]"]');
            const form = document.getElementById('createTourForm');

            form.addEventListener('submit', function (e) {
                const checkedCategories = Array.from(categoryCheckboxes).filter(cb => cb.checked);

                if (checkedCategories.length === 0) {
                    e.preventDefault();
                    alert('En az bir kategori seçmelisiniz!');
                    return false;
                }
            });

            // Initialize fields based on old values
            if (accommodationType.value) {
                accommodationType.dispatchEvent(new Event('change'));
            }
            if (durationType.value) {
                durationType.dispatchEvent(new Event('change'));
            }
            if (daysInput.value && durationType.value === 'days') {
                daysInput.dispatchEvent(new Event('input'));
            }

            // Loading state for form submission
            const createBtn = document.getElementById('createBtn');
            form.addEventListener('submit', function (e) {
                // Only disable if validation passes
                const checkedCategories = Array.from(categoryCheckboxes).filter(cb => cb.checked);

                if (checkedCategories.length === 0) {
                    return; // Let the earlier validation handler take care of it
                }

                // Check HTML5 form validity
                if (!form.checkValidity()) {
                    return; // Let browser validation handle it
                }

                // If all validations pass, disable button and show loading state
                createBtn.disabled = true;
                createBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Oluşturuluyor...';
            });
        });
    </script>
@endpush
