{% extends "app_home/base.html" %}
{% load static %}
{% load i18n %}

{% block navbar_app %}
{% include 'app_home/_sidebar.html' %}
{% endblock %}

{% block title %}
<div style="display: flex; justify-content: space-between; align-items: flex-start;">
	<div>
		<h2>
		  <i class="fa fa-check-square me-2"></i>{% trans 'New notification' %}
		</h2>
		<div class="text-muted">
			{% trans 'Template' %} : {{ message_template|default:'No template' }}
		</div>
	</div>

	<!-- Notification Summary Box (Top Right) -->
	<div id="notifySummaryBox" class="border border-secondary rounded p-2" style="background-color: #eeeeee; min-width: 200px; font-size: 0.9rem;">
		<div style="line-height: 1.4;">
			<div><strong>{% translate 'Recipients' %}:</strong> <span id="summaryPeople">0</span></div>
			<div><strong>{% translate 'Emails' %}:</strong> <span id="summaryEmails">0</span></div>
			<div><strong>{% translate 'SMS' %}:</strong> <span id="summarySMS">0</span></div>
		</div>
		<div id="summaryLoading" style="display: none; margin-top: 0.5rem; text-align: center;">
			<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
			<small>{% translate 'Updating...' %}</small>
		</div>
	</div>
</div>
<hr>
{% endblock %}

{% block content %}

<form action="" method="post" enctype="multipart/form-data"> {% csrf_token %}

<input class="btn btn-outline-danger" type="submit" name="submit_notify" value="{% translate 'Send' %}">

<hr>

<!-- DISPLAYNAME -->
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Title' %}</b></label>
  <div class="form-check col-sm-10">
    <input type="text" class="form-control col-sm-10" name="displayname" value="{{ message_title|default_if_none:''}}">
  </div>
</div>

<!-- Template -->
{% if message_template %}
<input type="hidden" name="template" value="{{ message_template }}">
{% endif %}

<!-- Severity -->
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Severity' %}</b></label>
  <div class="form-check col-sm-10">
    <select class="form-check col-sm-4" name="severity" id="id_severity">
        <!-- <option value="">----------------------</option> -->
        {% for item in message_severity %}
        {% if item.selected %} 
            {% if item.widget %}
                <option value="{{ item.value }}" selected>{{ item.widget|safe }} &nbsp; {{ item.value }}</option>
            {% else %}
                <option value="{{ item.value }}" selected>{{ item.value }}</option>
            {% endif %}
        {% else %}
            {% if item.widget %}
              <option value="{{ item.value }}">{{ item.widget|safe }} &nbsp; {{ item.value }}</option>
            {% else %}
              <option value="{{ item.value }}">{{ item.value }}</option>
            {% endif %}
        {% endif %}
        {% endfor %}
    </select>
  </div>
</div>


<!-- Category -->
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Category' %}</b></label>
  <div class="form-check col-sm-10">
    <select class="form-check col-sm-4" name="category" id="id_category">
        <!-- <option value="">----------------------</option> -->
        {% for item in message_category %}
        {% if item.selected %} 
            {% if item.widget %}
                <option value="{{ item.value }}" selected>{{ item.widget|safe }} &nbsp; {{ item.value }}</option>
            {% else %}
                <option value="{{ item.value }}" selected>{{ item.value }}</option>
            {% endif %}
        {% else %}
            {% if item.widget %}
              <option value="{{ item.value }}">{{ item.widget|safe }} &nbsp; {{ item.value }}</option>
            {% else %}
              <option value="{{ item.value }}">{{ item.value }}</option>
            {% endif %}
        {% endif %}
        {% endfor %}
    </select>
  </div>
</div>

<hr>

<!-- Channel: Public -->
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Show a Public page' %}</b></label>
  <div class="form-check col-sm-10">
  <select class="form-check col-sm-10" name="public_page" id="id_public_page">
      <option value="">---------------------------------</option>
      {% for instance in message_public %}
      {% if instance.selected %}<option value="{{ instance.key }}" selected>
        {{ instance.display|default:instance.key }}
      </option>
      {% else %}<option value="{{ instance.key }}">
        {{ instance.display|default:instance.key }}
      </option>{% endif %}
      {% endfor %}
  </select>
  </div>
</div>


<!-- Channel: Restricted -->
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Restricted' %}</b></label>
  <div class="col-sm-10 form-check">
  <input class="form-check mt-2" type="checkbox" name="is_restricted"
    {% if message_restricted %}checked{% endif %}> 
  </div>
</div>

<!-- Channel: EMAIL -->
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Send Emails' %}</b></label>
  <div class="col-sm-10 form-check">
  <input class="form-check mt-2" type="checkbox" name="has_email"
    {% if message_email %}checked{% endif %}> 
  </div>
</div>


<!-- Channel: SMS -->
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Send SMS' %}</b></label>
  <div class="col-sm-10 form-check">
  <input class="form-check mt-2" type="checkbox" name="has_sms"
    {% if message_sms %}checked{% endif %}> 
  </div>
</div>


<!-- Not before -->
<!-- Not after -->


<!-- NOTIFY_TO -->
 
<!-- Notify: user -->
<hr>
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Notify user(s)' %}</b></label>
  <div class="form-check col-sm-10">
  <select class="form-check col-sm-10" name="notify_user" id="id_notify_user" multiple>
      <option value="">---------------------------------</option>
      {% for instance in message_user %}
      {% if instance.selected %}<option value="{{ instance.key }}" selected>
        {{ instance.display|default:instance.key }}
      </option>
      {% else %}<option value="{{ instance.key }}">
        {{ instance.display|default:instance.key }}
      </option>{% endif %}
      {% endfor %}
  </select>
  </div>
</div>

<!-- Notify: group -->
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Notify group(s)' %}</b></label>
  <div class="form-check col-sm-10">
  <select class="form-check col-sm-10" name="notify_group" id="id_notify_group" multiple>
      <option value="">---------------------------------</option>
      {% for instance in message_group %}
      {% if instance.selected %}<option value="{{ instance.key }}" selected>
        {{ instance.display|default:instance.key }}
      </option>
      {% else %}<option value="{{ instance.key }}">
        {{ instance.display|default:instance.key }}
      </option>{% endif %}
      {% endfor %}
  </select>
  </div>
</div>



<!-- NOTIFY GENERIC site, app, ... -->
{% for fieldname, instances in notify_generic.items %}
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Notify' %} {{ fieldname }}</b></label>
  <div class="form-check col-sm-10">
  <select class="form-check col-sm-10" name="notify_{{fieldname}}" id="id_notify_{{fieldname}}" multiple>
      <option value="">---------------------------------</option>
      {% for instance in instances %}
      {% if instance.selected %}<option value="{{ instance.key }}" selected>
        {{ instance.display|default:instance.key }}
      </option>
      {% else %}<option value="{{ instance.key }}">
        {{ instance.display|default:instance.key }}
      </option>{% endif %}
      {% endfor %}
  </select>
  </div>
</div>
{% endfor %}


<!-- SMS content -->
 <hr>
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'SMS content' %}</b></label>
  <div class="form-check col-sm-10">
    <pre><textarea class="form-control" id="id_sms_content" name="sms_content" rows="2" maxlength="120">{{ message_sms_content|default_if_none:''}}</textarea></pre>
  </div>
</div>

<!-- Content -->
<hr>
<div class="mb-3 row">
  <label class="col-form-label col-sm-2"><b>{% trans 'Email content' %}</b></label>
  <div class="form-check col-sm-10">

  <textarea class="tinymce" cols="80" data-mce-conf="{&quot;theme&quot;: &quot;silver&quot;, &quot;height&quot;: 500, &quot;menubar&quot;: false, &quot;plugins&quot;: &quot;advlist,autolink,lists,link,image,charmap,print,preview,anchor,searchreplace,visualblocks,code,fullscreen,insertdatetime,media,table,paste,code,help,wordcount&quot;, &quot;toolbar&quot;: &quot;undo redo | formatselect | link |bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | code | preview | help&quot;, &quot;relative_urls&quot;: 0, &quot;remove_script_host&quot;: 0, &quot;language&quot;: &quot;fr_FR&quot;, &quot;directionality&quot;: &quot;ltr&quot;, &quot;strict_loading_mode&quot;: 1, &quot;selector&quot;: &quot;#content&quot;}" id="content" maxlength="20000" name="content" rows="20">{{ message_email_content|default_if_none:''}}</textarea>
  </div>
</div>



<!-- SEND button -->
<hr>
<input class="btn btn-outline-danger" type="submit" name="submit_notify" value="{% translate 'Send' %}">




{% endblock %}




{% block script %}<!-- select2 scripts -->

<!-- USER -->
<script type="text/javascript">
  $('#id_notify_user').select2({
    width: '100%',
    ajax: {
      url: "{% url 'app_user:ajax_user' %}",
      dataType: 'json',
      delay: 250,
      cache: true,
      data: function (params) {
        return {
          q: params.term
        };
      }
    },
    placeholder: '{% translate "Select users" %}'
    //minimumInputLength: 1
  });
  </script>
  
<!-- GROUP -->
<script> 
  $(document).ready(function() {
    $('#id_notify_group').select2({
      width: '100%'
  });
});
</script>

<!-- GENERIC -->
{% for fieldname in notify_generic %}
<!-- {{ fieldname }} -->
<script type="text/javascript">
  $('#id_notify_{{fieldname}}').select2({
    width: '100%',
    ajax: {
      url: "{% url 'app_data:ajax_instance' %}",
      dataType: 'json',
      delay: 250,
      cache: true,
      data: function (params) {
        return {
          q: params.term,
          c: '{{fieldname}}'
        };
      }
    },
    placeholder: '{% translate "Select items" %}'
    //minimumInputLength: 1
  });
  </script>
{% endfor %}



<!-- PUBLIC PAGE -->
<script> 
  $(document).ready(function() {
    $('#id_public_page').select2({
      width: '30%'
  });
});
</script>


<!-- CATEGORY -->
<script> 
  $(document).ready(function() {
    $('#id_category').select2({
      width: '30%'
  });
});
</script>

<!-- SEVERITY -->
<script> 
  $(document).ready(function() {
    $('#id_severity').select2({
      width: '30%'
  });
});
</script>



<script>

// Helper function to trigger HTMX POST
function triggerNotifySummaryUpdate() {
  htmx.ajax('POST', "{% url 'app_sirene:notify_summary' %}", {
    target: '#notifySummaryBox',
    swap: 'outerHTML',
    values: {
      'notify_user': Array.from(document.getElementById('id_notify_user').selectedOptions).map(x => x.value),
      'notify_group': Array.from(document.getElementById('id_notify_group').selectedOptions).map(x => x.value),
      {% for fieldname in notify_generic %}
      'notify_{{fieldname}}': Array.from(document.getElementById('id_notify_{{fieldname}}').selectedOptions).map(x => x.value),
      {% endfor %}
      'has_email': document.querySelector('[name="has_email"]').checked,
      'has_sms': document.querySelector('[name="has_sms"]').checked
    }
  });
}

// Trigger update when Select2 changes (notify_user)
$('#id_notify_user').on('change', function() {
  triggerNotifySummaryUpdate();
});

// Trigger update when Select2 changes (notify_group)
$('#id_notify_group').on('change', function() {
  triggerNotifySummaryUpdate();
});

// Trigger update when email checkbox changes
document.querySelector('[name="has_email"]').addEventListener('change', function() {
  triggerNotifySummaryUpdate();
});

// Trigger update when SMS checkbox changes
document.querySelector('[name="has_sms"]').addEventListener('change', function() {
  triggerNotifySummaryUpdate();
});

// Trigger initial update on page load
$(document).ready(function() {
  triggerNotifySummaryUpdate();
});
</script>

<!-- Trigger update when Select2 changes on notify_generics -->
{% for fieldname in notify_generic %}
<script>
$('#id_notify_{{fieldname}}').on('change', function() {
  triggerNotifySummaryUpdate();
});
</script>
{% endfor %}


{% endblock %}