<x-admin-layout>
    <x-slot name="header">
        <h1 class="text-2xl font-bold">Edit Tour</h1>
    </x-slot>

    <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
        <form action="{{ route('admin.tour_settings.update', $tour) }}" method="POST">
            @csrf
            @method('PUT')

            <div class="grid grid-cols-2 gap-6"> <!-- Two-column grid -->

                <!-- Tour Name -->
                <div>
                    <label for="name" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Tour Name</label>
                    <input type="text" id="name" name="name" value="{{ old('name', $tour->name) }}"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-500 focus:ring-opacity-50"
                    >
                </div>

                <!-- Time -->
                <div>
                    <label for="time" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Time</label>
                    <select id="time" name="time" class="select2 mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="">Please select an option</option>
                            <option value="custom" {{ old('time', $tour->time) == 'custom' ? 'selected' : '' }}>Custom</option>
                            <option value="fixed" {{ old('time', $tour->time) == 'fixed' ? 'selected' : '' }}>Fixed</option>
                    </select>
                </div>

                <!-- Start Time -->
                <div>
                    <label for="start_time" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Start Time</label>
                    <input type="time" id="start_time" name="start_time" value="{{ old('start_time', $tour->start_time) }}"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-500 focus:ring-opacity-50"
                    >
                </div>

                <!-- End Time -->
                <div>
                    <label for="end_time" class="block text-sm font-medium text-gray-700 dark:text-gray-200">End Time</label>
                    <input type="time" id="end_time" name="end_time" value="{{ old('end_time', $tour->end_time) }}"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-500 focus:ring-opacity-50"
                    >
                </div>

                <!-- Duration -->
                <div>
                    <label for="duration" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Duration</label>
                    <input type="number" id="duration" name="duration" value="{{ old('duration', $tour->duration) }}"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-500 focus:ring-opacity-50"
                    >
                </div>

                <!-- Region -->
                <div>
                    <label for="region_id" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Region</label>
                    <select id="region_id" name="region_id" class="select2 mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="">Select Region</option>
                        @foreach ($regions as $region)
                            <option value="{{ $region->id }}" {{ $tour->region_id == $region->id ? 'selected' : '' }}>
                                {{ $region->eng_name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <!-- Prefecture -->
                <div>
                    <label for="prefecture_id" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Prefecture</label>
                    <select id="prefecture_id" name="prefecture_id" class="select2 mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="">Select Prefecture</option>
                        @foreach ($tour->region->prefectures ?? [] as $prefecture)
                            <option value="{{ $prefecture->id }}" {{ $tour->prefecture_id == $prefecture->id ? 'selected' : '' }}>
                                {{ $prefecture->eng_name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <!-- City -->
                <div>
                    <label for="city_id" class="block text-sm font-medium text-gray-700 dark:text-gray-200">City</label>
                    {{-- <input type="text" value="{{ old('city_id', $tour->city_id) }}"> --}}
                    <select id="city_id" name="city_id" class="select2 mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="">Select City</option>
                        @foreach ($tour->prefecture->cities ?? [] as $city)
                            <option value="{{ $city->id }}" {{ $tour->city_id == $city->id ? 'selected' : '' }}>
                                {{ $city->eng_name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <!-- Operation Area -->
                <div>
                    <label for="operation_area" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Operation Area</label>
                    <input type="text" id="operation_area" name="operation_area" value="{{ old('operation_area', $tour->operation_area) }}"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-500 focus:ring-opacity-50"
                    >
                </div>

                <!-- Operation lat/lng -->
                <div>
                    <label for="operation_lat_lng" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Operation Lat/Long</label>
                    <input type="text" id="operation_lat_lng" name="operation_lat_lng" value="{{ old('operation_lat_lng', $tour->operation_lat_lng) }}"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-500 focus:ring-opacity-50"
                    >
                </div>

                <!-- Guide Fee -->
                <div>
                    <label for="guide_free" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Guide Fee</label>
                    <select id="guide_free" name="guide_free" class="select2 mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="">Please select an option</option>
                            <option value="dynamic" {{ old('guide_free', $tour->guide_free) == 'dynamic' ? 'selected' : '' }}>Dynamic</option>
                            <option value="fixed" {{ old('guide_free', $tour->guide_free) == 'fixed' ? 'selected' : '' }}>Fixed</option>
                    </select>
                </div>

                <!-- Manager -->
                <div>
                    <label for="manager" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Manager</label>
                    <select name="manager[]" id="manager" multiple class="select2 mt-1block w-full border border-gray-300 rounded-md shadow-sm">
                        @foreach($managers as $manager)
                            <option value="{{ $manager->id }}" {{ in_array($manager->id, old('manager', $tour->managers->pluck('id')->toArray() ?? [])) ? 'selected' : '' }}>
                                {{ $manager->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <!-- Link Form -->
                <div>
                    <label for="link_form" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Link Form</label>
                    <input type="url" id="link_form" name="link_form" value="{{ old('link_form', $tour->link_form) }}"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-500 focus:ring-opacity-50"
                    >
                </div>

                <!-- Tour Instructions -->
                <div>
                    <label for="tour_instructions" class="block text-sm font-medium text-gray-700 dark:text-gray-200">Tour Instructions</label>
                    <input type="text" id="tour_instructions" name="tour_instructions" value="{{ old('tour_instructions', $tour->tour_instructions) }}"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-500 focus:ring-opacity-50"
                    >
                </div>

                <!-- Tour Type & Rate -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-200">Tour Type & Rate</label>
                    <div id="tour-type-container">
                        @php
                            $tourTypes = json_decode($tourTypes, true) ?? [];
                        @endphp
                        @foreach ($tourTypes as $index => $tourType)
                        <div class="flex items-center space-x-4 tour-type-row">
                            <input type="text" name="tour_type[]" value="{{ old('tour_type.' . $index, $tourType['name']) }}" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <input type="number" name="rate[]" value="{{ old('rate.' . $index, $tourType['rate']) }}" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <button type="button" class="px-2 py-1 text-white bg-red-500 rounded-md remove-tour-type">−</button>
                        </div>
                        @endforeach
                        <!-- Default empty field -->
                        <div class="flex items-center space-x-4 tour-type-row">
                            <input type="text" name="tour_type[]" placeholder="Tour Type" class="w-full mt-1 border-gray-300 rounded-md shadow-sm">
                            <input type="number" name="rate[]" placeholder="Rate" class="w-full mt-1 border-gray-300 rounded-md shadow-sm">
                            <button type="button" class="px-2 py-1 text-white bg-green-500 rounded-md add-tour-type">+</button>
                        </div>
                    </div>
                </div>


                <!-- Meet Point & Lat/Long -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-200">Meet Point & Lat/Long</label>
                    <div id="meet-point-container">
                        @php
                            $meetPoints = json_decode($tour->meet_point, true) ?? [];
                            $meetLatLong = json_decode($tour->meet_lat_lng, true) ?? [];
                        @endphp

                    @foreach ($meetPoints as $index => $meetPoint)
                        <div class="flex items-center space-x-4 meet-point-row">
                            <input type="text" name="meet_point[]" value="{{ old('meet_point.' . $index, $meetPoint) }}"
                                class="w-full mt-1 border-gray-300 rounded-md shadow-sm">
                            <input type="text" name="meet_lat_lng[]" value="{{ old('meet_lat_lng.' . $index, $meetLatLong[$index]) }}"
                                class="w-full mt-1 border-gray-300 rounded-md shadow-sm">
                            <button type="button" class="px-2 py-1 text-white bg-red-500 rounded-md remove-meet-point">−</button>
                        </div>
                    @endforeach
                    <!-- Default empty field -->
                    <div class="flex items-center space-x-4 meet-point-row">
                        <input type="text" name="meet_point[]" placeholder="Meet Point" class="w-full mt-1 border-gray-300 rounded-md shadow-sm">
                        <input type="text" name="meet_lat_lng[]" placeholder="Meet Lat/Long" class="w-full mt-1 border-gray-300 rounded-md shadow-sm">
                        <button type="button" class="px-2 py-1 text-white bg-green-500 rounded-md add-meet-point">+</button>
                    </div>
                    </div>
                </div>

                <!-- Response Template -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Response Template</label>
                    <select name="response_template[]" id="response_template" multiple class="select2 mt-1block w-full border border-gray-300 rounded-md shadow-sm">
                        @foreach($groups as $group)
                            <option value="{{ $group->id }}" {{ in_array($group->id, old('response_template', $tour->groups->pluck('id')->toArray() ?? [])) ? 'selected' : '' }}>
                                {{ $group->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
            </div>
            <!-- Buttons -->
            <div class="flex items-center justify-between mt-6">
                <a href="{{ route('admin.tour_settings.index') }}" class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white">
                    Back to Tours List
                </a>
                <button type="submit" class="inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-md font-semibold text-white text-xs uppercase tracking-widest shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                    Update Tour
                </button>
            </div>

        </form>
    </div>
</x-admin-layout>

<style>
    .select2-container--default .select2-selection--single {
        border: 1px solid #d1d5db;
        border-radius: 0.375rem;
        height: 38px;
        padding: 6px 12px;
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
        color: #374151;
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 36px;
    }
</style>
<script>
    $(document).ready(function() {
        $('.select2').select2({ width: '100%' });

        var selectedPrefectureId = "{{ $tour->prefecture_id }}";
        var selectedCityId = "{{ $tour->city_id }}";

        $('#region_id').change(function() {
            var regionId = $(this).val();
            console.log("Region Changed, Fetching Prefectures for Region ID:", regionId);
            $('#prefecture_id').html('<option value="">Select Prefecture</option>');
            $('#city_id').html('<option value="">Select City</option>');

            if (regionId) {
                $.ajax({
                    url: "{{ route('get.prefectures') }}?region_id=" + regionId,
                    type: "GET",
                    success: function(data) {
                        $.each(data, function(key, value) {
                            var selected = value.id == selectedPrefectureId ? 'selected' : '';
                            $('#prefecture_id').append('<option value="' + value.id + '" ' + selected + '>' + value.eng_name + '</option>');
                        });
                        $('#prefecture_id').trigger('change');
                    }
                });
            }
        });

        $('#prefecture_id').change(function() {
            var prefectureId = $(this).val();
            $('#city_id').html('<option value="">Select City</option>');

            if (prefectureId) {
                $.ajax({
                    url: "{{ route('get.cities') }}?prefecture_id=" + prefectureId,
                    type: "GET",
                    success: function(data) {
                        console.log("Cities API Response:", data);
                        $.each(data, function(key, value) {
                            var selected = value.id == selectedCityId ? 'selected' : '';
                            $('#city_id').append('<option value="' + value.id + '" ' + selected + '>' + value.eng_name + '</option>');
                        });

                        // Manually trigger select2 update
                        $('#city_id').val(selectedCityId).trigger('change');
                        console.log($('#city_id').val());

                    }
                });
            }
        });

        $('#region_id').trigger('change');
    });


    document.addEventListener("DOMContentLoaded", function() {
        document.querySelector(".add-tour-type").addEventListener("click", function() {
            let container = document.getElementById("tour-type-container");
            let newInput = document.createElement("div");
            newInput.classList.add("flex", "items-center", "space-x-4", "mt-2");
            newInput.innerHTML = `
                <input type="text" name="tour_type[]" placeholder="Tour Type" class="block w-full border-gray-300 rounded-md shadow-sm" required>
                <input type="number" name="rate[]" placeholder="Rate" class="block w-full border-gray-300 rounded-md shadow-sm" required>
                <button type="button" class="remove-field px-2 py-1 text-white bg-red-500 rounded-md">-</button>
            `;
            container.appendChild(newInput);
        });

        document.getElementById("tour-type-container").addEventListener("click", function(e) {
            if (e.target.classList.contains("remove-field")) {
                e.target.parentElement.remove();
            }
        });

        document.querySelector(".add-meet-point").addEventListener("click", function() {
            let container = document.getElementById("meet-point-container");
            let newInput = document.createElement("div");
            newInput.classList.add("flex", "items-center", "space-x-4", "mt-2");
            newInput.innerHTML = `
                <input type="text" name="meet_point[]" placeholder="Meet Point" class="block w-full border-gray-300 rounded-md shadow-sm">
                <input type="text" name="meet_lat_lng[]" placeholder="Meet Lat/Long" class="block w-full border-gray-300 rounded-md shadow-sm">
                <button type="button" class="remove-field px-2 py-1 text-white bg-red-500 rounded-md">-</button>
            `;
            container.appendChild(newInput);
        });

        document.getElementById("meet-point-container").addEventListener("click", function(e) {
            if (e.target.classList.contains("remove-field")) {
                e.target.parentElement.remove();
            }
        });

    });
</script>
