@extends('layouts.admin')

@section('title', 'CEYLON THARU TRAVELS | EDIT ITINERARY')

@section('content_admin')
    <div class="content-wrapper">
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>Edit Itinerary for {{ $package->title }}</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="{{ route('packages.index') }}">Packages</a></li>
                            <li class="breadcrumb-item"><a
                                    href="{{ route('packages.itineraries', $package->id) }}">Itineraries</a></li>
                            <li class="breadcrumb-item active">Edit</li>
                        </ol>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="container-fluid">
                @if (session('success'))
                    <div class="alert alert-success alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                        {{ session('success') }}
                    </div>
                @endif

                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Edit Itinerary</h3>
                    </div>
                    <form action="{{ route('packages.itineraries.update', [$package->id, $itinerary->id]) }}" method="POST"
                        enctype="multipart/form-data">
                        @csrf
                        @method('PUT')
                        <div class="card-body">
                            <div class="form-group">
                                <label for="day_number">Day Number</label>
                                <select name="day_number" id="day_number" class="form-control" required>
                                    @for ($i = 1; $i <= 10; $i++)
                                        <option value="{{ $i }}"
                                            {{ $itinerary->day_number == $i ? 'selected' : '' }}>{{ $i }}
                                        </option>
                                    @endfor
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="title">Title</label>
                                <input type="text" name="title" id="title" class="form-control"
                                    value="{{ $itinerary->title }}" required>
                                @error('title')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div class="form-group">
                                <label for="map_url">Location</label>
                                <div id="map" style="height: 300px;"></div>
                                <input type="hidden" name="map_url" id="map_url" class="form-control"
                                    value="{{ $itinerary->map_url }}">
                                @error('map_url')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div class="form-group">
                                <label>Images</label>
                                @if (isset($itinerary->images) && $itinerary->images->isNotEmpty())
                                    <div class="row">
                                        @foreach ($itinerary->images as $image)
                                            <div class="col-md-4 mb-3">
                                                <div class="card">
                                                    <div class="card-body text-center">
                                                        <img src="{{ Storage::url($image->image_path) }}"
                                                            class="img-fluid mb-2" style="max-height: 150px;"
                                                            alt="{{ $image->caption ?? 'Itinerary Image' }}">

                                                        {{-- Show existing caption editable per image --}}
                                                        <div class="form-group">
                                                            <label
                                                                for="caption_existing_{{ $image->id }}">Caption</label>
                                                            <input type="text"
                                                                name="existing_captions[{{ $image->id }}]"
                                                                id="caption_existing_{{ $image->id }}"
                                                                class="form-control" value="{{ $image->caption }}">
                                                        </div>

                                                        {{-- Allow replacing this specific image (optional). If left empty, keep existing image. --}}
                                                        <div class="form-group mt-2">
                                                            <label for="replace_image_{{ $image->id }}">Replace Image
                                                                (optional)</label>
                                                            <input type="file"
                                                                name="replace_images[{{ $image->id }}]"
                                                                id="replace_image_{{ $image->id }}"
                                                                class="form-control-file" accept="image/*">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                @else
                                    <p class="text-muted">No images uploaded for this itinerary.</p>
                                @endif

                                {{-- Keep ability to upload additional new images (if fewer than 3 existing). --}}
                                <div class="mt-3">
                                    <label>Add New Images (optional, up to 3 total)</label>
                                    <div class="row">
                                        @for ($i = 0; $i < 3; $i++)
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="new_image_{{ $i }}">New Image
                                                        {{ $i + 1 }}</label>
                                                    <input type="file" name="new_images[]"
                                                        id="new_image_{{ $i }}" class="form-control-file"
                                                        accept="image/*">
                                                </div>
                                                <div class="form-group">
                                                    <label for="new_caption_{{ $i }}">Caption (optional)</label>
                                                    <input type="text" name="new_captions[]"
                                                        id="new_caption_{{ $i }}" class="form-control">
                                                </div>
                                            </div>
                                        @endfor
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">Update Itinerary</button>
                            <a href="{{ route('packages.itineraries', $package->id) }}"
                                class="btn btn-secondary">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>
        </section>
    </div>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        // Initialize map for editing itinerary
        (function() {
            // Try to parse server-side and pass a safe JSON string to JS to avoid quoting issues
            var safeCoords = @json($itinerary->map_url ? json_decode($itinerary->map_url) : null);

            // Fallback coordinates if none provided (center of Sri Lanka)
            var defaultCoords = {
                lat: 7.8731,
                lng: 80.7718
            };
            var coords = safeCoords && safeCoords.lat && safeCoords.lng ? safeCoords : defaultCoords;

            var map = L.map('map').setView([coords.lat, coords.lng], 10);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);

            var marker = L.marker([coords.lat, coords.lng]).addTo(map);
            var coordinates = {
                lat: coords.lat,
                lng: coords.lng
            };

            map.on('click', function(e) {
                coordinates = e.latlng;
                marker.setLatLng(coordinates);
                document.getElementById('map_url').value = JSON.stringify(coordinates);
            });
        })();
    </script>
@endsection
