<div class="modal " id="prestation-modal">
    <div class="modal-background"></div>
    <div class="modal-card">
      
      <section class="modal-card-body">
        <div class="card">
          <header class="card-header">
            <p class="card-header-title">
              <span class="icon"><i class="mdi mdi-ballot"></i></span>
              Nouvelle prestation
            </p>
            
            <button class="delete" onclick="closePopup('prestation-modal')" aria-label="close"></button>
          </header>

          <div class="card-content">
            <form method="post" id="prestation-form"  enctype="multipart/form-data" >
              {% csrf_token %}

              <input type="hidden" name="employeeId" id="employeeId" value="">

              <label class="label is-small">Employé</label>
              <div class="field is-horizontal">
                <div class="field-body is-flex is-flex-direction-row is-justify-content-center">
                  <div class="field is-expanded" style="position: relative;">
                    
                    <p class="control is-expanded has-icons-left has-icons-right">
                      <input class="input" type="text" name="employee" placeholder="Rechercher un employé ... (nom, téléphone, email, code)" id="employee-autocomplete" required>
                      <span class="icon is-small is-left"><i class="mdi mdi-account-search"></i></span>
                      {% comment %} <span class="icon is-small is-right"><i class="mdi mdi-lock-reset"></i></span> {% endcomment %}
                    </p>
                    <div class="box has-white-bg p-2"  id="employee-suggestions" style="display: none; position: absolute; z-index: 1000;width:100%"></div>
                  </div>
                  
                </div>
              </div>
              
              <hr>


              {% for group in form  %}
                <div class="subtitle is-6 mb-2" style="font-size:10px">{{group.name}}</div>
                
                    {% for gf in group.fields  %}


                      <div class="field is-horizontal">
                        <div class="field-body">

                            
                        {% for field  in gf  %}
                        
                            {% if field.type == 'input' or field.type == 'text' or field.type == 'email' or field.type == "tel"  or field.type == "number" %}
                              <div class="field">
                                <label class="label is-small">{{field.label}} {% if field.required %}<span style="color:red !important">*</span> {% endif %}</label>
                                <p class="control is-expanded ">
                                  <input class="input" type="{{field.type}}" name="{{field.name}}" placeholder="{{field.label}}" {% if field.required %} required {% endif %} {% if field.type == 'number' %} value="{{field.min}}" min="{{field.min}}" max= "{{field.max}}" step="{{field.step}}" {% endif %}>
                                  {% comment %} <span class="icon is-small is-left"><i class="mdi mdi-account"></i></span> {% endcomment %}
                                </p>
                              </div>
                            {% endif %}
                            
                            {% if field.type == 'date' %}

                            <div class="field">
                              <label class="label is-small">{{field.label}} {% if field.required %}<span style="color:red !important">*</span> {% endif %}</label>
                              <p class="control is-expanded has-icons-left">
                                <input  class="input" type="{{field.type}}" name="{{field.name}}" placeholder="{{field.label}}" {% if field.required %} required {% endif %}  >
                                <span class="icon is-small is-left"><i class="mdi mdi-calendar-check"></i></span>
                              </p>
                            </div>
                            
                            {% endif %}


                            {% if field.type == 'select' %}
                              <div class="field">
                                <label class="label is-small">{{field.label}} {% if field.required %}<span style="color:red !important">*</span> {% endif %}</label>
                                <div class="control ">
                                  <div class="select is-fullwidth">
                                    <select name="{{field.name}}" {% if field.required %} required {% endif %} {% if field.disabled %} disabled {% endif %}>
                                      <option value="">Sélectionner {{field.label}}</option>
                                      {% for key, label in field.options %}
                                        <option value="{{ key }}">{{ label }}</option>
                                      {% endfor %}
                                    </select>
                                  </div>
                                  
                                </div>
                              </div>
                            {% endif %}

                            {% if field.type == "file" %}
                                <div class="field mb-2">
                                  <label class="label is-small">{{field.label}} {% if field.required %}<span style="color:red !important">*</span> {% endif %}</label>
                                  <p class="control is-expanded has-icons-left">
                                    <input class="input" accept="application/pdf" type="{{field.type}}" name="{{field.name}}" placeholder="{{field.placeholder}}" {% if field.required %} required {% endif %}  >
                                    <span class="icon is-small is-left"><i class="mdi mdi-file-account"></i></span>
                                  </p>
                                </div>
                            {% endif %}

                            {% if field.type == "textarea"  %}
                                  <div class="field mb-2">
                                  <label class="label is-small">{{field.label}} {% if field.required %}<span style="color:red !important">*</span> {% endif %}</label>
                                  <p class="control is-expanded has-icons-left">
                                    <textarea class="textarea" row="3" name="{{field.name}}" placeholder="{{field.placeholder}}" {% if field.required %} required {% endif %}></textarea>
                                     
                                  </p>
                                </div>
                            {% endif %}


                        {% endfor %}
                        </div>
                      </div>
                        
                    
                    {% endfor %}
                    
                <hr>
              
              {% endfor %}
              
            
              <div class="field is-horizontal">
                <div class="field-body">
                  <div class="field">
                    <div class="field is-grouped">
                      <div class="control">
                        <button id="prestation-submit" type="submit" class="button is-info is-small">
                          <span>Sauver</span>
                        </button>
                      </div>
                      <div class="control">
                        <button onclick="closePopup('prestation-modal')" id="prestation-cancer" type="button" class="button is-danger is-light is-small">
                          <span>Annuler</span>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
            </form>

            
            {% comment %} Recapchat input {% endcomment %}
            <input type="hidden" name="g-recaptcha-response" id='recaptcha'>
            <script src="https://www.google.com/recaptcha/api.js?render={{RECAPTCHA_PUBLIC_KEY}}"></script>
            
            
          </div>
        </div>

        <!-- Content ... -->
      </section>
      
    </div>
</div>







<script type="text/javascript">

  $(document).ready(function () {
    $("#prestation-form").submit(function (event) {
        event.preventDefault()
        var formData = new FormData(this);
       grecaptcha.execute('{{RECAPTCHA_PUBLIC_KEY}}').then(function (token) {
        
            
            formData.append('csrfmiddlewaretoken', document.getElementsByName('csrfmiddlewaretoken')[0].value);
            formData.append('recap', token);

            $.ajax({
                type: "POST",
                url: "{% url 'app:createOrUpdatePrestation' %}",
                processData: false,
                contentType: false,
                complete: function () {
                },
                data: formData,

                error: function (data) {
                    $("#prestation-submit").removeClass("is-loading");
                    $("#prestation-submit").attr("disabled", false);
                    $("#prestation-cancel").attr("disabled", false);

                    Swal.fire({
                        title: "Erreur",
                        text: "Une erreur s'est produite lors de la soumission du formulaire.",
                        icon: "error",
                    });

                    console.log(data)

                },
                beforeSend: function () {

                    $("#prestation-submit").addClass("is-loading");
                    $("#prestation-submit").attr("disabled", true);
                    $("#prestation-cancel").attr("disabled", true);
                },
                success: function (data) {

                    $("#prestation-submit").removeClass("is-loading");
                    $("#prestation-submit").attr("disabled", false);
                    $("#prestation-cancel").attr("disabled", false);


                    if (data['status'] == "success") {
                        Swal.fire({
                            title: "Réussit",
                            text: data.message,
                            icon: "success",
                            timer: 1000,
                        });
                        document.getElementById("prestation-form").reset()
                        
                        if($("#forContract").val() != "true"){
                          goTo("{% url 'app:prestations' %}")
                          closePopup('prestation-modal')
                        }else{
                          $("#prestation-autocomplete").val(data.prestation.name);
                          $("#prestationContractId").val(data.prestation.id);
                          $("#prestation-suggestions").hide();
                          closePopup('prestation-modal')
                        }
                        
                        
                    } else {
                        Swal.fire({
                            title: "Erreur",
                            text: data.message,
                            icon: "error",
                        });
                    }



                }
            });
        });
        return false;
   });
});


// autocomplete

  $(document).ready(function () {
      
      $("#employee-autocomplete").on("keydown", function () {
          
          $("#employeeId").val("");
          console.log( "reset "+ $("#employeeId").val())
          $("#employee-suggestions").hide();
      });
       
      $("#employee-autocomplete").on("keyup", function () {


          let search = $(this).val();
          if (search.length < 2) {
              $("#employee-suggestions").hide();


              return;
          }
  
          $.ajax({
              url: "{% url 'app:employeesAutocomplete' %}",
              type: "POST",
              data: {
                  search: search,
                  csrfmiddlewaretoken: "{{ csrf_token }}"
              },
              success: function (response) {
                  if (response.status === "success") {
                      console.log(response.data.employees)
                      let suggestions = response.data.employees;
                      let suggestionsBox = $("#employee-suggestions");
                      suggestionsBox.empty();
  
                      if (suggestions.length > 0) {
                          suggestions.forEach(function (employee) {
                              suggestionsBox.append(`
                                  <div class="dropdown-item employee-suggestion" data-id="${employee.id}" data-name="${employee.name} ">
                                     <i class="mdi mdi-account"></i> &nbsp; ${employee.code} ${employee.name} (${employee.phone})
                                  </div>
                              `);
                          });
                          suggestionsBox.show();
                      } else {
                          suggestionsBox.hide();
                      }
                  }
              }
          });
      });
  
      $(document).on("click", ".employee-suggestion", function () {
          let fullName = $(this).data("name");
          let employeeId = $(this).data("id");
  
          $("#employee-autocomplete").val(fullName);
          $("#employeeId").val(employeeId);
          $("#employee-suggestions").hide();

          console.log(employeeId)
          console.log($("#employeeContractId").val())
      });
  
      $(document).click(function (e) {
          if (!$(e.target).closest("#employee-autocomplete, #employee-suggestions").length) {
              $("#employee-suggestions").hide();
          }
      });
  });
  



</script>