@extends('agency.layouts.app')

@section('title', $tour->name . ' - Görseller')
@section('page_title', 'Tur Görselleri')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        .tab-content {
            padding: 2rem;
        }

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

        .upload-methods {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
            background: var(--gray-50);
            padding: 1rem;
            border-radius: var(--radius-lg);
        }

        .upload-method-btn {
            flex: 1;
            padding: 1.5rem;
            border: 2px dashed var(--gray-300);
            border-radius: var(--radius-lg);
            background: white;
            cursor: pointer;
            transition: var(--transition);
            text-align: center;
        }

        .upload-method-btn:hover {
            border-color: var(--primary-color);
            background: var(--primary-light);
        }

        .upload-method-btn.active {
            border-color: var(--primary-color);
            border-style: solid;
            background: var(--primary-light);
        }

        .upload-method-icon {
            font-size: 32px;
            color: var(--primary-color);
            margin-bottom: 0.5rem;
        }

        .upload-method-title {
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 0.25rem;
        }

        .upload-method-desc {
            font-size: 13px;
            color: var(--gray-600);
        }

        .upload-area {
            display: none;
            margin-bottom: 2rem;
        }

        .upload-area.active {
            display: block;
        }

        .file-upload-zone {
            border: 2px dashed var(--gray-300);
            border-radius: var(--radius-lg);
            padding: 3rem;
            text-align: center;
            background: var(--gray-50);
            cursor: pointer;
            transition: var(--transition);
        }

        .file-upload-zone:hover,
        .file-upload-zone.dragover {
            border-color: var(--primary-color);
            background: var(--primary-light);
        }

        .file-upload-icon {
            font-size: 48px;
            color: var(--primary-color);
            margin-bottom: 1rem;
        }

        .file-upload-text {
            font-size: 16px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 0.5rem;
        }

        .file-upload-hint {
            font-size: 14px;
            color: var(--gray-600);
        }

        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .gallery-item {
            position: relative;
            aspect-ratio: 1;
            border-radius: var(--radius-lg);
            overflow: hidden;
            cursor: pointer;
            border: 3px solid transparent;
            transition: var(--transition);
        }

        .gallery-item:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .gallery-item.selected {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2);
        }

        .gallery-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .gallery-item-checkbox {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            width: 24px;
            height: 24px;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: var(--shadow-sm);
            opacity: 0;
            transition: var(--transition);
        }

        .gallery-item:hover .gallery-item-checkbox,
        .gallery-item.selected .gallery-item-checkbox {
            opacity: 1;
        }

        .gallery-item.selected .gallery-item-checkbox {
            background: var(--primary-color);
            color: white;
        }

        .image-type-selector {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }

        .image-type-btn {
            flex: 1;
            padding: 0.75rem;
            border: 2px solid var(--gray-300);
            border-radius: var(--radius-md);
            background: white;
            cursor: pointer;
            transition: var(--transition);
            text-align: center;
            font-size: 14px;
            font-weight: 500;
        }

        .image-type-btn:hover {
            border-color: var(--primary-color);
        }

        .image-type-btn.active {
            border-color: var(--primary-color);
            background: var(--primary-color);
            color: white;
        }

        .tour-images-section {
            margin-top: 3rem;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--gray-200);
        }

        .section-title {
            font-size: 20px;
            font-weight: 700;
            color: var(--gray-900);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .section-count {
            font-size: 14px;
            color: var(--gray-600);
            background: var(--gray-100);
            padding: 0.25rem 0.75rem;
            border-radius: var(--radius-full);
        }

        .images-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1.5rem;
        }

        .image-card {
            background: white;
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-lg);
            overflow: hidden;
            transition: var(--transition);
            position: relative;
        }

        .image-card:hover {
            box-shadow: var(--shadow-lg);
            transform: translateY(-4px);
        }

        .image-card-img {
            width: 100%;
            aspect-ratio: 16/9;
            object-fit: cover;
            background: var(--gray-100);
        }

        .image-card-body {
            padding: 1rem;
        }

        .image-card-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 0.75rem;
        }

        .image-badge {
            position: absolute;
            top: 0.5rem;
            left: 0.5rem;
            padding: 0.25rem 0.75rem;
            border-radius: var(--radius-md);
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            background: rgba(0, 0, 0, 0.7);
            color: white;
        }

        .image-badge.cover {
            background: var(--success-color);
        }

        .image-badge.featured {
            background: var(--warning-color);
        }

        .image-card-info {
            font-size: 12px;
            color: var(--gray-600);
            margin-top: 0.5rem;
        }

        .drag-handle {
            cursor: move;
            color: var(--gray-400);
            margin-right: 0.5rem;
        }

        .sortable-ghost {
            opacity: 0.4;
        }

        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            background: var(--gray-50);
            border: 2px dashed var(--gray-300);
            border-radius: var(--radius-xl);
        }

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

        .empty-state-title {
            font-size: 20px;
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
        }

        .empty-state-text {
            color: var(--gray-600);
            margin-bottom: 1.5rem;
        }

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

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

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

            .tour-meta {
                gap: 1rem;
            }

            .tab-content {
                padding: 1.5rem;
            }

            .upload-methods {
                flex-direction: column;
            }

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

            .gallery-grid {
                grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
                gap: 0.5rem;
            }

            .images-grid {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                gap: 1rem;
            }
        }
    </style>
@endpush

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

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

            <!-- Tab Content -->
            <div class="tab-content">
                <div class="media-header">
                    <div>
                        <h3>Tur Görselleri</h3>
                        <p class="text-muted mb-0">Turunuz için görseller ekleyin ve yönetin</p>
                    </div>
                </div>

                <!-- Upload Methods -->
                <div class="upload-methods">
                    <div class="upload-method-btn" onclick="selectUploadMethod('gallery')" data-method="gallery">
                        <div class="upload-method-icon">
                            <i class="fas fa-folder-open"></i>
                        </div>
                        <div class="upload-method-title">Galeriden Seç</div>
                        <div class="upload-method-desc">Mevcut görsellerden seçim yapın</div>
                    </div>
                    <div class="upload-method-btn" onclick="selectUploadMethod('upload')" data-method="upload">
                        <div class="upload-method-icon">
                            <i class="fas fa-cloud-upload-alt"></i>
                        </div>
                        <div class="upload-method-title">Yeni Yükle</div>
                        <div class="upload-method-desc">Bilgisayarınızdan görsel yükleyin</div>
                    </div>
                </div>

                <!-- Image Type Selector -->
                <div class="image-type-selector">
                    <div class="image-type-btn active" data-type="gallery" onclick="selectImageType('gallery')">
                        <i class="fas fa-images me-1"></i> Galeri
                    </div>
                    <div class="image-type-btn" data-type="featured" onclick="selectImageType('featured')">
                        <i class="fas fa-star me-1"></i> Öne Çıkan
                    </div>
                    <div class="image-type-btn" data-type="cover" onclick="selectImageType('cover')">
                        <i class="fas fa-image me-1"></i> Kapak
                    </div>
                    <div class="image-type-btn" data-type="thumbnail" onclick="selectImageType('thumbnail')">
                        <i class="fas fa-th me-1"></i> Thumbnail
                    </div>
                </div>

                <!-- Gallery Selection Area -->
                <div class="upload-area active" id="galleryArea">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <span id="selectedCount">0</span> görsel seçildi
                        </div>
                        <button class="btn btn-primary" onclick="addSelectedImages()" id="addImagesBtn" disabled>
                            <i class="fas fa-plus"></i> Seçili Görselleri Ekle
                        </button>
                    </div>

                    @if($availableImages->count() > 0)
                        <div class="gallery-grid">
                            @foreach($availableImages as $image)
                                <div class="gallery-item" data-image-id="{{ $image->id }}"
                                     onclick="toggleImageSelection({{ $image->id }})">
                                    <img src="{{ $image->thumbnail_url }}" alt="{{ $image->title }}">
                                    <div class="gallery-item-checkbox">
                                        <i class="fas fa-check"></i>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @else
                        <div class="empty-state">
                            <div class="empty-state-icon">
                                <i class="fas fa-images"></i>
                            </div>
                            <div class="empty-state-title">Galerinizde görsel bulunamadı</div>
                            <div class="empty-state-text">Önce galeri bölümünden görsel yükleyebilir veya doğrudan yeni
                                görsel yükleyebilirsiniz
                            </div>
                        </div>
                    @endif
                </div>

                <!-- File Upload Area -->
                <div class="upload-area" id="uploadArea">
                    <form id="fileUploadForm" enctype="multipart/form-data">
                        @csrf
                        <div class="file-upload-zone" id="dropZone">
                            <input type="file" id="fileInput" name="files[]" multiple accept="image/*"
                                   style="display: none;">
                            <div class="file-upload-icon">
                                <i class="fas fa-cloud-upload-alt"></i>
                            </div>
                            <div class="file-upload-text">Görselleri sürükleyip bırakın</div>
                            <div class="file-upload-hint">veya tıklayarak dosya seçin (JPEG, PNG, WEBP - Max 10MB)</div>
                        </div>
                        <div id="filePreview" class="gallery-grid mt-3" style="display: none;"></div>
                        <div class="text-center mt-3">
                            <button type="button" class="btn btn-primary" onclick="uploadFiles()" id="uploadBtn"
                                    style="display: none;">
                                <i class="fas fa-upload"></i> Yükle ve Ekle
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Current Tour Images -->
                <div class="tour-images-section">
                    @foreach(['cover' => 'Kapak Görseli', 'featured' => 'Öne Çıkan Görseller', 'gallery' => 'Galeri Görselleri', 'thumbnail' => 'Thumbnail Görseller'] as $type => $title)
                        @php
                            $images = $tourImages->get($type, collect());
                        @endphp

                        @if($images->count() > 0 || $type === 'cover')
                            <div class="mb-4">
                                <div class="section-header">
                                    <div class="section-title">
                                        {{ $title }}
                                        <span class="section-count">{{ $images->count() }}</span>
                                    </div>
                                </div>

                                @if($images->count() > 0)
                                    <div class="images-grid sortable-grid" data-type="{{ $type }}">
                                        @foreach($images as $tourImage)
                                            <div class="image-card" data-id="{{ $tourImage->id }}">
                                                @if($tourImage->is_cover)
                                                    <span class="image-badge cover">KAPAK</span>
                                                @elseif($tourImage->is_featured)
                                                    <span class="image-badge featured">ÖNE ÇIKAN</span>
                                                @endif

                                                <img src="{{ $tourImage->thumbnail_url }}"
                                                     alt="{{ $tourImage->display_title }}" class="image-card-img">

                                                <div class="image-card-body">
                                                    <div class="d-flex align-items-start">
                                                        <i class="fas fa-grip-vertical drag-handle"></i>
                                                        <div class="flex-grow-1">
                                                            <div class="image-card-info">
                                                                {{ $tourImage->galleryImage->formatted_file_size }} •
                                                                {{ $tourImage->galleryImage->width }}
                                                                x{{ $tourImage->galleryImage->height }}
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="image-card-actions">
                                                        @if($type !== 'cover')
                                                            <button type="button"
                                                                    class="btn btn-sm btn-outline-success flex-grow-1"
                                                                    onclick="setCover({{ $tourImage->id }})"
                                                                    title="Kapak Yap">
                                                                <i class="fas fa-image"></i>
                                                            </button>
                                                        @endif
                                                        <button type="button"
                                                                class="btn btn-sm btn-outline-warning flex-grow-1"
                                                                onclick="toggleFeatured({{ $tourImage->id }})"
                                                                title="{{ $tourImage->is_featured ? 'Öne Çıkarma' : 'Öne Çıkar' }}">
                                                            <i class="fas fa-star"></i>
                                                        </button>
                                                        <button type="button"
                                                                class="btn btn-sm btn-outline-danger flex-grow-1"
                                                                onclick="deleteImage({{ $tourImage->id }})" title="Sil">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                @else
                                    <div class="empty-state">
                                        <div class="empty-state-icon">
                                            <i class="fas fa-image"></i>
                                        </div>
                                        <div class="empty-state-title">Henüz kapak görseli eklenmemiş</div>
                                        <div class="empty-state-text">Yukarıdan görsel ekleyerek başlayın</div>
                                    </div>
                                @endif
                            </div>
                        @endif
                    @endforeach
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
    <script>
        let selectedImages = new Set();
        let currentImageType = 'gallery';
        let currentUploadMethod = null;

        function selectUploadMethod(method) {
            currentUploadMethod = method;

            document.querySelectorAll('.upload-method-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            document.querySelector(`[data-method="${method}"]`).classList.add('active');

            document.querySelectorAll('.upload-area').forEach(area => {
                area.classList.remove('active');
            });

            document.getElementById(method === 'gallery' ? 'galleryArea' : 'uploadArea').classList.add('active');
        }

        function selectImageType(type) {
            currentImageType = type;

            document.querySelectorAll('.image-type-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            document.querySelector(`[data-type="${type}"]`).classList.add('active');
        }

        function toggleImageSelection(imageId) {
            const item = document.querySelector(`[data-image-id="${imageId}"]`);

            if (selectedImages.has(imageId)) {
                selectedImages.delete(imageId);
                item.classList.remove('selected');
            } else {
                selectedImages.add(imageId);
                item.classList.add('selected');
            }

            updateSelectedCount();
        }

        function updateSelectedCount() {
            document.getElementById('selectedCount').textContent = selectedImages.size;
            document.getElementById('addImagesBtn').disabled = selectedImages.size === 0;
        }

        function addSelectedImages() {
            if (selectedImages.size === 0) return;

            const formData = new FormData();
            formData.append('_token', document.querySelector('[name="_token"]').value);
            formData.append('image_type', currentImageType);

            selectedImages.forEach(id => {
                formData.append('images[]', id);
            });

            fetch('{{ route('agency.products.yurtdisi-turlari.media.upload-images', $tour) }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        if (data.errors) {
                            let errorMsg = '';
                            Object.values(data.errors).forEach(errors => {
                                errors.forEach(error => {
                                    errorMsg += error + '\n';
                                });
                            });
                            alert(errorMsg);
                        } else {
                            alert(data.message || 'Görseller eklenirken bir hata oluştu.');
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Bir hata oluştu: ' + error.message);
                });
        }

        // File Upload with Drag & Drop
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const filePreview = document.getElementById('filePreview');
        const uploadBtn = document.getElementById('uploadBtn');

        dropZone.addEventListener('click', () => fileInput.click());

        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('dragover');
        });

        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('dragover');
        });

        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('dragover');

            const files = e.dataTransfer.files;
            fileInput.files = files;
            handleFiles(files);
        });

        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });

        function handleFiles(files) {
            filePreview.innerHTML = '';
            filePreview.style.display = 'grid';
            uploadBtn.style.display = 'inline-block';

            Array.from(files).forEach(file => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const div = document.createElement('div');
                        div.className = 'gallery-item';
                        div.innerHTML = `<img src="${e.target.result}" alt="${file.name}">`;
                        filePreview.appendChild(div);
                    };
                    reader.readAsDataURL(file);
                }
            });
        }

        function uploadFiles() {
            const files = fileInput.files;
            if (files.length === 0) return;

            const formData = new FormData();
            formData.append('_token', document.querySelector('[name="_token"]').value);
            formData.append('image_type', currentImageType);

            Array.from(files).forEach(file => {
                formData.append('files[]', file);
            });

            uploadBtn.disabled = true;
            uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Yükleniyor...';

            fetch('{{ route('agency.products.yurtdisi-turlari.media.upload-images', $tour) }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        uploadBtn.disabled = false;
                        uploadBtn.innerHTML = '<i class="fas fa-upload"></i> Yükle ve Ekle';

                        if (data.errors) {
                            let errorMsg = '';
                            Object.values(data.errors).forEach(errors => {
                                errors.forEach(error => {
                                    errorMsg += error + '\n';
                                });
                            });
                            alert(errorMsg);
                        } else {
                            alert(data.message || 'Görseller yüklenirken bir hata oluştu.');
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    uploadBtn.disabled = false;
                    uploadBtn.innerHTML = '<i class="fas fa-upload"></i> Yükle ve Ekle';
                    alert('Bir hata oluştu: ' + error.message);
                });
        }

        function deleteImage(tourImageId) {
            if (!confirm('Bu görseli kaldırmak istediğinizden emin misiniz?')) {
                return;
            }

            fetch(`{{ route('agency.products.yurtdisi-turlari.media', $tour) }}/images/${tourImageId}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value,
                    'Content-Type': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        alert(data.message || 'Görsel kaldırılırken bir hata oluştu.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Bir hata oluştu.');
                });
        }

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

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

        // Initialize Sortable for image reordering
        document.querySelectorAll('.sortable-grid').forEach(grid => {
            const sortable = new Sortable(grid, {
                animation: 150,
                handle: '.drag-handle',
                ghostClass: 'sortable-ghost',
                onEnd: function (evt) {
                    const imageType = grid.dataset.type;
                    const images = Array.from(grid.querySelectorAll('.image-card')).map((card, index) => ({
                        id: parseInt(card.dataset.id),
                        sort_order: index
                    }));

                    reorderImages(images);
                }
            });
        });

        function reorderImages(images) {
            fetch('{{ route('agency.products.yurtdisi-turlari.media.reorder-images', $tour) }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({images})
            })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        alert(data.message || 'Sıralama güncellenirken bir hata oluştu.');
                        window.location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Bir hata oluştu.');
                    window.location.reload();
                });
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function () {
            selectUploadMethod('gallery');
        });
    </script>
@endpush
