<%- include('../layouts/header'); -%>
<style>
 @media screen and (max-width: 992px) {
     .footer-top-margin {
      margin-top: 43% !important;
    }
 }
  @media screen and (max-width: 600px) {
    .footer-top-margin {
      margin-top: 200% !important;
    }
    .close-button{
    right: 28% !important;
  }
  }
  .footer-top-margin {
    margin-top: 30%;
  }
  .close-button{
    text-align: center;
    width: 29px;
    border-radius: 110px;
    position: absolute;
    top: 0%;
    right: 22%;
    background-color: red;
    color: white;
    cursor: pointer;
  }
</style>
<div
  class="hero-wrap"
  style="background-image: url('images/bg_2.jpg')"
  data-stellar-background-ratio="0.5"
>
  <div class="overlay"></div>
  <div class="overlay-2"></div>
  <div class="container">
    <div
      class="row no-gutters slider-text justify-content-center align-items-center"
      style="width: 100% !important"
    >
      <div
        class="row block-9 justify-content-center mb-5 form-bottom-margin"
        style="width: 100%; margin-top: 9% !important"
      >
        <div class="col-md-12 align-items-stretch d-flex">
          <form
            action="/properties/addProperty"
            method="post"
            class="bg-light p-5 contact-form"
            style="width: 100%"
            enctype="multipart/form-data"
          >
            <h3 style="display: flex; justify-content: center"><% if(property?.name){ %>Update<% }else{ %>Add<% } %> Property</h3>
            <% if(successMessage){ %>
            <div class="alert alert-success">
              <strong>Success!</strong> <%- successMessage %>
            </div>
            <% } %> <% if(errorMessage){ %>
            <div class="alert alert-danger">
              <strong>Error!</strong> <%- errorMessage %>
            </div>
            <% } %>
            <div class="row">
              <div class="col-md-12 col-sm-12">
                <div class="form-group">
                  <input
                    type="file"
                    name="image"
                    id="property-images"
                    multiple
                    <% if(!property?.image){ %>required<% } %>
                    class="form-control"
                    placeholder="Images"
                  />
                </div>
              </div>
              <div class="col-md-12 col-12 mb-3">
                <label for="">Images</label>
                <div class="row" id="property-images-preview">
                  <% property?.propertyImages?.forEach(image=>{ %>
                  <div class="col-md-3 col-6 mb-2" style="position: relative;">
                    <img src="<%- !image?.path ? '' : image?.path %>" alt="" style="width: 200px;height: 100px;">
                    <span class="close-button" data-id="<%- image?.id %>" data-property-id="<%- property?.id %>" >X</span>
                  </div>
                  <% }) %>
                </div>
              </div>
              <div class="col-md-6 col-sm-12">
                <div class="form-group">
                  <input
                    type="text"
                    name="name"
                    class="form-control"
                    value="<% if(property?.name){ %><%- property.name %><% } %>"
                    required
                    placeholder="Property Name"
                  />
                </div>
              </div>
              <div class="col-md-6 col-sm-12">
                <div class="form-group">
                  <select name="type" required class="form-control" id="property-types">
                    <option value="">Type</option>
                    <% PropertyTypes?.forEach(type=>{ %>
                    <option value="<%- type?.id %>" <% if(property?.type == type?.id){ %>selected<% } %>><%- type?.value %></option>
                    <% }) %>
                  </select>
                </div>
              </div>
              <div class="col-md-6 col-sm-12">
                <div class="form-group">
                  <select name="status" required class="form-control" id="">
                    <option value="">Status</option>
                    <% PropertyStatus?.forEach(status=>{ %>
                    <option value="<%- status?.id %>" <% if(property?.status == status?.id){ %>selected<% } %>>
                      <%- status?.value %>
                    </option>
                    <% }) %>
                  </select>
                </div>
              </div>
              <div class="col-md-6 col-12 mb-3">
                <input
                  type="number"
                  name="totalPrice"
                  required
                  class="form-control"
                  placeholder="Total Price"
                  value="<% if(property.totalPrice){%><%- property.totalPrice %><% } %>"
                  id="total-price"
                />
              </div>
              <div class="col-md-6 col-sm-12">
                <div class="form-group">
                  <input
                    type="number"
                    name="price"
                    required
                    id="discounted-price"
                    value="<% if(property?.price){ %><%- property.price %><% } %>"
                    class="form-control"
                    placeholder="Discounted Price"
                  />
                </div>
              </div>
              <div class="col-md-6 col-sm-12">
                <div class="form-group">
                  <input
                    type="text"
                    required
                    name="street"
                    value="<% if(property?.address?.street){%><%- property?.address?.street %><% } %>"
                    class="form-control"
                    placeholder="Street"
                  />
                </div>
              </div>
              <div class="col-md-6 col-sm-12">
                <div class="form-group">
                  <select name="state" class="form-control" id="state_changed">
                    <option value="">Select state</option>
                    <% States?.forEach(state=>{ %>
                      <option value="<%- state?.name %>" <% if(property?.address?.state && property?.address?.state == state?.name){%>selected<% } %>><%- state?.name %></option>
                    <% }) %> 
                  </select>
                </div>
              </div>
              <div class="col-md-6 col-sm-12">
                <div class="form-group">
                  <select name="city" class="form-control" id="city-changed">
                    <option value="">Select city</option>
                  </select>
                </div>
              </div>
              <% if(property){ %>
                <input type="hidden" name="id" value="<%- property?.id %>" />
                <input
                  type="hidden"
                  name="addressId"
                  value="<%- property?.addressId %>"
                />
                <% } %>
              <div class="col-md-6 col-sm-12">
                <div class="form-group">
                  <input
                    type="number"
                    class="form-control"
                    name="postalCode"
                    id="postal-code"
                    required
                    value="<% if(property?.address?.postalCode){%><%- property?.address?.postalCode %><% } %>"
                    placeholder="Postal Code"
                  />
                </div>
              </div>
              <div class="col-md-6 col-sm-12 add-remove-property">
                <div class="form-group">
                  <select name="furnishing" class="form-control" id="">
                    <option value="">Furnishing</option>
                    <% PropertyFurnishing?.forEach(furnishing=>{ %>
                    <option value="<%- furnishing?.id %>" <% if(property?.furnishing == furnishing?.id){ %>selected<% } %>>
                      <%- furnishing?.value %>
                    </option>
                    <% }) %>
                  </select>
                </div>
              </div>
              <div class="col-md-12 col-sm-12">
                <div class="form-group">
                  <textarea name="description" class="form-control"
                  placeholder="Description" id="editor" cols="30" rows="10"><% if(property?.description){%><%- property?.description %><% } %></textarea>
                  </select>
                </div>
              </div>
              <div class="col-md-12 col-sm-12">
                <h5>Property Features</h5>
              </div>
              <% PropertyFeature?.forEach(feature=>{ %>
                <% let
                featureValue = property?.propertyFeatures?.find(e=> e.key == feature?.id)
                let sqftArr = ['floorarea','lotarea'];
                let noOfArr = ['bathroom','bedroom'];
                %>
              <div class="col-md-6 col-sm-12 <% if(noOfArr.includes(feature?.id)){ %>add-remove-property<% }else if(!sqftArr.includes(feature?.id)){ %>add-remove-property<% } %>">
                <div class="form-group">
                  <input
                    type="text"
                    name="<%- feature?.id %>"
                    class="form-control"
                    value="<% if(featureValue){ %><%- featureValue?.value %><% } %>"
                    placeholder="<% if(sqftArr.includes(feature?.id)){ %><%- feature?.value %> (in sqft)<% }else if(noOfArr.includes(feature?.id)){ %>No Of <%- feature?.value %><% }else{ %><%- feature?.value %><% } %>"
                  />
                </div>
              </div>
              <% }) %>
            </div>
            <div class="form-group">
              <input
                type="submit"
                value="<% if(property?.name){ %>Update<% }else{ %>Add<% } %> Property"
                class="btn btn-primary py-3 px-5"
              />
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<%- include('../layouts/footer'); -%>

<script>
  $(document).ready(()=>{
    ClassicEditor
            .create(document.querySelector('#editor'), {
                alignment: {
                    options: ['left', 'right',"center"]
                }
            })
            .catch(error => {
                console.error(error);
            });
  })
  setTimeout(() => {
    $(".alert").hide();
  }, 2000);
  $("#total-price").keyup(e=>{
    let amount = $(e.target).val();
    $("#discounted-price").val(amount)
  });
  $(".close-button").click(e=>{
    console.log("-0-=-==in close button-=-=-")
    let id = $(e.target).attr("data-id")
    let propertyId = $(e.target).attr("data-property-id");
    if(id && propertyId){
      window.location.href = `/properties/deleteImage/${propertyId}/${id}`;
    }else{
      console.log($(e.target).parent());
      $(e.target).parent().remove();
    }
  })

  $("#property-images").on("change",function(){
    console.log(this.files)
    let arr = Object.keys(this.files ?? {});
    arr?.map(index=>{
      let file = this.files[index];
      var reader = new FileReader();
      reader.onload = function(event) {
        let imgTag = `<div class="col-md-3 col-6 mb-2 preview-image" style="position: relative;">
                    <img src="${event.target.result}" alt="" style="width: 200px;height: 100px;">
                    <span class="close-button" data-id="" data-property-id="">X</span>
                  </div>`;
          $('#property-images-preview').append(imgTag);
          $(".close-button").click(e=>{
              let id = $(e.target).attr("data-id")
              let propertyId = $(e.target).attr("data-property-id");
              if(id && propertyId){
                window.location.href = `/properties/deleteImage/${propertyId}/${id}`;
              }else{
                console.log($(e.target).parent());
                $(e.target).parent().remove();
              }
            })
      };
      reader.readAsDataURL(file);
    })
  });
  $(document).ready(()=>{
    let states = <%- JSON.stringify(States) %>;

    $("#city-changed").change(e=>{
      let pincode = $(e.target).find(':selected');
      pincode = pincode.attr("data-attr-pincode")
      $("#postal-code").val(pincode);
    })
    $("#state_changed").change((e)=>{
      let name = $(e.target).val();
      if(name){
        let cityName = `<%- property?.address?.city || "" %>`;
        let cities = states.find(e=> e.name?.toLowerCase() == name?.toLowerCase())?.cities || [];
        str = `<option value="">Select city</option>`;
        cities?.map(city=>{
          str += `<option value="${city?.name}" ${cityName == city?.name ? "selected" : ""}  data-attr-pincode="${city?.pinCode}">${city?.name}</option>`
        });

        $("#city-changed").html(str)
      }
    })
    let values = `<%- property?.type %>`
    showHidePropertyDetails(values);

    $("#property-types").change(e=>{
      let val = $(e.target).val();
      showHidePropertyDetails(val);
    })
    
    function showHidePropertyDetails(val){
      if(val == "land"){
        $(".add-remove-property").hide();
      }else{
        $(".add-remove-property").show();
      }
    }
  })
</script>
