<% var entity = 'User';%>
<%if(type == 'host'){%>
    <% entity = 'Host'; %>
<%}%>
<%- include("../layout/header",{ title: `Edit ${entity}`}) %>
<div class="propertyadd">
    <div class="row headingsection">
        <div class="col-sm-12"><h1>Edit <%=entity%></h1></div>
    </div>
    <div class="formcontainer">
        <h1 class="propertyheadingblue">Personal Details</h1>
        <hr> 
        <form id="useredit" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="id" id="user-id" value="<%=user.id%>"/>
            <div class="row form-row">
                <div class="form-group col-md-4">
                    <label for="">Firstname</label>
                    <input type="text" name="firstname" value="<%=user.firstname%>" placeholder="Firstname" required>     
                </div>
                <div class="form-group col-md-4">
                    <label for="">Lastname</label>
                    <input type="text" name="lastname" value="<%=user.lastname%>" placeholder="Lastname" required>     
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-2">
                    <div class="mb-2">
                        <% 
                            var maleChecked = "";
                            var femaleChecked = "";
                        %>
                        <%if(user.gender == "Male"){%>
                            <%maleChecked = "checked";%>
                        <%}%>
                        <%if(user.gender == "Female"){%>
                            <%femaleChecked = "checked";%>
                        <%}%>
                        <label for="">Gender</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="yes" value="Male" <%=maleChecked%>>
                            <label class="form-check-label" for="yes">M</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="no" value="Female" <%=femaleChecked%>>
                            <label class="form-check-label" for="no">F</label>
                        </div>
                    </div>
                </div>
                <div class="form-group col-md-4">
                    <label for="">Birthday</label>
                    <input type="text" name="date_of_birth" value="<%=user.date_of_birth%>" class="datepicker" placeholder="">     
                </div>
                <div class="form-group col-md-4">
                    <label for="">Date of Joining</label>
                    <input type="text" name="date_of_joining" value="<%=user.date_of_joining%>" class="datepicker" placeholder="">     
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-4">
                    <label for="">Email</label>
                    <input type="email" name="email" id="email" value="<%=user.email%>" placeholder="Email" required>     
                </div>
                <div class="form-group col-md-4">
                    <label for="">Phone</label>
                    <input type="text" name="phone" id="phone" value="<%=user.phone%>" placeholder="Phone No" required>     
                </div>
            </div><br>
            <h1 class="propertyheadingblue">Address</h1>
            <hr>
            <div class="row form-row">
                <div class="form-group col-md-4">
                    <input type="text" name="address_line_1" value="<%=user.address_line_1%>" placeholder="Address Line 1">     
                </div>
                <div class="form-group col-md-4">
                    <input type="text" name="address_line_2" value="<%=user.address_line_2%>" placeholder="Address Line 2">     
                </div>
            </div>
            <div class="row form-row">
                <div class="form-group col-md-3">
                    <input type="text" name="city" value="<%=user.city%>" placeholder="City">     
                </div>
                <div class="form-group col-md-3">
                    <input type="text" name="state" value="<%=user.state%>" placeholder="State">     
                </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 => { %>
                            <% if(country.id == selectedCountry){%>
                            <option value="<%= country.id %>" selected><%= country.display %></option>
                            <% }else{%>
                            <option value="<%= country.id %>"><%= country.display %></option>
                            <% }%>
                        <% }); %>
                    </select>
                </div>
            </div>
            <% if(type == 'host'){%>
                <br>
                <h1 class="propertyheadingblue">Properties</h1>
                <hr>
                <div class="row form-row">
                    <div class="form-group col-md-6">
                        <select class="form-control selectpicker" name="properties" id="properties" multiple>
                            <option value="">Select Properties</option>
                            <% allProperties.forEach(prop => { %>
                                <% if(user.hostProps.includes(prop.id)){%>
                                    <option value="<%= prop.id %>" selected><%= prop.listing_name %></option>
                                <%}else{%>
                                    <option value="<%= prop.id %>"><%= prop.listing_name %></option>
                                <%}%>
                                
                            <% }); %>
                        </select>
                    </div>
                </div>
            <%}%>
            <input type="hidden" name="type" id="user-type" value="<%=type%>"/>
            <div class="row headingsection">
                <div class="col-sm-12">
                    <button type="button" class="greenbutton" id="upload-button">Save</button>&nbsp;&nbsp;
                    <a href="/admin/users/<%=type%>"><button type="button" class="transparant">Discard</button></a>
                </div>
            </div>
        </form>
    </div>
</div>
<script src="/api/public/users.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const uploadButton = document.getElementById('upload-button');
        const editUserForm = document.getElementById('useredit');
        const emailField = document.getElementById('email');
        const phoneField = document.getElementById('phone');
        const userId = document.getElementById('user-id').value;
        const originalEmail = emailField.value;
        const originalPhone = phoneField.value;
        const userType = document.getElementById('user-type').value;

        emailField.addEventListener('blur', async() => {
            var exists = await checkUnique('email',emailField,userType,userId);
            if(exists){
                emailField.value= originalEmail;
                alert("Email already exists");
            }
        });
        phoneField.addEventListener('blur', async() => {
            var exists = await checkUnique('phone',phoneField,userType,userId);
            if(exists){
                phoneField.value= originalPhone;
                alert("Phone already exists");
            }
        });
        
        $( function() {
            $( ".datepicker" ).datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'dd M yy',
                yearRange: "c-100:today",
                maxDate: "today"
            });
        });
        uploadButton.addEventListener('click', async () => {
            if (!editUserForm.checkValidity()) {
                editUserForm.reportValidity();
                return;
            }
            try {
                uploadButton.disabled=true;
                const formData = new FormData(editUserForm);
                console.log(formData);
                // Send formData to backend
                const response = await fetch('/admin/user/save', {
                    method: 'POST',
                    body: formData,
                });

                if (!response.ok) {
                    console.log('Failed to save user:', response.json());
                    uploadButton.disabled=false;
                    throw new Error('Failed to save user');
                }

                const result = await response.json();
                if(result.success){
                    window.location.href = `/admin/users/${userType}/${result.flash}`;
                }else{
                    alert(result.error);
                }
                console.log('User saved successfully:', result);
                uploadButton.disabled=false;
                alert('User saved successfully');
            } catch (error) {
                console.error('Error saving request:', error);
                alert('Failed to save User');
            }
        });
    });
</script>
<%- include("../layout/footer") %>