{% extends 'base.html' %}
{% load static %}

{% block title %}Éléments d'ouvrages - Contrôle Technique{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="d-flex flex-wrap" id="icons-container">
               
                
    <a href="{% url 'controle:param_listepv'%}">
        <div class="card icon-card cursor-pointer text-center mb-6 mx-3 card-pv">
            <div class="card-body">
                <i class="icon-base bx bxl-figma mb-2"></i>
                <p class="icon-name text-capitalize text-truncate mb-0">Procès-Verbaux</p>
            </div>
        </div>
    </a>

    <a href="{% url 'controle:liste_ouvrages'%}">
        <div class="card icon-card cursor-pointer text-center mb-6 mx-3 card-ouvrages">
            <div class="card-body">
                <i class="icon-base bx bxl-redbubble mb-2"></i>
                <p class="icon-name text-capitalize text-truncate mb-0">Ouvrages</p>
            </div>
        </div>
    </a>

    <a href="{% url 'controle:liste_elements' %}">
        <div class="card icon-card cursor-pointer text-center mb-6 mx-3 card-elements">
            <div class="card-body">
                <i class="icon-base bx bxl-patreon mb-2"></i>
                <p class="icon-name text-capitalize text-truncate mb-0">Eléments d'Ouvrages</p>
            </div>
        </div>
    </a>
    <a href="{% url 'controle:liste_points_controle' %}">
        <div class="card icon-card cursor-pointer text-center mb-6 mx-3 card-elements">
            <div class="card-body">
                <i class="icon-base bx bxl-audible mb-2"></i>
                <p class="icon-name text-capitalize text-truncate mb-0">Points de contrôle </p>
            </div>
        </div>
    </a>           
    </div>
</div>

<!-- Barre de navigation secondaire -->
<nav class="layout-navbar container-xxl navbar-detached navbar navbar-expand-xl align-items-center bg-navbar-theme" id="layout-navbar">
    <div class="layout-menu-toggle navbar-nav align-items-xl-center me-4 me-xl-0 d-xl-none">
        <a class="nav-item nav-link px-0 me-xl-6" href="javascript:void(0)">
            <i class="icon-base bx bx-menu icon-md"></i>
        </a>
    </div>

    <div class="navbar-nav-right d-flex align-items-center justify-content-end" id="navbar-collapse">
        <!-- Titre de la section -->
        <div class="navbar-nav align-items-center me-auto">
            <div class="nav-item d-flex align-items-center">
                <span class="w-px-22 h-px-22"><i class="icon-base bx bx-layer icon-md"></i></span>
                <h4>Paramétrages : Liste des éléments d'ouvrages</h4>
            </div>
        </div>

        <!-- Boutons d'action -->
        <ul class="navbar-nav flex-row align-items-center ms-md-auto">
            <button type="button" class="btn btn-success btn-sm me-2" data-bs-toggle="modal" data-bs-target="#ajouterElementModal">
                <i class="fa fa-plus"></i> Ajouter
            </button>
            <li class="nav-item lh-1 me-4">
                <span>...</span>
            </li>
        </ul>
    </div>
</nav>

<!-- Contenu principal -->
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- Messages flash -->
    {% if messages %}
    <div class="row">
        <div class="col-12">
            {% for message in messages %}
            <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Fermer"></button>
            </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Filtres -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-4">
                            <label for="ouvrage" class="form-label">Filtrer par ouvrage</label>
                            <select name="ouvrage" id="ouvrage" class="form-select">
                                <option value="">Tous les ouvrages</option>
                                {% for ouvrage in ouvrages %}
                                <option value="{{ ouvrage.id }}" {% if request.GET.ouvrage == ouvrage.id|stringformat:"s" %}selected{% endif %}>
                                    {{ ouvrage.code }} - {{ ouvrage.nom }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <div class="col-md-4 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="fa fa-filter me-1"></i>Filtrer
                            </button>
                            <a href="{% url 'controle:liste_elements' %}" class="btn btn-secondary">
                                <i class="fa fa-undo me-1"></i>Réinitialiser
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Liste des éléments -->
    <div class="row">
        <div class="col-xxl-12 mb-6 order-0">
            <div class="card">
                <h5 class="card-header">Liste des éléments d'ouvrages</h5>
                <div class="table-responsive text-nowrap">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Ouvrage</th>
                                <th>Code élément</th>
                                <th>Nom</th>
                                <th>Description</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody class="table-border-bottom-0">
                            {% for element in elements %}
                            <tr>
                                <td>
                                    <span class="badge bg-info">{{ element.ouvrage.code }}</span>
                                    <small class="text-muted d-block">{{ element.ouvrage.nom }}</small>
                                </td>
                                <td>
                                    <strong>{{ element.code }}</strong>
                                </td>
                                <td>{{ element.nom }}</td>
                                <td>{{ element.description|default:"-"|truncatechars:50 }}</td>
                                <td>
                                    <!-- Bouton modifier -->
                                    <button type="button" class="btn btn-icon btn-warning" data-bs-toggle="modal"
                                            data-bs-target="#modifierElementModal{{ element.id }}">
                                        <span class="icon-base bx bx-edit-alt icon-md"></span>
                                    </button>

                                    <!-- Bouton supprimer -->
                                    <button type="button" class="btn btn-icon btn-danger" data-bs-toggle="modal"
                                            data-bs-target="#supprimerElementModal{{ element.id }}">
                                        <span class="icon-base bx bx-trash-alt icon-md"></span>
                                    </button>
                                </td>
                            </tr>

                            <!-- Modal de modification -->
                            <div class="modal fade" id="modifierElementModal{{ element.id }}" tabindex="-1"
                                 aria-labelledby="modifierElementModalLabel{{ element.id }}" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header bg-warning text-white">
                                            <h5 class="modal-title" id="modifierElementModalLabel{{ element.id }}">
                                                <i class="fa fa-edit me-2"></i>Modifier l'élément
                                            </h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
                                        </div>
                                        <form method="POST" action="{% url 'controle:modifier_element' element.id %}">
                                            {% csrf_token %}
                                            <div class="modal-body">
                                                <div class="mb-3">
                                                    <label for="ouvrage{{ element.id }}" class="form-label">Ouvrage <span class="text-danger">*</span></label>
                                                    <select class="form-select" id="ouvrage{{ element.id }}" name="ouvrage_id" required>
                                                        <option value="">Sélectionnez un ouvrage</option>
                                                        {% for ouvrage in ouvrages %}
                                                        <option value="{{ ouvrage.id }}" {% if element.ouvrage.id == ouvrage.id %}selected{% endif %}>
                                                            {{ ouvrage.code }} - {{ ouvrage.nom }}
                                                        </option>
                                                        {% endfor %}
                                                    </select>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="code{{ element.id }}" class="form-label">Code <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="code{{ element.id }}"
                                                           name="code" value="{{ element.code }}" required>
                                                    <small class="text-muted">Code unique de l'élément</small>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="nom{{ element.id }}" class="form-label">Nom <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="nom{{ element.id }}"
                                                           name="nom" value="{{ element.nom }}" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="description{{ element.id }}" class="form-label">Description</label>
                                                    <textarea class="form-control" id="description{{ element.id }}"
                                                              name="description" rows="3">{{ element.description|default:'' }}</textarea>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                                    <i class="fa fa-times me-1"></i>Annuler
                                                </button>
                                                <button type="submit" class="btn btn-warning">
                                                    <i class="fa fa-save me-1"></i>Modifier
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>

                            <!-- Modal de confirmation de suppression -->
                            <div class="modal fade" id="supprimerElementModal{{ element.id }}" tabindex="-1"
                                aria-labelledby="supprimerElementModalLabel{{ element.id }}" aria-hidden="true">
                                <div class="modal-dialog modal-sm">
                                    <div class="modal-content">
                                        <div class="modal-header bg-danger text-white">
                                            <h5 class="modal-title" id="supprimerElementModalLabel{{ element.id }}">
                                                <i class="fa fa-exclamation-triangle me-2"></i>Confirmation
                                            </h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
                                        </div>
                                        <div class="modal-body">
                                            <p>Êtes-vous sûr de vouloir supprimer l'élément :</p>
                                            <p class="fw-bold">{{ element.ouvrage.code }} - {{ element.code }} : {{ element.nom }}</p>
                                            <p class="text-danger"><small>Cette action est irréversible.</small></p>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                                <i class="fa fa-times me-1"></i>Annuler
                                            </button>
                                            <form method="POST" action="{% url 'controle:supprimer_element' element.id %}" style="display: inline;">
                                                {% csrf_token %}
                                                <button type="submit" class="btn btn-danger">
                                                    <i class="fa fa-trash me-1"></i>Supprimer
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% empty %}
                            <tr>
                                <td colspan="5" class="text-center py-4">
                                    <i class="fa fa-folder-open fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">Aucun élément d'ouvrage trouvé</p>
                                    {% if request.GET.ouvrage or request.GET.etat %}
                                    <a href="{% url 'controle:liste_elements' %}" class="btn btn-sm btn-primary">
                                        <i class="fa fa-undo me-1"></i>Réinitialiser les filtres
                                    </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

                <!-- Pied de tableau -->
                <div class="card-footer d-flex justify-content-between align-items-center">
                    <div class="text-muted">
                        <small>Total : {{ elements|length }} élément(s)</small>
                    </div>
                    {% if elements.has_other_pages %}
                    <nav aria-label="Navigation des pages">
                        <ul class="pagination pagination-sm mb-0">
                            {% if elements.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ elements.previous_page_number }}{% if request.GET.ouvrage %}&ouvrage={{ request.GET.ouvrage }}{% endif %}{% if request.GET.etat %}&etat={{ request.GET.etat }}{% endif %}">
                                    <i class="fa fa-chevron-left"></i>
                                </a>
                            </li>
                            {% endif %}

                            {% for i in elements.paginator.page_range %}
                            <li class="page-item {% if elements.number == i %}active{% endif %}">
                                <a class="page-link" href="?page={{ i }}{% if request.GET.ouvrage %}&ouvrage={{ request.GET.ouvrage }}{% endif %}{% if request.GET.etat %}&etat={{ request.GET.etat }}{% endif %}">
                                    {{ i }}
                                </a>
                            </li>
                            {% endfor %}

                            {% if elements.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ elements.next_page_number }}{% if request.GET.ouvrage %}&ouvrage={{ request.GET.ouvrage }}{% endif %}{% if request.GET.etat %}&etat={{ request.GET.etat }}{% endif %}">
                                    <i class="fa fa-chevron-right"></i>
                                </a>
                            </li>
                            {% endif %}
                        </ul>
                    </nav>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal d'ajout -->
<div class="modal fade" id="ajouterElementModal" tabindex="-1" aria-labelledby="ajouterElementModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title" id="ajouterElementModalLabel">
                    <i class="fa fa-plus-circle me-2"></i>Ajouter un élément d'ouvrage
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
            </div>
            <form method="POST" action="{% url 'controle:ajouter_element' %}">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="ouvrage" class="form-label">Ouvrage <span class="text-danger">*</span></label>
                        <select class="form-select" id="ouvrage" name="ouvrage_id" required>
                            <option value="">Sélectionnez un ouvrage</option>
                            {% for ouvrage in ouvrages %}
                            <option value="{{ ouvrage.id }}">
                                {{ ouvrage.code }} - {{ ouvrage.nom }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="code" class="form-label">Code <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="code" name="code" required
                               placeholder="Exemple : EL-001, FO-001, etc.">
                        <small class="text-muted">Code unique de l'élément</small>
                    </div>
                    <div class="mb-3">
                        <label for="nom" class="form-label">Nom de l'élément <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="nom" name="nom" required
                               placeholder="Exemple : Fondation superficielle, Poteau béton, etc.">
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="3"
                                  placeholder="Description détaillée de l'élément"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fa fa-times me-1"></i>Annuler
                    </button>
                    <button type="submit" class="btn btn-success">
                        <i class="fa fa-save me-1"></i>Enregistrer
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<script>
    // Attendre que le DOM soit chargé
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM chargé - Initialisation');

        // Vérifier la disponibilité de Bootstrap
        if (typeof bootstrap !== 'undefined') {
            console.log('Bootstrap est disponible');

            // Auto-fermeture des alertes après 5 secondes
            setTimeout(function() {
                document.querySelectorAll('.alert').forEach(function(alert) {
                    try {
                        var bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    } catch(e) {
                        console.error('Erreur lors de la fermeture de l\'alerte:', e);
                    }
                });
            }, 5000);

            // Réouverture du modal en cas d'erreur de formulaire
            {% if messages and request.method == 'POST' %}
                var modalElement = document.getElementById('ajouterElementModal');
                if (modalElement) {
                    try {
                        var myModal = new bootstrap.Modal(modalElement);
                        myModal.show();
                    } catch(e) {
                        console.error('Erreur lors de l\'ouverture du modal:', e);
                    }
                }
            {% endif %}
        } else {
            console.warn('Bootstrap n\'est pas chargé correctement');
        }
    });

    // Version jQuery si disponible
    if (typeof $ !== 'undefined') {
        $(document).ready(function() {
            console.log('jQuery est prêt');

            // Gestionnaire d'événements pour les modals
            $('#ajouterElementModal').on('show.bs.modal', function() {
                console.log('Ouverture du modal d\'ajout');
            });

            $('[id^=modifierElementModal]').on('show.bs.modal', function() {
                console.log('Ouverture d\'un modal de modification');
            });

            $('[id^=supprimerElementModal]').on('show.bs.modal', function() {
                console.log('Ouverture d\'un modal de suppression');
            });

            // Initialisation des tooltips Bootstrap si disponibles
            $('[data-bs-toggle="tooltip"]').tooltip();
        });
    }
</script>
{% endblock %}