@extends('admin.layouts.app')

@section('title', 'ویرایش مکان')

@section('styles')
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
    <style>
        #location-map {
            height: 400px;
            width: 100%;
            border-radius: 0.35rem;
            margin-bottom: 1rem;
        }
        .nested-select option {
            font-size: 14px;
        }
        .select-container {
            margin-bottom: 1rem;
        }
        .geo-select-container {
            border: 1px solid #e3e6f0;
            border-radius: 0.35rem;
            padding: 1rem;
            margin-bottom: 1rem;
            background-color: #f8f9fc;
        }
        .geo-select-container h6 {
            margin-bottom: 1rem;
            color: #4e73df;
        }
        .category-row {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 10px;
        }
        .category-row > div {
            flex: 1;
            min-width: 200px;
        }
    </style>
@endsection

@section('content')
<div class="container-fluid">
    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">ویرایش مکان: {{ $location->title }}</h1>
        <a href="{{ route('admin.locations.index') }}" class="d-none d-sm-inline-block btn btn-sm btn-secondary shadow-sm">
            <i class="fas fa-arrow-right fa-sm text-white-50 ml-1"></i> بازگشت به لیست
        </a>
    </div>

    <!-- Content Row -->
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">مشخصات مکان</h6>
        </div>
        <div class="card-body">
            <form action="{{ route('admin.locations.update', $location->id) }}" method="POST" enctype="multipart/form-data">
                @csrf
                <input type="hidden" name="_method" value="PUT">

                <div class="row">
                    <!-- اطلاعات پایه -->
                    <div class="col-md-6">
                        <div class="card mb-4">
                            <div class="card-header">
                                <h6 class="m-0 font-weight-bold text-primary">اطلاعات پایه</h6>
                            </div>
                            <div class="card-body">
                                <!-- نمایش خطاهای کلی -->
                                @if ($errors->any())
                                <div class="alert alert-danger mb-4">
                                    <ul class="mb-0">
                                        @foreach ($errors->all() as $error)
                                            <li>{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                                @endif

                                <div class="form-group">
                                    <label for="title">عنوان مکان <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('title') is-invalid @enderror" id="title" name="title" value="{{ old('title', $location->title) }}" required>
                                    @error('title')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="title_id">شناسه یکتا (به انگلیسی)</label>
                                    <input type="text" class="form-control @error('title_id') is-invalid @enderror" id="title_id" name="title_id" value="{{ old('title_id', $location->title_id) }}">
                                    <small class="form-text text-muted">بدون فاصله و حروف خاص. مثال: grand_hotel</small>
                                    @error('title_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label>دسته‌بندی <span class="text-danger">*</span></label>
                                    <div class="category-row">
                                        <div>
                                            <select class="form-control @error('parent_category_id') is-invalid @enderror" id="parent_category_id" name="parent_category_id">
                                                <option value="">انتخاب دسته‌بندی والد</option>
                                                @foreach($parentCategories as $id => $name)
                                                    <option value="{{ $id }}" {{ old('parent_category_id', $location->categoryRelation->parent_id ?? '') == $id ? 'selected' : '' }}>{{ $name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div>
                                            <select name="category_id" id="category_id" class="form-control @error('category_id') is-invalid @enderror">
                                                <option value="">انتخاب دسته‌بندی</option>
                                                @foreach($categories as $category)
                                                    <option value="{{ $category->id }}" {{ old('category_id', $location->category_id) == $category->id ? 'selected' : '' }}>
                                                        {{ $category->getTranslatedName(app()->getLocale()) }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    @error('category_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="description">توضیحات</label>
                                    <textarea class="form-control @error('description') is-invalid @enderror" id="description" name="description" rows="3">{{ old('description', $location->description) }}</textarea>
                                    @error('description')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="slogan">شعار</label>
                                    <input type="text" class="form-control @error('Slogan') is-invalid @enderror" id="slogan" name="Slogan" value="{{ old('Slogan', $location->Slogan) }}">
                                    @error('Slogan')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="emoji">ایموجی</label>
                                    <input type="text" class="form-control @error('emoji') is-invalid @enderror" id="emoji" name="emoji" value="{{ old('emoji', $location->emoji) }}">
                                    @error('emoji')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <div class="custom-control custom-switch">
                                        <input type="checkbox" class="custom-control-input" id="is_active" name="is_active" value="1" {{ old('is_active', $location->is_active) == '1' ? 'checked' : '' }}>
                                        <label class="custom-control-label" for="is_active">وضعیت فعال</label>
                                    </div>
                                </div>

                                <!-- تنظیمات پکیج تبلیغاتی -->
                                <div class="card mb-4 mt-4">
                                    <div class="card-header">
                                        <h6 class="m-0 font-weight-bold text-info">تنظیمات پکیج تبلیغاتی</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-group">
                                            <label for="package_type">نوع پکیج تبلیغاتی</label>
                                            <select class="form-control @error('package_type') is-invalid @enderror" id="package_type" name="package_type">
                                                <option value="regular" {{ old('package_type', $location->package_type) == 'regular' ? 'selected' : '' }}>معمولی (بدون پکیج)</option>
                                                <option value="bronze" {{ old('package_type', $location->package_type) == 'bronze' ? 'selected' : '' }}>برنزی</option>
                                                <option value="silver" {{ old('package_type', $location->package_type) == 'silver' ? 'selected' : '' }}>نقره‌ای</option>
                                                <option value="gold" {{ old('package_type', $location->package_type) == 'gold' ? 'selected' : '' }}>طلایی</option>
                                                <option value="diamond" {{ old('package_type', $location->package_type) == 'diamond' ? 'selected' : '' }}>الماسی</option>
                                            </select>
                                            @error('package_type')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                            <small class="form-text text-muted">با انتخاب پکیج تبلیغاتی، این مکان در بخش‌های ویژه سایت نمایش داده می‌شود.</small>
                                        </div>

                                        <div class="form-group">
                                            <label for="package_expires_at">تاریخ انقضای پکیج</label>
                                            <input type="date" class="form-control @error('package_expires_at') is-invalid @enderror" id="package_expires_at" name="package_expires_at" value="{{ old('package_expires_at', $location->package_expires_at ? date('Y-m-d', strtotime($location->package_expires_at)) : '') }}">
                                            @error('package_expires_at')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                            <small class="form-text text-muted">پس از این تاریخ، پکیج تبلیغاتی به حالت معمولی برمی‌گردد.</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- اطلاعات تماس و موقعیت -->
                    <div class="col-md-6">
                        <div class="card mb-4">
                            <div class="card-header">
                                <h6 class="m-0 font-weight-bold text-primary">اطلاعات تماس و موقعیت</h6>
                            </div>
                            <div class="card-body">
                                <div class="form-group">
                                    <label for="phone">شماره تماس</label>
                                    <input type="text" class="form-control @error('phone') is-invalid @enderror" id="phone" name="phone" value="{{ old('phone', $location->phone) }}">
                                    @error('phone')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="url">وب‌سایت</label>
                                    <input type="url" class="form-control @error('url') is-invalid @enderror" id="url" name="url" value="{{ old('url', $location->url) }}">
                                    @error('url')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="open_hours">ساعت شروع</label>
                                    <input type="text" class="form-control @error('open_hours') is-invalid @enderror" id="open_hours" name="open_hours" value="{{ old('open_hours', $location->open_hours) }}">
                                    @error('open_hours')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="closing_hours">ساعت پایان</label>
                                    <input type="text" class="form-control @error('closing_hours') is-invalid @enderror" id="closing_hours" name="closing_hours" value="{{ old('closing_hours', $location->closing_hours) }}">
                                    @error('closing_hours')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="country_id">کشور</label>
                                    <select class="form-control country-flag-select @error('country_id') is-invalid @enderror" id="country_id" name="country_id">
                                        <option value="">انتخاب کنید</option>
                                        @foreach($countries as $id => $name)
                                            @php
                                                $flag = '';
                                                if (is_object($name) && isset($name->flag)) $flag = $name->flag;
                                                elseif (is_array($name) && isset($name['flag'])) $flag = $name['flag'];
                                            @endphp
                                            <option value="{{ $id }}" {{ old('country_id', $location->country_id) == $id ? 'selected' : '' }}>
                                                {{ $flag }} {{ is_object($name) ? $name->name : (is_array($name) ? $name['name'] : $name) }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('country_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="province_id">استان</label>
                                    <select class="form-control @error('province_id') is-invalid @enderror" id="province_id" name="province_id">
                                        <option value="">انتخاب کنید</option>
                                        @foreach($provinces as $id => $name)
                                            <option value="{{ $id }}" {{ old('province_id', $location->province_id) == $id ? 'selected' : '' }}>{{ $name }}</option>
                                        @endforeach
                                    </select>
                                    @error('province_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="address">آدرس</label>
                                    <textarea class="form-control @error('address') is-invalid @enderror" id="address" name="address" rows="2">{{ old('address', $location->address) }}</textarea>
                                    @error('address')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="county_id">شهرستان</label>
                                    <select class="form-control @error('county_id') is-invalid @enderror" id="county_id" name="county_id">
                                        <option value="">انتخاب کنید</option>
                                        @foreach($counties as $id => $name)
                                            <option value="{{ $id }}" {{ old('county_id', $location->county_id) == $id ? 'selected' : '' }}>{{ $name }}</option>
                                        @endforeach
                                    </select>
                                    @error('county_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="district_id">بخش</label>
                                    <select class="form-control @error('district_id') is-invalid @enderror" id="district_id" name="district_id">
                                        <option value="">انتخاب کنید</option>
                                        @foreach($districts as $id => $name)
                                            <option value="{{ $id }}" {{ old('district_id', $location->district_id) == $id ? 'selected' : '' }}>{{ $name }}</option>
                                        @endforeach
                                    </select>
                                    @error('district_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="city_id">شهر</label>
                                    <select class="form-control @error('city_id') is-invalid @enderror" id="city_id" name="city_id">
                                        <option value="">انتخاب کنید</option>
                                        @foreach($cities as $id => $name)
                                            <option value="{{ $id }}" {{ old('city_id', $location->city_id) == $id ? 'selected' : '' }}>{{ $name }}</option>
                                        @endforeach
                                    </select>
                                    @error('city_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="village_id">روستا</label>
                                    <select class="form-control @error('village_id') is-invalid @enderror" id="village_id" name="village_id">
                                        <option value="">انتخاب کنید</option>
                                        @foreach($villages as $id => $name)
                                            <option value="{{ $id }}" {{ old('village_id', $location->village_id) == $id ? 'selected' : '' }}>{{ $name }}</option>
                                        @endforeach
                                    </select>
                                    @error('village_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="zone_id">منطقه</label>
                                    <select class="form-control @error('zone_id') is-invalid @enderror" id="zone_id" name="zone_id">
                                        <option value="">انتخاب کنید</option>
                                        @foreach($zones as $id => $name)
                                            <option value="{{ $id }}" {{ old('zone_id', $location->zone_id) == $id ? 'selected' : '' }}>{{ $name }}</option>
                                        @endforeach
                                    </select>
                                    @error('zone_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="lat">عرض جغرافیایی</label>
                                            <input type="text" class="form-control @error('lat') is-invalid @enderror" id="lat" name="lat" value="{{ old('lat', $location->lat) }}">
                                            @error('lat')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="lng">طول جغرافیایی</label>
                                            <input type="text" class="form-control @error('lng') is-invalid @enderror" id="lng" name="lng" value="{{ old('lng', $location->lng) }}">
                                            @error('lng')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                    </div>
                                </div>

                                <!-- Map container -->
                                <div class="form-group">
                                    <label>موقعیت روی نقشه</label>
                                    <div id="location-map"></div>
                                    <small class="form-text text-muted">برای انتخاب مکان روی نقشه کلیک کنید</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- امکانات -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="m-0 font-weight-bold text-primary">امکانات</h6>
                    </div>
                    <div class="card-body">
                        @php
                            $locationAmenities = $location->amenities ? json_decode($location->amenities, true) : [];
                        @endphp

                        @foreach($amenityTypes as $type)
                            <h6 class="mt-3 mb-2">{{ $type->type_name }}</h6>
                            <div class="row mb-2">
                                @foreach($amenities->where('type_id', $type->id) as $amenity)
                                    <div class="col-md-3 mb-2">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="amenity{{ $amenity->id }}" name="amenities[]" value="{{ $amenity->id }}"
                                            {{ (old('amenities') && in_array($amenity->id, old('amenities'))) ||
                                                (isset($locationAmenities[$amenity->id]) || isset($locationAmenities[$amenity->id.""]) || array_key_exists($amenity->id, $locationAmenities)) ? 'checked' : '' }}>
                                            <label class="custom-control-label" for="amenity{{ $amenity->id }}">
                                                <i class="{{ $amenity->icon }}"></i> {{ $amenity->title }}
                                            </label>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @endforeach
                    </div>
                </div>

                <!-- تصاویر و تگ‌ها -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="m-0 font-weight-bold text-primary">تصاویر و تگ‌ها</h6>
                    </div>
                    <div class="card-body">
                        @if($location->images)
                            <div class="mb-4">
                                <h6 class="mb-3">تصاویر موجود:</h6>
                                <div class="row">
                                    @php
                                        $images = $location->images_array;
                                    @endphp

                                    @foreach($images as $index => $image)
                                        @if(!empty($image))
                                        <div class="col-md-3 mb-3">
                                            <div class="card">
                                                <img src="{{ asset('storage/' . $image) }}" alt="تصویر {{ $index + 1 }}" class="card-img-top" style="height: 200px; object-fit: cover;">
                                                <div class="card-body p-2">
                                                    <div class="custom-control custom-checkbox">
                                                        <input type="checkbox" class="custom-control-input" id="remove_image_{{ $index }}" name="remove_images[]" value="{{ $image }}">
                                                        <label class="custom-control-label" for="remove_image_{{ $index }}">حذف تصویر</label>
                                                    </div>
                                                    <small class="text-muted d-block mt-1">{{ basename($image) }}</small>
                                                </div>
                                            </div>
                                        </div>
                                        @endif
                                    @endforeach
                                </div>
                            </div>
                        @endif

                        <div class="form-group">
                            <label for="images">آپلود تصاویر جدید</label>
                            <input type="file" class="form-control-file @error('images') is-invalid @enderror" id="images" name="images[]" multiple>
                            <small class="form-text text-muted">می‌توانید چند تصویر را همزمان انتخاب کنید</small>
                            @error('images')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="form-group">
                            <label for="tags">برچسب‌ها</label>
                            <input type="text" class="form-control @error('tags') is-invalid @enderror" id="tags" name="tags" value="{{ old('tags', $location->tags) }}">
                            <small class="form-text text-muted">برچسب‌ها را با کاما جدا کنید</small>
                            @error('tags')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>

                <!-- دکمه‌های ثبت -->
                <div class="text-left">
                    <button type="submit" class="btn btn-primary">بروزرسانی اطلاعات</button>
                    <a href="{{ route('admin.locations.index') }}" class="btn btn-secondary">انصراف</a>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script src="{{ asset('js/hierarchical-selects.js') }}"></script>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script src="{{ asset('js/boundary-display.js') }}"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize map only if it hasn't been initialized before
        if (!window.map) {
            window.map = L.map('location-map').setView([35.6892, 51.3890], 13);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(window.map);
        }

        var marker;
        @if($location->lat && $location->lng)
            marker = L.marker([{{ $location->lat }}, {{ $location->lng }}]).addTo(window.map);
        @endif

        // Handle map click
        window.map.on('click', function(e) {
            if (marker) {
                window.map.removeLayer(marker);
            }
            marker = L.marker(e.latlng).addTo(window.map);
            document.getElementById('lat').value = e.latlng.lat;
            document.getElementById('lng').value = e.latlng.lng;
        });

        // Handle category dependencies
        const parentCategorySelect = document.getElementById('parent_category_id');
        const childCategorySelect = document.getElementById('category_id');

        if (parentCategorySelect && childCategorySelect) {
            parentCategorySelect.addEventListener('change', function() {
                var parentId = this.value;

                // Clear current options
                childCategorySelect.innerHTML = '<option value="">انتخاب دسته‌بندی فرزند</option>';

                if (parentId) {
                    // Fetch child categories
                    fetch(`/admin/api/categories/${parentId}/children`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(data => {
                            data.forEach(category => {
                                var option = document.createElement('option');
                                option.value = category.id;
                                option.textContent = category.name;
                                childCategorySelect.appendChild(option);
                            });
                        })
                        .catch(error => {
                            console.error('Error fetching child categories:', error);
                        });
                }
            });

            // Trigger change event if parent category is already selected
            if (parentCategorySelect.value) {
                parentCategorySelect.dispatchEvent(new Event('change'));
            }
        }

        // Handle geographical area dependencies
        const countrySelect = document.getElementById('country_id');
        const provinceSelect = document.getElementById('province_id');
        const countySelect = document.getElementById('county_id');
        const districtSelect = document.getElementById('district_id');
        const citySelect = document.getElementById('city_id');
        const villageSelect = document.getElementById('village_id');
        const zoneSelect = document.getElementById('zone_id');

        if (countrySelect) {
            countrySelect.addEventListener('change', function() {
                var countryId = this.value;

                // Clear dependent selects
                clearSelect(provinceSelect);
                clearSelect(countySelect);
                clearSelect(districtSelect);
                clearSelect(citySelect);
                clearSelect(villageSelect);
                clearSelect(zoneSelect);

                if (countryId) {
                    fetch(`/admin/api/geography/provinces/${countryId}`)
                        .then(response => response.json())
                        .then(data => {
                            data.forEach(province => {
                                var option = document.createElement('option');
                                option.value = province.id;
                                option.textContent = province.name;
                                provinceSelect.appendChild(option);
                            });
                        });
                }
            });
        }

        // Add similar event listeners for other geographical selects...
        // (Keep the existing event listeners for province, county, district, city, village, and zone)

        function clearSelect(select) {
            if (select) {
                select.innerHTML = '<option value="">انتخاب کنید</option>';
            }
        }
    });
</script>
@endsection