{% extends "base.html" %}

{% block title %}Éditeur de code - GMAO{% endblock %}

{% block content %}
<div class="container-fluid py-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h4><i class="bi bi-code-slash me-2"></i>Éditeur de code</h4>
    <div class="alert alert-success">
      <i class="bi bi-shield-check me-2"></i>
      <strong>Accès admin uniquement</strong> - Les utilisateurs non-admin ne peuvent pas voir cette page
    </div>
  </div>

  <div class="row">
    <div class="col-md-4">
      <div class="card">
        <div class="card-header">
          <h6 class="mb-0"><i class="bi bi-folder me-2"></i>Fichiers templates</h6>
        </div>
        <div class="card-body p-0">
          <div class="list-group list-group-flush">
            {% for file in files %}
            <a href="#" class="list-group-item list-group-item-action" onclick="loadFile('{{ file }}')">
              <i class="bi bi-file-earmark-text me-2"></i>{{ file }}
            </a>
            {% endfor %}
          </div>
        </div>
      </div>
    </div>
    
    <div class="col-md-8">
      <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
          <h6 class="mb-0"><i class="bi bi-file-earmark-code me-2"></i>Éditeur</h6>
          <div>
            <select id="fileSelector" class="form-select form-select-sm d-inline-block w-auto me-2">
              {% for file in files %}
              <option value="{{ file }}">{{ file }}</option>
              {% endfor %}
            </select>
            <button class="btn btn-primary btn-sm" onclick="saveFile()">
              <i class="bi bi-save me-1"></i>Sauvegarder
            </button>
          </div>
        </div>
        <div class="card-body">
          <textarea id="codeEditor" class="form-control" rows="20" placeholder="Sélectionnez un fichier à éditer..."></textarea>
          <div id="saveStatus" class="mt-2"></div>
        </div>
      </div>
    </div>
  </div>

  <div class="card mt-4">
    <div class="card-header">
      <h6><i class="bi bi-info-circle me-2"></i>Permissions actuelles</h6>
    </div>
    <div class="card-body">
      <div class="row">
        <div class="col-md-6">
          <strong>Utilisateur actuel :</strong> {{ current_user.username }} ({{ current_user.role_label }})
        </div>
        <div class="col-md-6">
          <strong>Permission code:edit :</strong> 
          {% if current_user.is_admin() %}
            <span class="badge bg-success">✅ Accordée</span>
          {% else %}
            <span class="badge bg-danger">❌ Refusée</span>
          {% endif %}
        </div>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block scripts %}
<script>
function loadFile(filePath) {
    document.getElementById('fileSelector').value = filePath;
    fetch(`/ent/admin/load-template?path=${encodeURIComponent(filePath)}`)
        .then(response => response.json())
        .then(data => {
            if (data.content) {
                document.getElementById('codeEditor').value = data.content;
            } else {
                document.getElementById('codeEditor').value = `<!-- Template: ${filePath} -->\n\n<!-- Contenu du template ici -->`;
            }
        })
        .catch(error => {
            document.getElementById('codeEditor').value = `Erreur de chargement: ${error}`;
        });
}

function saveFile() {
    const filePath = document.getElementById('fileSelector').value;
    const content = document.getElementById('codeEditor').value;
    const statusDiv = document.getElementById('saveStatus');
    
    fetch('/ent/admin/save-template', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            path: filePath,
            content: content
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            statusDiv.innerHTML = '<div class="alert alert-success"><i class="bi bi-check-circle me-2"></i>' + data.message + '</div>';
        } else {
            statusDiv.innerHTML = '<div class="alert alert-danger"><i class="bi bi-exclamation-circle me-2"></i>' + data.error + '</div>';
        }
    })
    .catch(error => {
        statusDiv.innerHTML = '<div class="alert alert-danger"><i class="bi bi-exclamation-circle me-2"></i>Erreur: ' + error + '</div>';
    });
}

// Charger le premier fichier par défaut
{% if files %}
window.onload = function() {
    loadFile('{{ files[0] }}');
};
{% endif %}
</script>
{% endblock %}
