<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ app.name }}</title>
    <style>
      .material-symbols-outlined {
        font-variation-settings:
        'FILL' 0,
        'wght' 400,
        'GRAD' 0,
        'opsz' 48
      }

      .material-icons {
        vertical-align: middle;
        line-height: 0 !important;
        position: relative;
        top: -1px;
      }
      .custom-file-input ~ .custom-file-label::after {
        content: "Choose file";
        background-color:#0072bc;
        color:white;
        position: absolute;
        top:38px;
        left: 0px;
      }
      .custom-file .custom-file-input {
        cursor: pointer;
        height:76px;
      }
      label.custom-file-label {
        border:0px;
      }
      .custom-file {
        max-width: 300px;
        margin-bottom:20px;
        margin-top:20px;
      }
      .after-hide::after {
        display: none;
      }

      table.table-fit {
          width: auto !important;
          table-layout: auto !important;
      }
      table.table-fit thead th, table.table-fit tfoot th {
          width: auto !important;
      }
      table.table-fit tbody td, table.table-fit tfoot td {
          width: auto !important;
      }
    </style>
    {{ bootstrap.load_js() }}
    {{ bootstrap.load_css() }}
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Icons">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js" integrity="sha512-42PE0rd+wZ2hNXftlM78BSehIGzezNeQuzihiBCvUEB3CVxHvsShF86wBWwQORNxNINlBPuq7rG4WWhNiTVHFg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bs-stepper/dist/css/bs-stepper.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bs-stepper/dist/js/bs-stepper.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
    <link rel="stylesheet" href="https://unpkg.com/tagin@2.0.2/dist/tagin.min.css">
    <script src="https://unpkg.com/tagin@2.0.2/dist/tagin.min.js"></script>
    <!-- Popperjs -->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha256-BRqBN7dYgABqtY9Hd4ynE+1slnEw+roEPFzQ7TRRfcg=" crossorigin="anonymous"></script>
    <!-- Tempus Dominus JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/@eonasdan/tempus-dominus@6.7.7/dist/js/tempus-dominus.min.js" crossorigin="anonymous"></script>

    <!-- Tempus Dominus Styles -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@eonasdan/tempus-dominus@6.7.7/dist/css/tempus-dominus.min.css" crossorigin="anonymous">
    <script>
      function showError(error) {
        switch(error.code) {
          case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
          case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
          case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
          case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
        }
      }
      function getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
          document.getElementById("location").innerHTML = "Geolocation is not supported by this browser.";
        }
      }
      
      function showPosition(position) {
        document.getElementById("location").innerHTML = "Lat: " + position.coords.latitude +
        " Lng: " + position.coords.longitude;
      }
      </script>
    {% if forms %}
    <script>
      
      //var progress = new Stepper($('.progress')[0]);
      $(document).ready(function () {
        //$.fn.modal.Constructor.prototype.enforceFocus = function() {};
        //console.log(document.querySelector('.tagin'));
        //new Tagin(document.querySelector('.tagin'));

        var stepper = new Stepper($('.bs-stepper')[0]);

        $(".previous_button").on("click", function() {
          stepper.previous();
        });
        $(".next_button").on("click", function() {
          stepper.next();
        });

        //$('.multiselect').multiselect({maxHeight: 200, enableFiltering: true, enableCaseInsensitiveFiltering: true, numberDisplayed: 10, buttonWidth: '100%'});
        $('.fa-solid').removeClass('fa-solid').addClass('fa');
        getLocation();

        $('.menu-item-button').on('click', function(event) {
          const target = $(this).attr('data-target');
          //console.log(target);
          if(target === '#form_UploadForm' || target === '#form_TypeUploadForm') {
            //console.log($($(this).attr('data-target')).find('.modal-footer #create_submitting'));
            $($(this).attr('data-target')).find('.modal-body .progress').hide();
            $($(this).attr('data-target')).find('.modal-footer #create_submit').hide();
            //$($(this).attr('data-target')).find('.modal-footer #create_cancel').hide();
            $($(this).attr('data-target')).find('.modal-footer #create_submitting').hide();
            //const t = $($(this).attr('data-target')).find('.tagin');

            // const tagin = new Tagin();
            //console.log($($(this).attr('data-target')).find('.modal-body #control_target').val())

            $(document).on('change', '#file', function(e) {
              console.log(e);
              console.log(e.target.files);
              //console.log($('#file')[0].files);
              var nextSibling = e.target.nextElementSibling;
              if (e.target.files && e.target.files.length > 0) {
                  nextSibling.innerText = e.target.files[0].name;
                  //$('#create_submit').show();
                  //$('#create_cancel').show();
                  //$('#update_submit').show();
                  //$('#update_cancel').show();
                  $('.custom-file-label').addClass('after-hide');
                  $('#create').submit(function(){
                      $(target).find('.modal-body #create_submit').hide();
                      $(target).find('.modal-body #create_submitting').show();
                      //console.log($(this).children('#file'));
                      //console.log($(target).find('.modal-body #control_target').val())
                      $.getJSON({ 
                                  url: $('#create').attr('action') + '/upload-url',
                                  data: {
                                    filename: e.target.files[0].name,
                                    size: e.target.files[0].size,
                                    parent_id: $('#parent_id').val(),
                                    target: $(target).find('.modal-body #control_target').val(),
                                    processing: 'true',
                                    extracted: 'false'
                                  },
                                  success: function(result) {
                                    console.log('getjson', result);
                                    const formData = new FormData();
                                    Object.keys(result['fields']).forEach(key => {
                                      formData.append(key, result['fields'][key]);
                                    });
                                    formData.append('file', e.target.files[0]);
                                    $('.progress').show();
                                    $.ajax({
                                      xhr: function() {
                                            var xhr = new window.XMLHttpRequest();
                                            xhr.upload.addEventListener("progress", function(evt) {
                                                console.log(evt);
                                                if (evt.lengthComputable) {
                                                    var percentComplete = evt.loaded / evt.total;
                                                    percentComplete = parseInt(percentComplete * 100);
                                                    $('.progress-bar').css('width',percentComplete+"%");
                                                    $('.progress-bar').html(percentComplete+"%");
                                                    if (percentComplete === 100) {

                                                }
                                              }
                                            }, false);
                                            return xhr;
                                          },
                                      url: result['url'],
                                      type: 'POST',
                                      data : formData,
                                      processData: false,
                                      contentType: false,
                                      success: function(result2){
                                        console.log(result2);
                                        $.ajax({
                                          dataType: "json",
                                          type: 'POST',
                                          url: $('#create').attr('action') + '/upload-confirm',
                                          data: JSON.stringify({
                                            target: $(target).find('.modal-body #control_target').val(),
                                            item_id: result['fields']['key'], 
                                            filename: e.target.files[0].name, 
                                            size: e.target.files[0].size}),
                                          contentType: "application/json; charset=utf-8",
                                          success: function(result3) {
                                            if ($(target).find('.modal-body #control_target').val() === 'type') {
                                              window.location.href = '/types/'  + result['fields']['key'];
                                            } else {
                                              window.location.href = '/items/'  + result['fields']['key'];
                                            }
                                            
                                          }
                                        });
                                      }
                                    });
                                  }
                                });
                      
                      return false;
                  });
                  $('#create').submit();
                } else {
                  nextSibling.innerText = '';
                  e.target.value = '';
                }
                
              });  
          
          
          }

          const tags_element = $($(this).attr('data-target')).find('.tagin');
          
          if (tags_element.length > 0) {
            //TODO: check if tagin already exists
            let tagin_element = tags_element[0];
            let classes = tagin_element.classList;
            if (!classes.contains('tagin-init')) {
              const tagin = new Tagin(tagin_element);
              classes.add('form-control', 'tagin', 'tagin-init');
              tagin_element = $(tagin_element).find('.tagin')[0];
            }
          }

          $($(this).attr('data-target')).find('.multiselect').multiselect({maxHeight: 600, enableFiltering: true, enableCaseInsensitiveFiltering: true, numberDisplayed: 10, buttonWidth: '100%'});
          
          const picker_elements = $($(this).attr('data-target')).find('.datetimepicker');
          
          if (picker_elements.length > 0) {
            //TODO: check if tagin already exists
            Array.from(picker_elements).forEach(e => {
              let classes = e.classList;
              if (!classes.contains('picker-init')) {
                const picker = new tempusDominus.TempusDominus(e);
                classes.add('input-group', 'date', 'datetimepicker', 'picker-init');
              }
            });
          }

          $('.fa-solid').removeClass('fa-solid').addClass('fa');

          
          //$($(this).attr('data-target')).find('.datetimepicker').datetimepicker();
          //const types_element = $($(this).attr('data-target')).find('.multiselect');
          //Array.from(types_element).multiSelect({maxHeight: 600, enableFiltering: true, enableCaseInsensitiveFiltering: true, numberDisplayed: 10, buttonWidth: '100%'});
          /*
          Array.from(types_element).forEach(e => {
            console.log(e);
            e.multiselect({maxHeight: 600, enableFiltering: true, enableCaseInsensitiveFiltering: true, numberDisplayed: 10, buttonWidth: '100%'})
          });
          */
          //$($(this).attr('data-target')).find('.modal-body #control_id').val($(this).attr('data-id'));
          //$($(this).attr('data-target')).find('.modal-body #control_type').val($(this).attr('data-type')).change();
          //$($(this).attr('data-target')).find('form').attr('action', '/' + $(this).attr('data-resource'));
          //$($(this).attr('data-target')).find('.modal-body #control_name').val($(this).attr('data-name'));
          //$($(this).attr('data-target')).find('.modal-header #title-name').text($(this).attr('data-name'));
          //const item = $(this).attr('data-item');
          //$($(this).attr('data-target')).find('.form-control').each(function () { updateForm($(this).attr('name'), item, $(this))});
          //todo populate edit form with item attributes
          //console.log('edit:', $(this).attr('data-id'), $(this).attr('data-target'));
        });

        
        
      });
      
      $(document).ready(function(){
        //console.log('document ready')
        
      }); 
    </script>
    <script>
      $(document).ready(function() {
          $('.item-select-ctrl').each(function() {
              // Save a reference to the current element
              var $element = $(this);
              // Make an AJAX call to fetch data and populate the dropdown
              $.getJSON({
                  url: $element.data('path'), // Replace this with your API endpoint
                  data: $element.data('query'),
                  success: function(data) {
                      // Loop through the data and create dropdown options
                      $.each(data, function(index, item) {
                          $element.append($('<option></option>').attr('value', item.id).text(item.name));
                      });
                  },
                  error: function() {
                      alert('Error fetching data');
                  }
              });
          });
          $('.form-check-input').on('click', function(event) {
            if (this.checked) {
              this.value = '1';
            } else {
              this.value = '0';
            }
          });
      });
  </script>
    {% endif %}
</head>
<body>  

<!-- BeginRender world app -->
    
<!-- BeginBars -->
      <!-- BeginWorldBar -->
        
      <!-- EndWorldBar -->
      <!-- BeginAppsBar -->
  
      <!-- EndAppsBar -->
      <!-- BeginAccountBar -->
  
      <!-- EndAccountBar -->
    <!-- EndBars -->
    
    <!-- BeginViews -->
    <!-- EndViews -->
    
<!-- EndRender world app -->
<div class="container-fluid p-0">
  {% include "nav.html" %}
  <main role="main">
    <div class="container-fluid p-0">
      {% block content %}{% endblock %}
    </div>
  </main>
  {% if forms %}
    <input type="hidden" id="parent_id" name="parent_id" value="{{item.id}}">
    {% for form in forms %}
    <div class="modal fade itemform" id="form_{{form.name}}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          {% if form.attributes['upload'] == 'true' %} 
            <form enctype="multipart/form-data" id="create" action="/{{form.attributes['path']}}" method="post">
              <div class="modal-header">
                {{form.attributes['type']}}
                {% if form.attributes['type'] %} 
                  <h5 class="modal-title" id="exampleModalLabel">{{form.attributes['title_prefix']}} {{form.attributes['type']}}</h5>
                {% else %}
                    <h5 class="modal-title" id="exampleModalLabel">{{form.attributes['title_prefix']}} {{item.name}}</h5> 
                {% endif %}
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                {% if form.attributes['text'] %}
                <div>
                  {{form.attributes['text']}}
                </div>
                {% endif %}
                {% for control in form.items %}
                  {% with item=item, control=control, form=form %}
                    {% include "control.html" %}
                  {% endwith %}
                {% endfor %}
                <div class="form-group">
                  <div class="custom-file" id="customFile" lang="sr">
                    <input type="file" class="custom-file-input" id="file" aria-describedby="fileHelp" name="file">
                      <label class="custom-file-label" for="file">
                        File not selected...
                      </label>
                  </div>
                </div>
                <div class="progress" >
                  <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:20%;">
                  </div>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="create_cancel">Cancel</button>
                <button type="submit" class="btn btn-primary" id="create_submit">{{form.attributes['submit_text']}}</button>
                <button type="button" class="btn btn-primary" id="create_submitting" disabled>
                  <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                  Uploading in progress...
                </button>
              </div>
            </form>
          {% else %} 
            <form action="/{{form.attributes['path']}}" method="{{form.attributes['method']}}">
              <div class="modal-header">
                {% if form.attributes['type'] %} 
                  <h5 class="modal-title" id="exampleModalLabel">{{form.attributes['title_prefix']}} <span>{{form.attributes['type']}}</span></h5>
                {% else %}
                    <h5 class="modal-title" id="exampleModalLabel">{{form.attributes['title_prefix']}} <span>{{item.name}}</span></h5> 
                {% endif %}
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                {% if form.attributes['text'] %}
                <div>
                  {{form.attributes['text']}}
                </div>
                {% endif %}
                {% for control in form.items %}
                  {% if not (control.instance.type and control.instance.type.name == 'ButtonCtrl') %}
                    {% with item=item, control=control, form=form %}
                      {% include "control.html" %}
                    {% endwith %}
                  {% endif %}
                {% endfor %}
                {% if view %}
                  <input type="hidden" id="control_active_view" name="active_view" value="{{view.name | lower}}">
                {% endif %}
              </div>
              <div class="modal-footer">
                {% for control in form.items %}
                  {% if control.instance.type and control.instance.type.name == 'ButtonCtrl' %}
                    {% with item=item, control=control, form=form %}
                      {% include "control.html" %}
                    {% endwith %}
                  {% endif %}
                {% endfor %}
              </div>
            </form>
          {% endif %}
        </div>
      </div>
    </div>
    {% endfor %}
  {% endif %}
</div>
</body>
</html>