<%- include("layout/header",{ title: 'Edit Property'}) %>
<form id="edit-property-form" method="POST" enctype="multipart/form-data">
    <input type="hidden" id="property-id" name="id" value="<%=property.id%>"/>
    <fieldset>
        <legend>Property Details</legend>
        <table width="100%">
            <tr>
                <td><input type="text" name="slug" value="<%= property.slug %>" placeholder="unique_slug" required></td>
                <td>Display Order: <input type="number" name="display_order" value="<%= property.display_order %>" placeholder="" required></td>
                <td colspan="4">&nbsp;</td>
            </tr>
            <tr>
                <td colspan="2">
                    <table width="100%">
                        <tr>
                            <td><input type="text" name="channel_id" value="<%= property.channel_id %>" placeholder="channel_id" required></td>
                            <td><input type="text" name="listing_name" value="<%= property.listing_name %>" placeholder="Listing Name" required></td>
                            <td><select name="hosts" id="hosts" multiple required>
                                    <option value="">Select Client</option>
                                    <% results.hosts.forEach(host => { %>
                                        <% if(property.hosts.includes(host.id)){%>
                                            <option value="<%= host.id %>" selected><%= host.name %></option>
                                        <% }else{ %>
                                            <option value="<%= host.id %>"><%= host.name %></option>
                                        <% } %>
                                    <% }); %>
                                </select>
                            </td>
                            <td>Staymaster Select
                                <input type="radio" id="yes" name="staymaster_select" value="1" />
                                <label for="yes">Yes</label>
                                <input type="radio" id="no" name="staymaster_select" value="0" checked />
                                <label for="no">No</label>
                            </td>
                            <td><input type="text" name="internal_name" value="<%= property.internal_name %>" placeholder="Internal Name" required></td>
                            <td>
                                <select name="destination" id="destination" required>
                                    <option value="">Select Location</option>
                                    <% results.destinations.forEach(destination => { %>
                                        <% if(destination.id == property.destination) {%>
                                            <option value="<%= destination.id %>" selected><%= destination.name %></option>
                                        <% }else{ %>
                                            <option value="<%= destination.id %>"><%= destination.name %></option>
                                        <% } %>
                                    <% }); %>
                                </select>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td colspan="2">
                    <table width="100%">
                        <tr>
                            <td><input type="text" name="address_line_1" value="<%= property.address_line_1 %>" placeholder="Address Line 1"></td>
                            <td><input type="text" name="address_line_2" value="<%= property.address_line_2 %>" placeholder="Address Line 2"></td>
                            <td><input type="text" name="city" value="<%= property.city %>" placeholder="city" required></td>
                            <td><input type="text" name="state" value="<%= property.state %>" placeholder="state" required></td>
                            <td>
                                <select name="country" id="" required>
                                    <option value="">Select Country</option>
                                    <% results.countries.forEach(country => { %>
                                        <% if(country.id == property.country) {%>
                                            <option value="<%= country.id %>" selected><%= country.display %></option>
                                        <% }else{ %>
                                            <option value="<%= country.id %>"><%= country.display %></option>
                                        <% } %>
                                    <% }); %>
                                </select>
                            </td>
                            <td><input type="text" name="postcode" value="<%= property.postcode %>" placeholder="postcode" required></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td colspan="2">
                    <table width="100%">
                        <tr>
                            <td>
                                <select name="property_type" id="" required>
                                    <option value="">Type of property</option>
                                    <% results.property_types.forEach(property_type => { %>
                                        <% if(property_type.id == property.property_type) {%>
                                            <option value="<%= property_type.id %>" selected><%= property_type.display %></option>
                                        <% }else{ %>
                                            <option value="<%= property_type.id %>"><%= property_type.display %></option>
                                        <% } %>
                                    <% }); %>
                                </select>
                            </td>
                            <td><input type="text" name="number_of_bedrooms" value="<%= property.number_of_bedrooms %>" placeholder="No of bedrooms" required></td>
                            <td><input type="text" name="number_of_bathrooms" value="<%= property.number_of_bathrooms %>" placeholder="No of bathrooms" required></td>
                            <td><input type="text" name="number_of_guests" value="<%= property.number_of_guests %>" placeholder="No of guests" required></td>
                            <td><input type="text" name="number_of_extra_guests" value="<%= property.number_of_extra_guests %>" placeholder="No of extra guests" required></td>
                            <td>Featured Property <input type="checkbox" name="featured_property" placeholder="Featured Property" value="1"></td>
                            <td><input type="text" id="sdp" name="security_deposit_percentage" value="<%= property.security_deposit_percentage %>" placeholder="Security Deposit" required></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </fieldset>
    <table width="100%">
        <tr><td>&nbsp;</td></tr>
        <tr>
            <td>
                <fieldset>
                    <legend>Property Category(Select upto 5)</legend>
                    <% results.collections.forEach(collection => { %>
                        <% if(property.collections.includes(collection.id)){%>
                            <input type="checkbox" name="property_collections" value="<%= collection.id %>" checked><%= collection.name %><br>
                        <% }else{ %>
                            <input type="checkbox" name="property_collections" value="<%= collection.id %>"><%= collection.name %><br>
                        <% } %>
                    <% }); %>
                </fieldset>
            </td>
            <td>
                <fieldset>
                    <legend>Property Detailed Descriptions</legend>
                    <table>
                        <tr>
                            <td><textarea name="description_summary" rows="4" cols="50" placeholder="Summary (Description upto 500 characters)"><%= property.description_summary %></textarea></td>
                            <td><textarea name="description_bedrooms_and_bath" rows="4" cols="50" placeholder="bedrooms_and_bath (Description upto 500 characters)"><%=property.description_bedrooms_and_bath%></textarea></td>
                        </tr>
                        <tr>
                            <td><textarea name="description_living_and_dining" rows="4" cols="50" placeholder="living_and_dining (Description upto 500 characters)"><%=property.description_living_and_dining%></textarea></td>
                            <td><textarea name="description_kitchen_space" rows="4" cols="50" placeholder="kitchen_space (Description upto 500 characters)"><%=property.description_kitchen_space%></textarea></td>
                        </tr>
                        <tr>
                            <td><textarea name="description_pool" rows="4" cols="50" placeholder="Pool (Description upto 500 characters)"><%=property.description_pool%></textarea></td>
                            <td><textarea name="description_unique_highlights" rows="4" cols="50" placeholder="description_unique_highlights (Description upto 500 characters)"><%=property.description_unique_highlights%></textarea></td>
                        </tr>
                        <tr>
                            <td colspan="2"><textarea name="description_hospitality_service" rows="4" cols="50" placeholder="Hospitality (Description upto 500 characters)"><%=property.description_hospitality_service%></textarea></td>
                        </tr>
                    </table>
                </fieldset>
            </td>
        </tr>
        <tr><td>&nbsp;</td></tr>
    </table>
    <fieldset>
        <legend>Amenities</legend>
        <table>
            <tr>
            <% var amenityWithDisc;%>
            <% Object.keys(results.amenities).forEach(category => { %>
                <td style="border:1px solid #eeeeee; vertical-align: top;">
                <br><%= category %><br>
                <% results.amenities[category].forEach(amenity => { %>
                    <% if(property.amenities.includes(amenity.id)){%>
                        <input type="checkbox" name="amenities" value="<%= amenity.id %>" checked><%= amenity.name %><br>
                    <% }else{ %>
                        <input type="checkbox" name="amenities" value="<%= amenity.id %>"><%= amenity.name %><br>
                    <% } %>
                    <% amenityWithDisc = property.amenitiesWithDescriptions.find(awd => awd.amenity_id == amenity.id); %>
                    <% if(amenityWithDisc){ %>
                        <input type="text" name="<%= amenity.id %>_description" value="<%=amenityWithDisc['description']%>" placeholder="">
                    <% }else{ %>
                        <input type="text" name="<%= amenity.id %>_description" value="" placeholder="">
                    <% } %>
                <% }); %>
                </td>
            <% }); %>
            </tr>
        </table>
    </fieldset>
    <table><tr><td>&nbsp;</td></tr></table>
    <fieldset>
        <legend>Location & Neighbourhood</legend>
        <table width="100%">
            <tr>
                <td>
                    <table>
                        <tr><td><input type="text" name="google_latitude" value="<%=property.google_latitude%>" placeholder="Google Latitude" required></td></tr>
                        <tr><td><input type="text" name="google_longitude" value="<%=property.google_longitude%>" placeholder="Google Longitude" required></td></tr>
                    </table>
                </td>
                <td>
                    <textarea name="location_details" rows="4" cols="50" placeholder="Location Details (Description upto 500 characters)"><%=property.location_details%></textarea>
                </td>
                <td>
                    <textarea name="places_around" rows="4" cols="50" placeholder="Places Around (Description upto 500 characters)"><%=property.places_around%></textarea>
                </td>
            </tr>
        </table>
    </fieldset>
    <table><tr><td>&nbsp;</td></tr></table>
    <fieldset>
        <legend>Meals</legend>
        <table>
            <tr>
                <td>
                    Meals Available: 
                    <input type="radio" id="yes" name="meals_available" value="1" />
                    <label for="yes">Yes</label>
                    <input type="radio" id="no" name="meals_available" value="0" checked />
                    <label for="no">No</label><br/>
                    Breakfast Fee: <input type="text" name="breakfast_fee" value="0" placeholder="">
                </td>
                <td><textarea name="meals_text" rows="4" cols="50" placeholder="Meals Description"><%=property.meals_text%></textarea></td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </fieldset>
    <table><tr><td>&nbsp;</td></tr></table>
    <table>
        <tr>
            <td>
                <fieldset>
                    <legend>Essential Info</legend>
                    Check In: <input type="text" name="check_in" value="<%=property.check_in%>" required>
                    Check Out:<input type="text" name="check_out" value="<%=property.check_out%>" required>
                    <input type="text" name="other_details" value="<%=property.other_details%>">
                </fieldset>
            </td>
            <td>
                <fieldset>
                    <legend>House Rules & Policies</legend>
                    <textarea name="house_rules" rows="4" cols="50" placeholder="House Rules"><%=property.house_rules%></textarea>
                </fieldset>
            </td>
        </tr>
    </table>
    <table><tr><td>&nbsp;</td></tr></table>
    <fieldset>
        <legend>Users</legend>
        <table width="100%">
            <tr>
                <td>
                    <select name="reservation_executive" id="" required>
                        <option value="">Select Reservation Executive</option>
                        <% results.staffs.forEach(staff => { %>
                            <% if(staff.id == property.reservation_executive) {%>
                                <option value="<%= staff.id %>" selected><%= staff.name %></option>
                            <% }else{ %>
                                <option value="<%= staff.id %>"><%= staff.name %></option>
                            <% } %>
                        <% }); %>
                    </select>
                </td>
                <td>
                    <select name="revenue_manager" id="" required>
                        <option value="">Select Revenue Manager</option>
                        <% results.staffs.forEach(staff => { %>
                            <% if(staff.id == property.revenue_manager) {%>
                                <option value="<%= staff.id %>" selected><%= staff.name %></option>
                            <% }else{ %>
                                <option value="<%= staff.id %>"><%= staff.name %></option>
                            <% } %>
                        <% }); %>
                    </select>
                </td>
                <td>
                    <select name="hospitality_manager" id="" required>
                        <option value="">Select Hospitalty Manager</option>
                        <% results.staffs.forEach(staff => { %>
                            <% if(staff.id == property.hospitality_manager) {%>
                                <option value="<%= staff.id %>" selected><%= staff.name %></option>
                            <% }else{ %>
                                <option value="<%= staff.id %>"><%= staff.name %></option>
                            <% } %>
                        <% }); %>
                    </select>
                </td>
                <td>
                    <select name="general_manager" id="" required>
                        <option value="">Select Hospitalty Manager</option>
                        <% results.staffs.forEach(staff => { %>
                            <% if(staff.id == property.general_manager) {%>
                                <option value="<%= staff.id %>" selected><%= staff.name %></option>
                            <% }else{ %>
                                <option value="<%= staff.id %>"><%= staff.name %></option>
                            <% } %>
                        <% }); %>
                    </select>
                </td>
            </tr>
        </table>
    </fieldset>
    <table><tr><td>&nbsp;</td></tr></table>
    <div class="form-group">
        <label>Display Picture</label>
        <img id="current-display-picture" class="non-editable-image" photoid="<%=property.display_image_id%>" src="<%= property.display_image %>" alt="Current Display Picture">
        <div class="dropzone" id="display-picture-dropzone">Drop new display picture here or click to upload</div>
    </div>
    <div class="form-group">
        <label>Property Pictures</label>
        <div class="dropzone" id="bedroom-dropzone" data-category="271"><h4>Bedroom Photos</h4></div>
        <div class="dropzone" id="bathroom-dropzone" data-category="7"><h4>Bathroom Photos</h4></div>
        <div class="dropzone" id="living-dropzone" data-category="8"><h4>Living & Dining Photos</h4></div>
        <div class="dropzone" id="kitchen-dropzone" data-category="9"><h4>Kitchen & Pantry Photos</h4></div>
        <div class="dropzone" id="pool-dropzone" data-category="10"><h4>Pool Photos</h4></div>
        <div class="dropzone" id="garden-dropzone" data-category="11"><h4>Garden or Outdoor Areas Photos</h4></div>
        <div class="dropzone" id="shared-dropzone" data-category="12"><h4>Shared Spaces Photos</h4></div>
        <div class="dropzone" id="fascade-dropzone" data-category="13"><h4>Fascade & Exterior Photos</h4></div>
    </div>
    <div class="button-container">
        <button type="button" class="add-villa-btn" id="save-button">Save Property</button>
        <button onclick="location.href='/api/properties/listing'">Cancel</button>
    </div>
</form>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const saveButton = document.getElementById('save-button');
        const editPropertyForm = document.getElementById('edit-property-form');
        const currentDisplayPicture = document.getElementById('current-display-picture');
        const displayPictureDropzone = document.getElementById('display-picture-dropzone');
        const propertyId = document.getElementById('property-id').value;
        
        saveButton.addEventListener('click', async () => {
            if (!editPropertyForm.checkValidity()) {
                editPropertyForm.reportValidity();
                return;
            }
            try {
                const formData = new FormData(editPropertyForm);
                const propertyPictures = document.querySelectorAll('.dropzone[id$="-dropzone"]');

                // Add property pictures to formData
                propertyPictures.forEach(dropzone => {
                    const category_id = dropzone.getAttribute('data-category');
                    if(category_id != null){
                        const images = dropzone.querySelectorAll('img:not(.delete-icon)');
                        images.forEach((img, index) => {
                            formData.append(`photos_${category_id}`, img.id);
                            formData.append(`category_ids_${category_id}`, category_id);
                        });
                    }
                });

                // Send formData to backend
                const response = await fetch('/api/properties/save', {
                    method: 'POST',
                    body: formData,
                });

                if (!response.ok) {
                    console.log('Failed to save property:', response.json())
                    throw new Error('Failed to save property');
                }

                const result = await response.json();
                console.log('Property saved successfully:', result);
                alert('Property saved successfully');
                window.location.href = '/api/properties/listing';
            } catch (error) {
                console.error('Error saving property:', error);
                alert('Failed to save property');
            }
        });

        function handleDisplayPicture(file) {
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = async () => {
                    // Delete current display picture from the database
                    if (currentDisplayPicture.src) {
                        await replaceImage(currentDisplayPicture.getAttribute('photoid'),file);
                    }
                    // Update the current display picture
                    currentDisplayPicture.src = reader.result;
                    currentDisplayPicture.style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        }
        
        displayPictureDropzone.addEventListener('dragover', (e) => {
            e.preventDefault();
            displayPictureDropzone.style.backgroundColor = '#e0e0e0';
        });

        displayPictureDropzone.addEventListener('dragleave', () => {
            displayPictureDropzone.style.backgroundColor = '#fff';
        });

        displayPictureDropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            displayPictureDropzone.style.backgroundColor = '#fff';

            const files = Array.from(e.dataTransfer.files);
            if (files.length > 1) {
                alert('Only one display picture is allowed.');
            } else {
                handleDisplayPicture(files[0]);
            }
        });

        displayPictureDropzone.addEventListener('click', () => {
            const input = document.createElement('input');
            input.type = 'file';
            input.onchange = (e) => {
                const file = e.target.files[0];
                handleDisplayPicture(file);
            };
            input.click();
        });
    
        const dropzones = document.querySelectorAll('.dropzone:not(#display-picture-dropzone)');
        const categories = <%- JSON.stringify(property.mediasById) %>;
        dropzones.forEach(dropzone => {
            const categoryId = dropzone.getAttribute('data-category');
            const photos = categories[categoryId];
            if(photos){
                photos.forEach(imgSrc => {
                    const imgContainer = createImageContainer(imgSrc['filename'], categoryId,imgSrc['media_id']);
                    dropzone.appendChild(imgContainer);
                });
            }

            dropzone.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropzone.style.backgroundColor = '#e0e0e0';
            });

            dropzone.addEventListener('dragleave', () => {
                dropzone.style.backgroundColor = '#fff';
            });

            dropzone.addEventListener('drop', (e) => {
                e.preventDefault();
                dropzone.style.backgroundColor = '#fff';

                const files = Array.from(e.dataTransfer.files);
                handleFiles(files, dropzone, categoryId);
            });

            dropzone.addEventListener('click', () => {
                const input = document.createElement('input');
                input.type = 'file';
                input.multiple = true;
                input.onchange = (e) => {
                    const files = Array.from(e.target.files);
                    handleFiles(files, dropzone, categoryId);
                };
                input.click();
            });
        });
    
        function handleFiles(files, dropzone, categoryId) {
            files.forEach(file => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = async () => {
                        var newId = await uploadImageToDatabase(file, 'category', categoryId);
                        //alert(newId);
                        //console.log(newId);
                        const imgContainer = createImageContainer(reader.result, categoryId,newId);
                        dropzone.appendChild(imgContainer);

                        // Upload category image to the database
                        //await uploadImageToDatabase(file, 'category', categoryId);
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
        
        function createImageContainer(src, categoryId,id=null) {
            //alert("image id: " + id);
            const imgContainer = document.createElement('div');
            imgContainer.style.position = 'relative';
            imgContainer.style.display = 'inline-block';
            imgContainer.draggable = true;

            const img = document.createElement('img');
            img.src = src;
            img.id = id;
            imgContainer.appendChild(img);

            const deleteIcon = document.createElement('img');
            deleteIcon.src = '/api/public/delete_icon.jpg'; // Provide URL for delete icon
            deleteIcon.classList.add('delete-icon');
            imgContainer.appendChild(deleteIcon);

            deleteIcon.addEventListener('click', async () => {
                // Delete category image from the database
                await deleteImage(id);
                imgContainer.remove();
            });

            // Enable drag-and-drop reordering
            imgContainer.addEventListener('dragstart', (e) => {
                e.dataTransfer.effectAllowed = 'move';
                e.dataTransfer.setData('text/plain', null);
                imgContainer.classList.add('dragging');
            });

            imgContainer.addEventListener('dragover', (e) => {
                e.preventDefault();
                const draggingElement = document.querySelector('.dragging');
                if (draggingElement !== imgContainer) {
                    const bounding = imgContainer.getBoundingClientRect();
                    const offset = bounding.y + (bounding.height / 2);
                    if (e.clientY - offset > 0) {
                        imgContainer.style['border-bottom'] = '2px solid blue';
                        imgContainer.style['border-top'] = '';
                    } else {
                        imgContainer.style['border-top'] = '2px solid blue';
                        imgContainer.style['border-bottom'] = '';
                    }
                }
            });

            imgContainer.addEventListener('dragleave', () => {
                imgContainer.style['border-bottom'] = '';
                imgContainer.style['border-top'] = '';
            });

            imgContainer.addEventListener('drop', (e) => {
                e.preventDefault();
                const draggingElement = document.querySelector('.dragging');
                if (draggingElement !== imgContainer) {
                    const bounding = imgContainer.getBoundingClientRect();
                    const offset = bounding.y + (bounding.height / 2);
                    if (e.clientY - offset > 0) {
                        imgContainer.style['border-bottom'] = '';
                        imgContainer.insertAdjacentElement('afterend', draggingElement);
                    } else {
                        imgContainer.style['border-top'] = '';
                        imgContainer.insertAdjacentElement('beforebegin', draggingElement);
                    }
                }
            });

            imgContainer.addEventListener('dragend', () => {
                imgContainer.classList.remove('dragging');
                imgContainer.style['border-bottom'] = '';
                imgContainer.style['border-top'] = '';
            });

            return imgContainer;
        }

        async function deleteImage(id) {
            await fetch(`/api/properties/delete-image`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ id:id }),
            });
        }

        async function replaceImage(id,file){
            const formData = new FormData(editPropertyForm);
            formData.append('photoId', id);
            formData.append('file', file);
            await fetch(`/api/properties/replace-image`, {
                    method: 'POST',
                    body: formData,
            });
        }

        async function uploadImageToDatabase(file, type, categoryId = null) {
            // Implement API call to upload image to the database
            console.log(`Uploading ${type} image to category: ${categoryId}`);
            const formData = new FormData(editPropertyForm);
            formData.append('file', file);
            formData.append('filetype', type);
            formData.append('propertyId',propertyId);
            if (categoryId) {
                formData.append('categoryId', categoryId);
            }
            // Example API call
            const response = await fetch(`/api/properties/upload-image`, {
                method: 'POST',
                body: formData,
            });
            if (!response.ok) {
                console.log('Failed to upload photo:', response.json())
                throw new Error('Failed to upload photo');
            }
            const result = await response.json();
            return result.newId;
        }

        editPropertyForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            // Save property details to the database
            const formData = new FormData(editPropertyForm);

            // Example API call to save property details
            // await fetch(`/api/properties/update`, {
            //     method: 'POST',
            //     body: formData,
            // });

            alert('Property details updated successfully.');
        });
    });
</script>
<%- include("layout/footer") %>