<%- include("layout/header",{ title: 'Add Property'}) %>
<div class="propertyadd">
    <div class="row headingsection">
        <div class="col-sm-6"><h1>Add Property</h1></div>
        <div class="col-sm-6" style="text-align: right;">
            <button type="button" class="greenbutton" id="upload-button">Save</button>&nbsp;&nbsp;
            <button type="button" class="transparant" onclick="location.href='/api/properties/listing'">Cancel</button>
        </div>
    </div>
    <form id="add-property-form" enctype="multipart/form-data" class="addproperty">
        <div class="formcontainer">
            <h1 class="propertyheadingblue">Property Details</h1>
            <hr>
            <div class="row form-row">
                <div class="form-group col-md-3">
                    <div class="mb-3">
                        <label for="slug" class="form-label">Unique Slug</label>
                        <input type="text" name="slug" id="slug" value="" placeholder="Unique Slug" required fdprocessedid="6cs09k">
                    </div>
                </div>
                <div class="form-group col-md-3">
                    <div class="mb-3">
                        <label for="channel_id" class="form-label">Channel Id</label>
                        <input type="text" name="channel_id" id="channel_id" value="" placeholder="Channel Id" required fdprocessedid="dwn75a">
                    </div>
                </div>
                <div class="form-group col-md-3">
                    <div class="mb-3">
                        <label for="listing_name" class="form-label">Listing Name</label>
                        <input type="text" name="listing_name" id="listing_name" value="" placeholder="Listing Name" required fdprocessedid="efraj8">
                    </div>
                </div>
                <div class="form-group col-md-3">
                    <div class="mb-3">
                        <label for="display_order" class="form-label">Display Order</label>
                        <input type="number" name="display_order" id="display_order" value="<%= results.nextOrder %>" required>
                    </div>
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-3">
                    <div class="mb-3">
                        <label for="internal_name" class="form-label">Internal Name</label>
                        <input type="text" name="internal_name" id="internal_name" value="" placeholder="Internal Name" required>
                    </div>
                </div>
                <div class="form-group col-md-3">
                    <label for="destination" class="form-label">Select Destination</label>
                    <select class="form-control selectpicker" name="destination" id="destination" required>
                        <option value="">Select Destination</option>
                        <% results.destinations.forEach(destination => { %>
                            <option value="<%= destination.id %>"><%= destination.name %></option>
                        <% }); %>
                    </select>
                </div>
                <div class="form-group col-md-3">
                    <label for="hosts" class="form-label">Select Client(s)</label>
                    <select class="form-control selectpicker" data-live-search="true" name="hosts" id="hosts" multiple required>
                        <option value="">Select Client</option>
                        <% results.hosts.forEach(host => { %>
                            <% if (host && host.name) { %>
                                <option value="<%= host.id %>"><%= host.name %></option>
                            <% } %>
                        <% }); %>
                    </select>    
                </div>
                <div class="form-group col-md-3">
                    <div class="mb-3">
                        <label for="">Staymaster Select</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="staymaster_select" id="yes" value="1">
                            <label class="form-check-label" for="yes">Yes</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="staymaster_select" id="no" value="0" checked>
                            <label class="form-check-label" for="no">No</label>
                        </div>
                    </div>
                </div>                                
            </div>
            <br>
            <div class="row form-row">
                <div class="form-group col-md-6">
                    <input type="text" name="address_line_1" value="" placeholder="Address Line 1" fdprocessedid="witk7i">
                </div>
                <div class="form-group col-md-6">
                    <input type="text" name="address_line_2" value="" placeholder="Address Line 2" fdprocessedid="2bxhx">
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-3">
                    <input type="text" name="city" id="city" value="" placeholder="City" required>
                </div>
                <div class="form-group col-md-3">
                    <input type="text" name="state" id="state" value="" placeholder="State" required>
                </div>
                <div class="form-group col-md-3">
                    <select class="form-control selectpicker" name="country" id="country" required>
                        <option value="">Select Country</option>
                        <% results.countries.forEach(country => { %>
                            <option value="<%= country.id %>"><%= country.display %></option>
                        <% }); %>
                    </select>
                </div>
                <div class="form-group col-md-3">
                    <input type="text" class="form-control" name="postcode" id="postcode" placeholder="Pin Code" required>
                </div>
            </div>
            <br><br>
            <div class="row form-row">
                <div class="form-group col-md-3">
                    <select class="form-control" name="property_type" id="property_type" required>
                        <option value="">Type of property</option>
                        <% results.property_types.forEach(property_type => { %>
                            <option value="<%= property_type.id %>"><%= property_type.display %></option>
                        <% }); %>
                    </select>
                </div>
                <div class="form-group col-md-3">
                    <div class="form-check">
                        <label class="form-check-label" for="featured_property"> &nbsp;Featured Property
                            <input class="form-check-input checkbox" type="checkbox" name="featured_property" id="featured_property"></label>   
                    </div>
                </div>
                <div class="form-group col-md-3">
                    <input type="number" name="security_deposit_percentage" id="security_deposit_percentage" value="" placeholder="Security Deposit" required>
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-3">
                    <input type="text" name="number_of_bedrooms" id="number_of_bedrooms" value="" placeholder="No. of bedrooms" required>
                </div>
                <div class="form-group col-md-3">
                    <input type="text" name="number_of_bathrooms" id="number_of_bathrooms" value="" placeholder="No. of bathrooms" required>
                </div>
                <div class="form-group col-md-3">
                    <input type="text" name="number_of_guests" id="number_of_guests" value="" placeholder="No. of guests" required>
                </div>
                <div class="form-group col-md-3">
                    <input type="text" name="number_of_extra_guests" id="number_of_extra_guests" value="" placeholder="No. of extra guests" required>
                </div>
            </div>
            <br><br>
            <h1 class="propertyheadingblue">Property Category <span style="font-size:12px">(Select upto 5 categories)</span></h1>
            <hr>
            <div class="row form-row">
                <% results.collections.forEach(collection => { %>
                    <div class="form-group col-md-3">
                        <div class="form-check form-check-inline">
                            <input class="form-check-input checkbox" type="checkbox" name="property_collections" value="<%= collection.id %>"><%= collection.name %>
                        </div>
                    </div>
                <% }); %>
            </div>
        </div>
        <br>
        <div class="formcontainer">
            <h1 class="propertyheadingblue">Property Detailed Descriptions</h1>
            <hr>
            <div class="row form-row">
                <div class="form-group col-md-6">
                    <div data-mdb-input-init class="form-outline">
                        <label class="form-label">Summary</label>
                        <textarea name="description_summary" rows="4" placeholder=""></textarea>
                    </div>
                </div>
                <div class="form-group col-md-6">
                    <div data-mdb-input-init class="form-outline">
                        <label class="form-label">Bedrooms and Bathrooms</label>
                        <textarea name="description_bedrooms_and_bath" rows="4" placeholder=""></textarea>
                    </div>
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-6">
                    <div data-mdb-input-init class="form-outline">
                        <label class="form-label">Living and Dining</label>
                        <textarea name="description_living_and_dining" rows="4" placeholder=""></textarea>
                    </div>
                </div>
                <div class="form-group col-md-6">
                    <div data-mdb-input-init class="form-outline">
                        <label class="form-label">Kitchen Space</label>
                        <textarea name="description_kitchen_space" rows="4" placeholder=""></textarea>
                    </div>
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-6">
                    <div data-mdb-input-init class="form-outline">
                        <label class="form-label">Pool</label>
                        <textarea name="description_pool" rows="4" placeholder=""></textarea>
                    </div>
                </div>
                <div class="form-group col-md-6">
                    <div data-mdb-input-init class="form-outline">
                        <label class="form-label">Unique Highlights</label>
                        <textarea name="description_unique_highlights" rows="4" placeholder=""></textarea>
                    </div>
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-6">
                    <div data-mdb-input-init class="form-outline">
                        <label class="form-label">Hospitality Service</label>
                        <textarea name="description_hospitality_service" rows="4" placeholder=""></textarea>
                    </div>
                </div>
            </div>
        </div>
        <br>
        <div class="formcontainer">
            <h1 class="propertyheadingblue">Amenities</h1>
            <hr>
            <% Object.keys(results.amenities).forEach(category => { %>
                <p><%= category %></p>
                <div class="row form-row">
                <% results.amenities[category].forEach(amenity => { %>
                    <div class="form-group col-md-3">
                        <div class="form-check form-check-inline">
                            <input class="form-check-input checkbox" type="checkbox" name="amenities" value="<%= amenity.id %>">
                            <label class="form-check-label" for="inlineCheckbox1"><%= amenity.name %></label>
                            <input type="text" name="<%= amenity.id %>_description" value="">
                        </div>
                    </div>
                <% }); %>
                </div>
                <br>
            <% }); %>
        </div>
        <br>
        <div class="formcontainer">
            <h1 class="propertyheadingblue">Location & Neighbourhood</h1>
            <hr>
            <p>Pin Property Location</p>
            <div class="row form-row">
                <div class="form-group col-md-3">
                    <input type="text" name="google_latitude" value="" placeholder="Google Latitude" required>
                </div>
                <div class="form-group col-md-3">
                    <input type="text" name="google_longitude" value="" placeholder="Google Longitude" required>
                </div>
                <!--<div class="form-group col-md-9">
                   <div><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d18906.129712753736!2d6.722624160288201!3d60.12672284414915!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x463e997b1b6fc09d%3A0x6ee05405ec78a692!2sJ%C4%99zyk%20trola!5e0!3m2!1spl!2spl!4v1672239918130!5m2!1spl!2spl" width="100%" height="300" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe></div>
                </div>-->
            </div>
            <div class="row form-row">
                <div class="form-group col-md-6">
                    <label class="form-label" for="textAreaExample">Location Details</label>
                    <div data-mdb-input-init class="form-outline">
                        <textarea class="form-control" name="location_details" rows="4" placeholder=""></textarea>
                    </div>
                </div>
                <div class="form-group col-md-6">
                    <label class="form-label" for="textAreaExample">Places Around</label>
                    <div data-mdb-input-init class="form-outline">
                        <textarea class="form-control" name="places_around" rows="4" placeholder=""></textarea>
                    </div>
                </div>
            </div>
        </div>
        <br>
        <div class="formcontainer">
            <h1 class="propertyheadingblue">Meals</h1>
            <hr>
            <div class="row form-row">
                <div class="col-md-3"> 
                    <label for="" style="padding-right:40px">Meals Available</label>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="meals_available" id="yes" value="1">
                        <label class="form-check-label" for="yes">Yes</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="meals_available" id="no" value="0" checked>
                        <label class="form-check-label" for="no">No</label>
                    </div>
                </div>
                <div class="col-md-3">
                    <div data-mdb-input-init class="form-outline">
                        <label class="form-label" for="" style="padding-right:10px">Breakfast Fee</label>
                        <input type="text" name="breakfast_fee" style="width: 150px;" value="0" placeholder="0">
                    </div>
                </div>
                <div class="form-group col-md-6">
                    <label class="form-label" for="">Meals Description</label>
                    <div data-mdb-input-init class="form-outline">
                        <textarea class="form-control" name="meals_text" rows="4" placeholder=""></textarea>
                    </div>
                </div>
            </div>
        </div>
        <br>
        <div class="formcontainer">
            <h1 class="propertyheadingblue">Essential Info</h1>
            <hr>
            <div class="row form-row">
                <div class="form-group col-md-4">
                    <label class="form-label" for="" style="padding-right:10px">Check In Time</label>
                    <input type="text" name="check_in" style="width: 200px;" value="15:00:00" placeholder="0" required>
                </div>
                <div class="form-group col-md-4">
                    <label class="form-label" for="" style="padding-right:10px">Check Out Time</label>
                    <input type="text" name="check_out" style="width: 200px;" value="11:00:00" placeholder="0" required>
                </div>
                <div class="form-group col-md-4">
                    <label class="form-label" for="" style="padding-right:10px">Other Details</label>
                    <input type="text" name="other_details" style="width: 200px;" value="0" placeholder="0">
                </div>
            </div>
            <h1 class="propertyheadingblue">House Rules and Policies</h1>
            <hr>
            <div class="row form-row">
                <div class="form-group col-md-12">
                    <label class="form-label" for="" style="padding-right:10px">House Rules and Policies</label>
                    <div data-mdb-input-init class="form-outline">
                        <textarea class="form-control" name="house_rules" rows="4" placeholder="House Rules and Policies"></textarea>
                    </div>
                </div>
            </div>
        </div>
        <br>
        <div class="formcontainer">
            <h1 class="propertyheadingblue">User Details</h1>
            <hr>
            <div class="row form-row">
                <div class="form-group col-md-3">
                    <label class="form-label" for="" style="padding-right:10px">Reservation Executive</label>
                    <div data-mdb-input-init class="form-outline">
                        <select class="form-control" name="reservation_executive" id="" required>
                            <option value="">Select Reservation Executive</option>
                            <% results.staffs.forEach(staff => { %>
                                <option value="<%= staff.id %>"><%= staff.name %></option>
                            <% }); %>
                        </select>
                    </div>
                </div>
                <div class="form-group col-md-3">
                    <label class="form-label" for="" style="padding-right:10px">Revenue Manager</label>
                    <div data-mdb-input-init class="form-outline">
                        <select class="form-control" name="revenue_manager" id="" required>
                            <option value="">Select Revenue Manager</option>
                            <% results.staffs.forEach(staff => { %>
                                <option value="<%= staff.id %>"><%= staff.name %></option>
                            <% }); %>
                        </select>
                    </div>
                </div>
                <div class="form-group col-md-3">
                    <label class="form-label" for="" style="padding-right:10px">Hospitalty Manager</label>
                    <div data-mdb-input-init class="form-outline">
                        <select class="form-control" name="hospitality_manager" id="" required>
                            <option value="">Select Hospitalty Manager</option>
                            <% results.staffs.forEach(staff => { %>
                                <option value="<%= staff.id %>"><%= staff.name %></option>
                            <% }); %>
                        </select>
                    </div>
                </div>
                <div class="form-group col-md-3">
                    <label class="form-label" for="" style="padding-right:10px">General Manager</label>
                    <div data-mdb-input-init class="form-outline">
                        <select class="form-control" name="general_manager" id="" required>
                            <option value="">Select General Manager</option>
                            <% results.staffs.forEach(staff => { %>
                                <option value="<%= staff.id %>"><%= staff.name %></option>
                            <% }); %>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <br>
        <div class="formcontainer">
            <h1 class="propertyheadingblue">Display Picture</h1>
            <hr>
            <div class="row form-row">
                <div class="form-group col-md-10">
                    <label>Display Picture <span class="error" id="display-picture-error">This field is required.</span></label>
                    <div class="dropzone" id="display-picture-dropzone"><h4>Display Picture</h4></div>
                </div>
            </div>
        </div>
    </form>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const uploadButton = document.getElementById('upload-button');
        const addPropertyForm = document.getElementById('add-property-form');
        const displayPictureDropzone = document.getElementById('display-picture-dropzone');
        const displayPictureError = document.getElementById('display-picture-error');
        let displayPictureFile = null;
        
        // Debug bootstrap-select initialization
        console.log("=== Bootstrap Select Debug ===");
        console.log("Hosts field:", document.getElementById('hosts'));
        console.log("Hosts field classList:", document.getElementById('hosts').classList);
        console.log("jQuery available:", typeof $ !== 'undefined');
        if (typeof $ !== 'undefined') {
            console.log("jQuery version:", $.fn.jquery);
            console.log("Bootstrap select available:", typeof $.fn.selectpicker !== 'undefined');
            if (typeof $.fn.selectpicker !== 'undefined') {
                console.log("Initializing bootstrap-select for hosts field");
                $('#hosts').selectpicker();
            }
        }
        console.log("=============================");

        uploadButton.addEventListener('click', async (e) => {
            e.preventDefault(); // Prevent default form submission
            console.log("=== Upload Button Clicked ===");
            console.log("Form validity:", addPropertyForm.checkValidity());
            console.log("Form validation message:", addPropertyForm.validationMessage);
            
            // Check individual field validity
            const requiredFields = addPropertyForm.querySelectorAll('[required]');
            console.log("=== Required Fields Validation ===");
            requiredFields.forEach(field => {
                console.log(`${field.name}:`, field.validity.valid, field.validity.message);
            });
            console.log("================================");
            
            console.log("Hosts field:", document.getElementById('hosts'));
            console.log("Hosts field classList:", document.getElementById('hosts').classList);
            console.log("Hosts field selectedOptions:", document.getElementById('hosts').selectedOptions);
            console.log("=============================");
            
            if (!addPropertyForm.checkValidity()) {
                console.log("Form validation failed, reporting validity");
                addPropertyForm.reportValidity();
                return;
            }
            if (!displayPictureFile) {
                console.log("Display picture validation failed");
                alert("Display picture is mandatory");
                displayPictureError.style.display = 'block';
                return;
            }
            try {
                // uploadButton.disabled=true; // Removed disabled condition as requested
                console.log('Processing property creation');
                
                // Debug raw form data
                console.log("=== Raw Form Data Debug ===");
                const formElements = addPropertyForm.elements;
                for (let i = 0; i < formElements.length; i++) {
                    const element = formElements[i];
                    if (element.name) {
                        console.log(`${element.name}:`, element.value, element.type, element.checked);
                    }
                }
                console.log("=============================");
                
                const formData = new FormData(addPropertyForm);
                
                // Manually collect hosts value from bootstrap-select
                const hostsSelect = document.getElementById('hosts');
                const selectedHosts = Array.from(hostsSelect.selectedOptions).map(opt => opt.value);
                console.log("=== Manually Collected Hosts ===");
                console.log("Selected hosts:", selectedHosts);
                console.log("================================");
                
                // Manually collect amenities
                const amenityCheckboxes = document.querySelectorAll('input[name="amenities"]:checked');
                const selectedAmenities = Array.from(amenityCheckboxes).map(cb => cb.value);
                console.log("=== Manually Collected Amenities ===");
                console.log("Selected amenities:", selectedAmenities);
                console.log("================================");
                
                // Manually collect property collections
                const collectionCheckboxes = document.querySelectorAll('input[name="property_collections"]:checked');
                const selectedCollections = Array.from(collectionCheckboxes).map(cb => cb.value);
                console.log("=== Manually Collected Collections ===");
                console.log("Selected collections:", selectedCollections);
                console.log("================================");
                
                // Clear and re-add hosts to formData
                formData.delete('hosts');
                selectedHosts.forEach(host => {
                    formData.append('hosts', host);
                });
                
                // Clear and re-add amenities to formData
                formData.delete('amenities');
                selectedAmenities.forEach(amenity => {
                    formData.append('amenities', amenity);
                });
                
                // Clear and re-add collections to formData
                formData.delete('property_collections');
                selectedCollections.forEach(collection => {
                    formData.append('property_collections', collection);
                });
                
                // Add display picture to formData using the validated displayPictureFile
                if (displayPictureFile) {
                    formData.append('display_image', displayPictureFile);
                }
                
                const propertyPictures = document.querySelectorAll('.dropzone:not(#display-picture-dropzone)');
                // Add property pictures to formData
                propertyPictures.forEach(dropzone => {
                    const category_id = dropzone.getAttribute('data-category');
                    const images = dropzone.querySelectorAll('img:not(.delete-icon)');
                    console.log(`=== Property Pictures for category ${category_id} ===`);
                    console.log(`Images found:`, images.length);
                    images.forEach((img, index) => {
                        console.log(`Image ${index}:`, img.file);
                        console.log(`Image ${index} instanceof File:`, img.file instanceof File);
                        formData.append(`photos_${category_id}`, img.file);
                        formData.append(`category_ids_${category_id}`, category_id);
                    });
                });

                // Debug: Log what's being sent
                console.log("=== Frontend Debug ===");
                console.log("displayPictureFile:", displayPictureFile);
                console.log("displayPictureFile type:", typeof displayPictureFile);
                console.log("displayPictureFile instanceof File:", displayPictureFile instanceof File);
                console.log("Hosts field value:", document.getElementById('hosts').value);
                console.log("Hosts field selectedOptions:", Array.from(document.getElementById('hosts').selectedOptions).map(opt => opt.value));
                console.log("Form data entries:");
                for (let [key, value] of formData.entries()) {
                    console.log(`${key}:`, value);
                }
                console.log("=====================");

                // Send formData to backend
                console.log("=== Sending Form Data ===");
                console.log("FormData entries count:", Array.from(formData.entries()).length);
                console.log("FormData entries:");
                for (let [key, value] of formData.entries()) {
                    console.log(`${key}:`, value);
                }
                console.log("=========================");
                
                const response = await fetch('/api/properties/x', {
                    method: 'POST',
                    body: formData,
                });
                
                console.log("=== Response Received ===");
                console.log("Response status:", response.status);
                console.log("Response status text:", response.statusText);
                console.log("Response headers:", response.headers);
                console.log("=========================");

                if (!response.ok) {
                    const errorData = await response.json();
                    console.log('=== Error Response Details ===');
                    console.log('Failed to upload property:', errorData);
                    console.log('Error status:', response.status);
                    console.log('Error status text:', response.statusText);
                    console.log('==============================');
                    // uploadButton.disabled=false; // Removed disabled condition as requested
                    console.log('Error handling completed');
                    throw new Error(errorData.error || 'Failed to upload property');
                }

                const result = await response.json();
                console.log('=== Success Response Details ===');
                console.log('Property uploaded successfully:', result);
                console.log('Response status:', response.status);
                console.log('Response status text:', response.statusText);
                console.log('==============================');
                // uploadButton.disabled=false; // Removed disabled condition as requested
                console.log('Property creation completed successfully');
                alert('Property uploaded successfully');
                //window.location.href = '/api/properties/listing';
            } catch (error) {
                console.log('=== Catch Error Details ===');
                console.error('Error uploading property:', error);
                console.log('Error name:', error.name);
                console.log('Error message:', error.message);
                console.log('Error stack:', error.stack);
                console.log('==========================');
                alert('Failed to upload property');
            }
        });

        displayPictureDropzone.addEventListener('dragover', (e) => {
            e.preventDefault();
            //alert("displayPictureDropzone dragover");
            displayPictureDropzone.style.backgroundColor = '#e0e0e0';
        });
        
        displayPictureDropzone.addEventListener('dragleave', () => {
            alert("displayPictureDropzone dragleave");
            displayPictureDropzone.style.backgroundColor = '#fff';
        });
        
        displayPictureDropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            alert("displayPictureDropzone drop");
            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', () => {
            //alert("displayPictureDropzone click");
            const input = document.createElement('input');
            input.type = 'file';
            input.onchange = (e) => {
                const file = e.target.files[0];
                handleDisplayPicture(file);
            };
            input.click();
        });

        function handleDisplayPicture(file) {
            if (file && file.type.startsWith('image/')) {
                console.log("=== handleDisplayPicture Debug ===");
                console.log("File received:", file);
                console.log("File type:", file.type);
                console.log("File size:", file.size);
                console.log("File instanceof File:", file instanceof File);
                console.log("================================");
                
                const existingImg = displayPictureDropzone.querySelector('img:not(.delete-icon)');
                if (existingImg) {
                    alert('Only one display picture is allowed.');
                    return;
                }

                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => {
                    const img = document.createElement('img');
                    img.src = reader.result;
                    img.file = file;
                    displayPictureDropzone.appendChild(img);

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

                    deleteIcon.addEventListener('click', () => {
                        displayPictureDropzone.innerHTML = 'Display picture';
                        displayPictureFile = null;
                        displayPictureError.style.display = 'block';
                        console.log("=== File Deleted ===");
                        console.log("displayPictureFile cleared:", displayPictureFile);
                        console.log("================================");
                    });
                    displayPictureFile = file;
                    displayPictureError.style.display = 'none';
                    
                    console.log("=== File Stored Successfully ===");
                    console.log("displayPictureFile set to:", displayPictureFile);
                    console.log("================================");
                };
            }
        }

        const dropzones = document.querySelectorAll('.dropzone:not(#display-picture-dropzone)');
        
        dropzones.forEach(dropzone => {
            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);
            });
            
            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);
                };
                input.click();
            });
        });

        function handleFiles(files, dropzone) {
            console.log("=== handleFiles Debug ===");
            console.log("Files received:", files);
            console.log("Dropzone:", dropzone);
            console.log("==========================");
            
            files.forEach(file => {
                if (file.type.startsWith('image/')) {
                    console.log(`=== Processing file: ${file.name} ===`);
                    console.log("File type:", file.type);
                    console.log("File size:", file.size);
                    console.log("File instanceof File:", file instanceof File);
                    
                    const reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = () => {
                        const imgContainer = document.createElement('div');
                        imgContainer.style.position = 'relative';
                        imgContainer.style.display = 'inline-block';
                        imgContainer.draggable = true;

                        const img = document.createElement('img');
                        img.src = reader.result;
                        img.file = file;
                        imgContainer.appendChild(img);
                        
                        console.log(`=== File stored in img.file ===`);
                        console.log("img.file:", img.file);
                        console.log("img.file instanceof File:", img.file instanceof File);
                        console.log("================================");

                        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', () => {
                            imgContainer.remove();
                        });
                        dropzone.appendChild(imgContainer);

                        // 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'] = '';
                        });
                    };
                }
            });
        }
    });
</script>
<%- include("layout/footer") %>