@extends('agency.layouts.app')

@section('title', $tour->name . ' - Tur Programı')
@section('page_title', 'Tur Düzenle')

@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' => 'Program', 'url' => '']
    ];
@endphp

@push('styles')
    <link href="https://cdn.jsdelivr.net/npm/quill@2.0.0/dist/quill.snow.css" rel="stylesheet">
    <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;
        }

        .day-card {
            background: white;
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-lg);
            margin-bottom: 1.5rem;
            overflow: hidden;
        }

        .day-header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: white;
            padding: 1rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .day-title {
            font-size: 1.2rem;
            font-weight: 600;
            margin: 0;
        }

        .day-content {
            padding: 1.5rem;
        }

        .itinerary-item {
            background: var(--gray-50);
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-lg);
            padding: 1rem;
            margin-bottom: 1rem;
            position: relative;
        }

        .itinerary-item:last-child {
            margin-bottom: 0;
        }

        .itinerary-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 0.5rem;
        }

        .itinerary-title {
            font-weight: 600;
            font-size: 1.1rem;
            color: var(--gray-900);
            flex: 1;
        }

        .itinerary-actions {
            display: flex;
            gap: 0.5rem;
        }

        .itinerary-description {
            color: var(--gray-700);
            margin-bottom: 0.5rem;
            line-height: 1.6;
        }

        .itinerary-location {
            color: var(--gray-600);
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .empty-state {
            text-align: center;
            padding: 3rem;
            color: var(--gray-500);
        }

        .quill-editor {
            background: white;
            border-radius: var(--radius-lg);
        }

        .ql-toolbar.ql-snow {
            border-top-left-radius: var(--radius-lg);
            border-top-right-radius: var(--radius-lg);
            background: var(--gray-50);
            border: 1px solid var(--gray-300);
        }

        .ql-container.ql-snow {
            border-bottom-left-radius: var(--radius-lg);
            border-bottom-right-radius: var(--radius-lg);
            min-height: 150px;
            border: 1px solid var(--gray-300);
            border-top: 0;
        }

        .add-program-btn {
            position: sticky;
            top: 20px;
            z-index: 10;
        }
    </style>
@endpush

@section('content')
    <div class="tour-detail-container">
        <!-- Tour Header -->
        <div class="tour-header">
            <div class="tour-header-content">
                <h1 class="tour-title">{{ $tour->name }}</h1>
                <div class="tour-code">Tur Kodu: {{ $tour->code }}</div>
                <div class="tour-meta">
                    <div class="tour-meta-item">
                        <i class="fas fa-calendar tour-meta-icon"></i>
                        <span>{{ $tour->days }} Gün {{ $tour->nights }} Gece</span>
                    </div>
                    <div class="tour-meta-item">
                        <i class="fas fa-map-marker-alt tour-meta-icon"></i>
                        <span>{{ $tour->departureCity?->name ?? 'Belirtilmemiş' }}</span>
                    </div>
                    @if($tour->tour_type)
                        <div class="tour-meta-item">
                            <i class="fas fa-tag tour-meta-icon"></i>
                            <span>{{ $tour->tour_type_display_name }}</span>
                        </div>
                    @endif
                </div>
            </div>
        </div>

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

            <!-- Tab Content -->
            <div class="tab-content">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h4 class="mb-0">Tur Programı</h4>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addItineraryModal">
                        <i class="fas fa-plus me-2"></i>Program Ekle
                    </button>
                </div>

                <!-- Itineraries by Day -->
                @if($itineraries->count() > 0)
                    @foreach($itineraries as $dayNumber => $dayItineraries)
                        <div class="day-card">
                            <div class="day-header">
                                <h3 class="day-title">
                                    <i class="fas fa-calendar-day me-2"></i>
                                    {{ $dayNumber }}. Gün
                                </h3>
                                <button type="button" class="btn btn-sm btn-light" onclick="addItineraryForDay({{ $dayNumber }})">
                                    <i class="fas fa-plus me-1"></i>Ekle
                                </button>
                            </div>
                            <div class="day-content">
                                @foreach($dayItineraries as $itinerary)
                                    <div class="itinerary-item">
                                        <div class="itinerary-header">
                                            <div class="itinerary-title">{{ $itinerary->title }}</div>
                                            <div class="itinerary-actions">
                                                <button type="button" class="btn btn-sm btn-outline-primary"
                                                        onclick="editItinerary({{ $itinerary->id }})">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-danger"
                                                        onclick="deleteItinerary({{ $itinerary->id }})">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                        @if($itinerary->description)
                                            <div class="itinerary-description">{!! $itinerary->description !!}</div>
                                        @endif
                                        @if($itinerary->location)
                                            <div class="itinerary-location">
                                                <i class="fas fa-map-marker-alt"></i>
                                                {{ $itinerary->location }}
                                            </div>
                                        @endif
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    @endforeach
                @else
                    <div class="empty-state">
                        <i class="fas fa-calendar-alt fa-3x mb-3 text-muted"></i>
                        <h5>Henüz program eklenmemiş</h5>
                        <p class="text-muted">Başlamak için yukarıdaki "Program Ekle" butonuna tıklayın</p>
                    </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Add/Edit Itinerary Modal -->
    <div class="modal fade" id="addItineraryModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Program Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="itineraryForm">
                    <div class="modal-body">
                        <input type="hidden" id="itinerary_id">

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="day_number" class="form-label">Gün <span class="text-danger">*</span></label>
                                <select class="form-select" id="day_number" name="day_number" required>
                                    @for($i = 1; $i <= $tour->days; $i++)
                                        <option value="{{ $i }}">{{ $i }}. Gün</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="title" class="form-label">Başlık <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="title" name="title" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="location" class="form-label">Konum / Şehir</label>
                            <input type="text" class="form-control" id="location" name="location"
                                   placeholder="Örn: İstanbul, Sultanahmet Meydanı">
                        </div>

                        <div class="mb-3">
                            <label for="description" class="form-label">Açıklama</label>
                            <div class="quill-editor" id="editor-description"></div>
                            <input type="hidden" id="description" name="description">
                        </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">
                            <i class="fas fa-save me-2"></i>Kaydet
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/quill@2.0.0/dist/quill.js"></script>
    <script>
        let descriptionEditor;
        const tourId = {{ $tour->id }};

        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Quill editor
            const toolbarOptions = [
                [{ 'header': [1, 2, 3, false] }],
                ['bold', 'italic', 'underline'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                ['link'],
                ['clean']
            ];

            descriptionEditor = new Quill('#editor-description', {
                theme: 'snow',
                modules: { toolbar: toolbarOptions },
                placeholder: 'Program açıklamasını buraya yazın...'
            });

            const descriptionInput = document.getElementById('description');
            descriptionEditor.on('text-change', function() {
                descriptionInput.value = descriptionEditor.root.innerHTML;
            });

            // Form submit
            document.getElementById('itineraryForm').addEventListener('submit', function(e) {
                e.preventDefault();
                saveItinerary();
            });

            // Modal reset on hide
            document.getElementById('addItineraryModal').addEventListener('hidden.bs.modal', function() {
                resetForm();
            });
        });

        function addItineraryForDay(dayNumber) {
            resetForm();
            document.getElementById('day_number').value = dayNumber;
            new bootstrap.Modal(document.getElementById('addItineraryModal')).show();
        }

        function editItinerary(id) {
            fetch(`/agency/products/yurtdisi-turlari/${tourId}/itinerary/${id}/edit`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('modalTitle').textContent = 'Program Düzenle';
                        document.getElementById('itinerary_id').value = data.itinerary.id;
                        document.getElementById('day_number').value = data.itinerary.day_number;
                        document.getElementById('title').value = data.itinerary.title;
                        document.getElementById('location').value = data.itinerary.location || '';

                        if (data.itinerary.description) {
                            descriptionEditor.root.innerHTML = data.itinerary.description;
                            document.getElementById('description').value = data.itinerary.description;
                        }

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

        function saveItinerary() {
            const itineraryId = document.getElementById('itinerary_id').value;
            const formData = new FormData(document.getElementById('itineraryForm'));
            const data = Object.fromEntries(formData.entries());

            const url = itineraryId
                ? `/agency/products/yurtdisi-turlari/${tourId}/itinerary/${itineraryId}`
                : `/agency/products/yurtdisi-turlari/${tourId}/itinerary`;

            const method = itineraryId ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    AgencyPanel.showNotification(data.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    AgencyPanel.showNotification(data.message || 'Bir hata oluştu', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                AgencyPanel.showNotification('Bir hata oluştu', 'error');
            });
        }

        function deleteItinerary(id) {
            if (!confirm('Bu programı silmek istediğinize emin misiniz?')) {
                return;
            }

            fetch(`/agency/products/yurtdisi-turlari/${tourId}/itinerary/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    AgencyPanel.showNotification(data.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    AgencyPanel.showNotification(data.message || 'Bir hata oluştu', 'error');
                }
            });
        }

        function resetForm() {
            document.getElementById('modalTitle').textContent = 'Program Ekle';
            document.getElementById('itineraryForm').reset();
            document.getElementById('itinerary_id').value = '';
            descriptionEditor.root.innerHTML = '';
            document.getElementById('description').value = '';
        }
    </script>
@endpush
