{% extends "base.html" %}
{% block title %}Configuration Yeastar - GMAO{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1><i class="bi bi-telephone-gear"></i> Configuration Yeastar P520</h1>
    </div>
    
    <div class="row">
        <div class="col-md-6">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-key"></i> Identifiants de connexion</h5>
                </div>
                <div class="card-body">
                    {% with messages = get_flashed_messages(with_categories=true) %}
                        {% if messages %}
                            {% for category, message in messages %}
                                <div class="alert alert-{{ category }}" role="alert">
                                    {{ message }}
                                </div>
                            {% endfor %}
                        {% endif %}
                    {% endwith %}
                    
                    <form method="POST" action="{{ url_for('yeastar.config_page') }}">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        
                        <div class="mb-3">
                            <label for="base_url" class="form-label">URL du P520</label>
                            <input type="url" class="form-control" id="base_url" name="base_url" 
                                   value="{{ yeastar_config.base_url if yeastar_config else '' }}"
                                   placeholder="https://telclg.example.com/" required>
                            <div class="form-text">URL complète du PBX Yeastar</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="username" class="form-label">Nom d'utilisateur</label>
                            <input type="text" class="form-control" id="username" name="username" 
                                   value="{{ yeastar_config.username if yeastar_config else '' }}"
                                   placeholder="admin" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="password" class="form-label">Mot de passe</label>
                            <input type="password" class="form-control" id="password" name="password" 
                                   placeholder="{% if yeastar_config %}Laisser vide pour conserver le mot de passe actuel{% else %}Mot de passe{% endif %}"
                                   {% if not yeastar_config or not yeastar_config.password_is_valid %}required{% endif %}>
                            <div class="form-text text-muted">
                                {% if yeastar_config and yeastar_config.password_is_valid %}
                                    Le mot de passe stocké est chiffré. Laissez vide pour le conserver.
                                {% elif yeastar_config %}
                                    La clé de chiffrement a changé : saisissez à nouveau le mot de passe.
                                {% else %}
                                    Le mot de passe sera chiffré avant d'être stocké.
                                {% endif %}
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save"></i> Sauvegarder
                            </button>
                            <button type="button" class="btn btn-outline-secondary" id="test-btn">
                                <i class="bi bi-plug"></i> Tester la connexion
                            </button>
                            <a href="{{ url_for('yeastar.index') }}" class="btn btn-secondary">
                                <i class="bi bi-arrow-left"></i> Retour
                            </a>
                        </div>
                    </form>
                    
                    <div id="test-result" class="mt-3" style="display:none;">
                        <!-- Résultat du test -->
                    </div>
                    
                    {% if yeastar_config %}
                    <div class="mt-4 text-muted">
                        <small>Dernière modification: {{ yeastar_config.updated_at|datetime_fmt if yeastar_config.updated_at else 'N/A' }}</small>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-shield-check"></i> Sécurité</h5>
                </div>
                <div class="card-body">
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i> Sécurité des données
                    </div>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">
                            <i class="bi bi-lock text-success"></i>
                            Les identifiants sont chiffrés avec Fernet (AES-128)
                        </li>
                        <li class="list-group-item">
                            <i class="bi bi-database text-success"></i>
                            Stockage en base de données (pas de fichier .env)
                        </li>
                        <li class="list-group-item">
                            <i class="bi bi-cloud-check text-success"></i>
                            Configuration portable entre environnements
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('test-btn').addEventListener('click', function() {
    const btn = this;
    const resultDiv = document.getElementById('test-result');
    
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Test en cours...';
    resultDiv.style.display = 'block';
    resultDiv.innerHTML = '<div class="alert alert-secondary">Connexion en cours...</div>';
    
    fetch('{{ url_for("yeastar.test_connection") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            resultDiv.innerHTML = `
                <div class="alert alert-success">
                    <i class="bi bi-check-circle"></i> Connexion réussie !<br>
                    <strong>${data.extension_count}</strong> extensions trouvées<br>
                    PBX: ${data.pbx_type} (v${data.version})
                </div>
            `;
        } else {
            resultDiv.innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle"></i> Échec de connexion<br>
                    ${data.error}
                </div>
            `;
        }
    })
    .catch(error => {
        resultDiv.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle"></i> Erreur<br>
                ${error}
            </div>
        `;
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-plug"></i> Tester la connexion';
    });
});
</script>
{% endblock %}
