{% extends "base.html" %}

{% block title %}Configuration ENT77 - GMAO{% endblock %}

{% block content %}
<div class="container-fluid py-4">
  <div class="row mb-4">
    <div class="col-12">
      <h4><i class="bi bi-broadcast-pin me-2"></i>Configuration ENT77</h4>
      <p class="text-muted">Surveillance automatique des messages ENT77 et création d'interventions</p>
    </div>
  </div>

  <div class="row">
    <!-- Colonne gauche : Configuration -->
    <div class="col-lg-8">
      <div class="card shadow-sm mb-4">
        <div class="card-header bg-primary text-white">
          <i class="bi bi-gear me-2"></i>Paramètres de surveillance
        </div>
        <div class="card-body">
          <form method="POST" id="entConfigForm">
            {{ form.hidden_tag() }}

            <div class="row mb-3">
              <div class="col-md-4">
                {{ form.check_interval_minutes.label(class="form-label") }}
                {{ form.check_interval_minutes(class="form-control", min=1, max=1440) }}
                <div class="form-text">Vérifier les messages toutes les N minutes</div>
              </div>
              <div class="col-md-4">
                {{ form.work_start_hour.label(class="form-label") }}
                {{ form.work_start_hour(class="form-control", min=0, max=23) }}
              </div>
              <div class="col-md-4">
                {{ form.work_end_hour.label(class="form-label") }}
                {{ form.work_end_hour(class="form-control", min=1, max=24) }}
              </div>
            </div>

            <!-- Jours ouvrés -->
            <div class="mb-3">
              <label class="form-label">Jours ouvrés</label>
              <div class="d-flex gap-3">
                {% for day_num in WORKDAYS %}
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" name="work_days" value="{{ day_num }}"
                         id="day_{{ day_num }}"
                         {% if day_num|string in (config.work_days or '') %}checked{% endif %}>
                  <label class="form-check-label" for="day_{{ day_num }}">
                    {% if day_num == 1 %}Lundi{% elif day_num == 2 %}Mardi{% elif day_num == 3 %}Mercredi{% elif day_num == 4 %}Jeudi{% elif day_num == 5 %}Vendredi{% elif day_num == 6 %}Samedi{% elif day_num == 7 %}Dimanche{% endif %}
                  </label>
                </div>
                {% endfor %}
              </div>
            </div>

            <div class="mb-3">
              {{ form.default_equipment_id.label(class="form-label") }}
              {{ form.default_equipment_id(class="form-select") }}
              <div class="form-text">Équipement cible pour les interventions créées automatiquement</div>
            </div>

            <div class="row mb-3">
              <div class="col-md-6">
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" name="auto_create_intervention" id="auto_create_intervention"
                         {% if config.auto_create_intervention %}checked{% endif %}>
                  <label class="form-check-label" for="auto_create_intervention">Création automatique d'interventions</label>
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" name="is_enabled" id="is_enabled"
                         {% if config.is_enabled %}checked{% endif %}>
                  <label class="form-check-label" for="is_enabled">Surveillance activée</label>
                </div>
              </div>
            </div>

            <!-- Mode Debug (optionnel) -->
            {% if current_user.is_admin() %}
            <div class="mb-3 p-3 bg-warning-subtle rounded">
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" name="debug_mode" id="debug_mode" value="1"
                       {% if config.debug_mode %}checked{% endif %}>
                <label class="form-check-label fw-medium" for="debug_mode">
                  <i class="bi bi-bug me-1"></i>Mode Debug
                </label>
              </div>
              <div class="form-text text-muted">Active le mode debug pour les tests Outlook/ENT (servira plus tard)</div>
            </div>
            {% endif %}

            <button type="submit" class="btn btn-primary" id="saveButton">
              <i class="bi bi-check-lg me-1"></i>Enregistrer
            </button>
          </form>
        </div>
      </div>
    </div>

    <!-- Colonne droite : Identifiants + Statut -->
    <div class="col-lg-4">
      <div class="card shadow-sm mb-4">
        <div class="card-header bg-dark text-white">
          <i class="bi bi-key me-2"></i>Identifiants ENT77
        </div>
        <div class="card-body">
          {% if credential %}
          <p class="mb-2">
            <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Configuré</span>
          </p>
          <p class="text-muted small mb-1">
            <i class="bi bi-person me-1"></i>Utilisateur : <code>{{ credential.ent_username_encrypted|decrypt_value_safe|default('•••') }}</code>
          </p>
          <p class="text-muted small mb-1">
            <i class="bi bi-clock me-1"></i>Dernière vérification :
            {% if credential.last_check %}
              {{ credential.last_check|datetime_fmt }}
            {% else %}
              <span class="text-warning">Jamais</span>
            {% endif %}
          </p>
          <p class="text-muted small mb-3">
            <i class="bi bi-shield-lock me-1"></i>Stockage : <span class="badge bg-info">Chiffré Fernet (AES-128)</span>
          </p>
          <a href="{{ url_for('ent.credentials') }}" class="btn btn-outline-dark btn-sm w-100">
            <i class="bi bi-pencil me-1"></i>Modifier les identifiants
          </a>
          {% else %}
          <p class="text-warning mb-3">
            <i class="bi bi-exclamation-triangle me-1"></i>Aucun identifiant configuré
          </p>
          <a href="{{ url_for('ent.credentials') }}" class="btn btn-dark btn-sm w-100">
            <i class="bi bi-key me-1"></i>Configurer les identifiants
          </a>
          {% endif %}
        </div>
      </div>

      <div class="card shadow-sm">
        <div class="card-header bg-secondary text-white">
          <i class="bi bi-info-circle me-2"></i>Statut
        </div>
        <div class="card-body">
          {% if config.is_enabled %}
          <span class="badge bg-success fs-6"><i class="bi bi-broadcast me-1"></i>Surveillance active</span>
          {% else %}
          <span class="badge bg-secondary fs-6"><i class="bi bi-broadcast-pin me-1"></i>Surveillance désactivée</span>
          {% endif %}
          <hr>
          <p class="small text-muted mb-1">Les identifiants sont chiffrés en base de données (Fernet AES-128-CBC + HMAC).</p>
          <p class="small text-muted mb-0">La clé est dérivée de la SECRET_KEY Flask via PBKDF2 (480 000 itérations).</p>
        </div>
      </div>
    </div>
  </div>
</div>

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
  const form = document.getElementById('entConfigForm');
  
  if (form) {
    // Surcharge du comportement de soumission pour le débogage
    form.addEventListener('submit', function(e) {
      console.log('DEBUG: Formulaire soumis');
      
      // Vérifier si le formulaire est valide
      if (!form.checkValidity()) {
        console.log('DEBUG: Formulaire invalide');
        form.reportValidity();
        e.preventDefault();
        return;
      }
      
      console.log('DEBUG: Formulaire valide, soumission en cours...');
      console.log('DEBUG: Données du formulaire:', new FormData(form));
    });
  }
});
</script>
{% endblock %}
{% endblock %}
