@extends('layouts.app')

@section('title', 'Edit Property')

@section('content')
<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Edit Property</h1>
                </div>
                <div class="col-sm-6">
                    <div class="float-sm-right">
                        <a href="{{ route('properties.index') }}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Properties
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">
                        <i class="fas fa-edit"></i> Edit Property: {{ $property->title }}
                    </h3>
                </div>
                <div class="card-body">
                    <form method="POST" action="{{ route('properties.update', $property) }}" enctype="multipart/form-data">
                        @csrf
                        @method('PUT')

                        <div class="row">
                            <!-- Basic Information -->
                            <div class="col-md-8">
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title">Basic Information</h4>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label for="title" class="font-weight-bold">Property Title *</label>
                                                    <input type="text" 
                                                           name="title" 
                                                           id="title" 
                                                           value="{{ old('title', $property->title) }}"
                                                           class="form-control @error('title') is-invalid @enderror"
                                                           placeholder="Enter property title"
                                                           required>
                                                    @error('title')
                                                        <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="type" class="font-weight-bold">Property Type *</label>
                                                    <select name="type" 
                                                            id="type" 
                                                            class="form-control @error('type') is-invalid @enderror"
                                                            required>
                                                        <option value="">Select Property Type</option>
                                                        @foreach($types as $key => $name)
                                                            <option value="{{ $key }}" {{ old('type', $property->type) == $key ? 'selected' : '' }}>
                                                                {{ $name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                    @error('type')
                                                        <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="area" class="font-weight-bold">Area (m²) *</label>
                                                    <input type="number" 
                                                           name="area" 
                                                           id="area" 
                                                           value="{{ old('area', $property->area) }}"
                                                           class="form-control @error('area') is-invalid @enderror"
                                                           placeholder="Enter area in square meters"
                                                           step="0.01"
                                                           min="1"
                                                           required>
                                                    @error('area')
                                                        <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="bedrooms" class="font-weight-bold">Bedrooms *</label>
                                                    <input type="number" 
                                                           name="bedrooms" 
                                                           id="bedrooms" 
                                                           value="{{ old('bedrooms', $property->bedrooms) }}"
                                                           class="form-control @error('bedrooms') is-invalid @enderror"
                                                           placeholder="Number of bedrooms"
                                                           min="0"
                                                           max="50"
                                                           required>
                                                    @error('bedrooms')
                                                        <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="bathrooms" class="font-weight-bold">Bathrooms *</label>
                                                    <input type="number" 
                                                           name="bathrooms" 
                                                           id="bathrooms" 
                                                           value="{{ old('bathrooms', $property->bathrooms) }}"
                                                           class="form-control @error('bathrooms') is-invalid @enderror"
                                                           placeholder="Number of bathrooms"
                                                           min="0"
                                                           max="50"
                                                           required>
                                                    @error('bathrooms')
                                                        <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </div>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="short_description" class="font-weight-bold">Short Description *</label>
                                            <textarea name="short_description" 
                                                      id="short_description" 
                                                      rows="3"
                                                      class="form-control @error('short_description') is-invalid @enderror"
                                                      placeholder="Brief description of the property"
                                                      required>{{ old('short_description', $property->short_description) }}</textarea>
                                            @error('short_description')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>

                                        <div class="form-group">
                                            <label for="full_description" class="font-weight-bold">Full Description *</label>
                                            <textarea name="full_description" 
                                                      id="full_description" 
                                                      rows="6"
                                                      class="form-control @error('full_description') is-invalid @enderror"
                                                      placeholder="Detailed description of the property">{{ old('full_description', $property->full_description) }}</textarea>
                                            @error('full_description')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Images and Settings -->
                            <div class="col-md-4">
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title">Images & Settings</h4>
                                    </div>
                                    <div class="card-body">
                                        <!-- Current Card Image -->
                                        @if($property->card_image)
                                            <div class="form-group">
                                                <label class="font-weight-bold">Current Card Image</label>
                                                <div class="text-center mb-3">
                                                    <img src="{{ $property->card_image_url }}" 
                                                         alt="{{ $property->title }}" 
                                                         class="img-thumbnail" 
                                                         style="max-width: 200px; max-height: 150px;">
                                                </div>
                                            </div>
                                        @endif

                                        <div class="form-group">
                                            <label for="card_image" class="font-weight-bold">
                                                {{ $property->card_image ? 'Update Card Image' : 'Card Image *' }}
                                            </label>
                                            <input type="file" 
                                                   name="card_image" 
                                                   id="card_image" 
                                                   class="form-control @error('card_image') is-invalid @enderror"
                                                   accept="image/jpeg,image/png,image/jpg,image/webp"
                                                   {{ !$property->card_image ? 'required' : '' }}>
                                            <small class="form-text text-muted">Main property image. Max size: 2MB. Formats: JPEG, PNG, JPG, WebP</small>
                                            @error('card_image')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>

                                        <!-- Current Gallery Images -->
                                        @if($property->gallery && count($property->gallery) > 0)
                                            <div class="form-group">
                                                <label class="font-weight-bold">Current Gallery Images</label>
                                                <div class="row">
                                                    @foreach($property->gallery as $index => $image)
                                                        <div class="col-6 mb-2">
                                                            <div class="position-relative">
                                                                <img src="{{ asset('storage/' . $image) }}" 
                                                                     alt="Gallery image {{ $index + 1 }}" 
                                                                     class="img-thumbnail" 
                                                                     style="width: 100%; height: 80px; object-fit: cover;">
                                                                <div class="position-absolute top-0 end-0">
                                                                    <button type="button" 
                                                                            class="btn btn-sm btn-danger" 
                                                                            onclick="removeGalleryImage({{ $index }})"
                                                                            title="Remove image">
                                                                        <i class="fas fa-times"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    @endforeach
                                                </div>
                                                <input type="hidden" name="removed_gallery_images" id="removed_gallery_images" value="">
                                            </div>
                                        @endif

                                        <div class="form-group">
                                            <label for="gallery" class="font-weight-bold">Add Gallery Images</label>
                                            <input type="file" 
                                                   name="gallery[]" 
                                                   id="gallery" 
                                                   class="form-control @error('gallery.*') is-invalid @enderror"
                                                   accept="image/jpeg,image/png,image/jpg,image/webp"
                                                   multiple>
                                            <small class="form-text text-muted">Additional property images. Max size: 2MB each. Formats: JPEG, PNG, JPG, WebP</small>
                                            @error('gallery.*')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>

                                        <!-- Gallery Preview -->
                                        <div id="gallery-preview" class="mt-3" style="display: none;">
                                            <label class="font-weight-bold">New Gallery Preview:</label>
                                            <div id="gallery-images" class="row mt-2"></div>
                                        </div>

                                        <div class="form-group">
                                            <label for="sort_order" class="font-weight-bold">Sort Order</label>
                                            <input type="number" 
                                                   name="sort_order" 
                                                   id="sort_order" 
                                                   value="{{ old('sort_order', $property->sort_order) }}"
                                                   class="form-control @error('sort_order') is-invalid @enderror"
                                                   placeholder="Display order (0 = first)"
                                                   min="0">
                                            @error('sort_order')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>

                                        <hr>

                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" 
                                                       name="is_active" 
                                                       id="is_active" 
                                                       class="custom-control-input"
                                                       value="1"
                                                       {{ old('is_active', $property->is_active) ? 'checked' : '' }}>
                                                <label class="custom-control-label" for="is_active">Active</label>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" 
                                                       name="display_on_mobile" 
                                                       id="display_on_mobile" 
                                                       class="custom-control-input"
                                                       value="1"
                                                       {{ old('display_on_mobile', $property->display_on_mobile) ? 'checked' : '' }}>
                                                <label class="custom-control-label" for="display_on_mobile">Display on Mobile</label>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" 
                                                       name="display_on_homepage" 
                                                       id="display_on_homepage" 
                                                       class="custom-control-input"
                                                       value="1"
                                                       {{ old('display_on_homepage', $property->display_on_homepage) ? 'checked' : '' }}>
                                                <label class="custom-control-label" for="display_on_homepage">Display on Homepage</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Submit Buttons -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body text-center">
                                        <button type="submit" class="btn btn-primary btn-lg">
                                            <i class="fas fa-save"></i> Update Property
                                        </button>
                                        <a href="{{ route('properties.index') }}" class="btn btn-secondary btn-lg ml-2">
                                            <i class="fas fa-times"></i> Cancel
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Include TinyMCE (Free Version) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.7.2/tinymce.min.js" referrerpolicy="origin"></script>

<style>
.custom-switch .custom-control-label::before {
    width: 2rem;
    height: 1rem;
    border-radius: 0.5rem;
}
.custom-switch .custom-control-label::after {
    width: calc(1rem - 4px);
    height: calc(1rem - 4px);
    border-radius: calc(0.5rem - 2px);
}
.custom-switch .custom-control-input:checked ~ .custom-control-label::after {
    transform: translateX(1rem);
}
.card {
    margin-bottom: 1.5rem;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}
.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
}
.card-title {
    margin-bottom: 0;
    font-size: 1.1rem;
    font-weight: 600;
}
.position-relative {
    position: relative;
}
.position-absolute {
    position: absolute;
}
.top-0 {
    top: 0;
}
.end-0 {
    right: 0;
}
.gallery-preview-item {
    position: relative;
    margin-bottom: 10px;
}
.gallery-preview-item img {
    width: 100%;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
}
.gallery-preview-item .remove-btn {
    position: absolute;
    top: -5px;
    right: -5px;
    background: #dc3545;
    color: white;
    border: none;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    font-size: 10px;
    cursor: pointer;
}
.tox-tinymce {
    border: 1px solid #ced4da !important;
    border-radius: 0.375rem !important;
}
</style>

<script>
let removedImages = [];

// Initialize TinyMCE for rich text editing
document.addEventListener('DOMContentLoaded', function() {
    tinymce.init({
        selector: '#full_description',
        height: 400,
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'insertdatetime', 'media', 'table', 'help', 'wordcount', 'emoticons',
            'paste', 'textcolor', 'colorpicker', 'textpattern', 'nonbreaking'
        ],
        toolbar: 'undo redo | formatselect | bold italic underline strikethrough | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media table | removeformat | help',
        menubar: 'file edit view insert format tools table help',
        content_style: `
            body { 
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; 
                font-size: 14px; 
                line-height: 1.6;
                color: #333;
            }
            h1, h2, h3, h4, h5, h6 { 
                color: #2c3e50; 
                margin-top: 1em; 
                margin-bottom: 0.5em; 
            }
            p { 
                margin-bottom: 1em; 
            }
            ul, ol { 
                margin-bottom: 1em; 
                padding-left: 2em; 
            }
            blockquote { 
                border-left: 4px solid #3498db; 
                padding-left: 1em; 
                margin: 1em 0; 
                font-style: italic; 
            }
        `,
        setup: function(editor) {
            editor.on('change', function() {
                editor.save();
            });
        },
        paste_data_images: true,
        image_advtab: true,
        image_title: true,
        automatic_uploads: false,
        file_picker_types: 'image',
        relative_urls: false,
        remove_script_host: false,
        convert_urls: false,
        browser_spellcheck: true,
        contextmenu: true,
        paste_as_text: false,
        paste_enable_default_filters: true,
        paste_word_valid_elements: "b,strong,i,em,h1,h2,h3,h4,h5,h6",
        paste_retain_style_properties: "color background-color font-size font-weight font-style text-decoration",
        paste_remove_styles_if_webkit: false,
        paste_remove_styles: false
    });
});

// Form validation fix
document.querySelector('form').addEventListener('submit', function(e) {
    // Ensure TinyMCE content is saved before form submission
    if (tinymce.get('full_description')) {
        tinymce.get('full_description').save();
    }
    
    // Check if full_description has content
    const fullDescription = document.getElementById('full_description');
    if (!fullDescription.value || fullDescription.value.trim() === '') {
        e.preventDefault();
        alert('Please enter a detailed description for the property.');
        if (tinymce.get('full_description')) {
            tinymce.get('full_description').focus();
        } else {
            fullDescription.focus();
        }
        return false;
    }
});

function removeGalleryImage(index) {
    if (confirm('Are you sure you want to remove this image?')) {
        removedImages.push(index);
        document.getElementById('removed_gallery_images').value = JSON.stringify(removedImages);
        
        // Hide the image container
        const imageContainer = event.target.closest('.col-6');
        imageContainer.style.display = 'none';
    }
}

// Gallery preview functionality for new images
document.getElementById('gallery').addEventListener('change', function(e) {
    const files = e.target.files;
    const preview = document.getElementById('gallery-preview');
    const imagesContainer = document.getElementById('gallery-images');
    
    if (files.length > 0) {
        preview.style.display = 'block';
        imagesContainer.innerHTML = '';
        
        Array.from(files).forEach((file, index) => {
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const col = document.createElement('div');
                    col.className = 'col-6';
                    col.innerHTML = `
                        <div class="gallery-preview-item">
                            <img src="${e.target.result}" alt="Gallery preview ${index + 1}">
                            <button type="button" class="remove-btn" onclick="removeGalleryPreview(${index})">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    `;
                    imagesContainer.appendChild(col);
                };
                reader.readAsDataURL(file);
            }
        });
    } else {
        preview.style.display = 'none';
    }
});

function removeGalleryPreview(index) {
    const input = document.getElementById('gallery');
    const dt = new DataTransfer();
    const { files } = input;
    
    for (let i = 0; i < files.length; i++) {
        if (i !== index) {
            dt.items.add(files[i]);
        }
    }
    
    input.files = dt.files;
    
    // Re-trigger the change event to update preview
    const event = new Event('change');
    input.dispatchEvent(event);
}

// Card image preview
document.getElementById('card_image').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file && file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = function(e) {
            // You can add card image preview here if needed
            console.log('Card image selected:', file.name);
        };
        reader.readAsDataURL(file);
    }
});
</script>
@endsection 