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

{% block title %}Modification du PV n°{{ pv.numero_pv }}{% endblock %}

{% block content %}
<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">
        <div class="navbar-nav align-items-center me-auto">
            <div class="nav-item d-flex align-items-center">
                <i class="icon-base bx bx-file icon-md me-2"></i>
                <h4 class="mb-0">
                    Modification du Procès-Verbal
                    {% if pv.numero %}<span class="text-primary">n°{{ pv.numero }}</span>{% endif %}
                </h4>
            </div>
        </div>
        <div class="navbar-nav align-items-center">
            <span class="badge 
                {% if pv.statut == 'brouillon' %}bg-label-warning
                {% elif pv.statut == 'finalise' %}bg-label-success
                {% elif pv.statut == 'archive' %}bg-label-secondary
                {% else %}bg-label-info{% endif %} p-2">
                <i class="icon-base 
                    {% if pv.statut == 'brouillon' %}bx-edit
                    {% elif pv.statut == 'finalise' %}bx-check-circle
                    {% elif pv.statut == 'archive' %}bx-archive
                    {% else %}bx-time{% endif %} me-1"></i>
                {{ pv.get_statut_display|default:"Brouillon" }}
            </span> &nbsp;&nbsp;
            <div>
                <a href="{% url 'controle:detail_pv' pv.pk %}" class="btn btn-outline-secondary">
                    <i class="fa fa-arrow-left"></i> Retour au détail
                </a>
            </div>
        </div>
    </div>
</nav>

<div class="container-xxl flex-grow-1 container-p-y">
    <div class="container-fluid py-4">
   
        <!-- Messages -->
        {% if messages %}
            {% 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="Close"></button>
                </div>
            {% endfor %}
        {% endif %}

        <!-- Formulaire principal -->
        <form method="POST" id="modificationForm" class="needs-validation" novalidate>
            {% csrf_token %}
            
            <!-- Informations générales -->
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-white">
                    <h1 class="h3 mb-0">Informations générales</h1>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.numero.id_for_label }}" class="form-label">Numéro du PV</label>
                            {{ form.numero }}
                            {% if form.numero.errors %}
                                <div class="invalid-feedback d-block">{{ form.numero.errors }}</div>
                            {% endif %}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.type_pv.id_for_label }}" class="form-label">Type de PV</label>
                            {{ form.type_pv }}
                            {% if form.type_pv.errors %}
                                <div class="invalid-feedback d-block">{{ form.type_pv.errors }}</div>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.client.id_for_label }}" class="form-label">Client</label>
                            {{ form.client }}
                            {% if form.client.errors %}
                                <div class="invalid-feedback d-block">{{ form.client.errors }}</div>
                            {% endif %}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.date_visite.id_for_label }}" class="form-label">Date de visite</label>
                            {{ form.date_visite }}
                            {% if form.date_visite.errors %}
                                <div class="invalid-feedback d-block">{{ form.date_visite.errors }}</div>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="{{ form.lieu.id_for_label }}" class="form-label">Lieu de contrôle</label>
                            {{ form.lieu }}
                            {% if form.lieu.errors %}
                                <div class="invalid-feedback d-block">{{ form.lieu.errors }}</div>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="{{ form.objet_controle.id_for_label }}" class="form-label">Objet du contrôle</label>
                            {{ form.objet_controle }}
                            {% if form.objet_controle.errors %}
                                <div class="invalid-feedback d-block">{{ form.objet_controle.errors }}</div>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="{{ form.observations_generales.id_for_label }}" class="form-label">Observations générales</label>
                            {{ form.observations_generales }}
                            {% if form.observations_generales.errors %}
                                <div class="invalid-feedback d-block">{{ form.observations_generales.errors }}</div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <!-- Participants -->
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h1 class="h3 mb-0">Participants</h1>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="addParticipant">
                        <i class="fa fa-plus"></i> Ajouter un participant
                    </button>
                </div>
                <div class="card-body">
                    {{ participant_formset.management_form }}
                    
                    <div class="table-responsive">
                        <table class="table table-hover table-bordered" id="participants-table">
                            <thead class="table-light">
                                <tr>
                                    <th style="width: 30%">Nom</th>
                                    <th style="width: 25%">Fonction</th>
                                    <th style="width: 25%">Organisme</th>
                                    <th style="width: 15%">Signature</th>
                                    <th style="width: 5%">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="participants-container">
                                {% for participant_form in participant_formset %}
                                    <tr class="participant-form" data-form-id="{{ forloop.counter0 }}">
                                        <td>
                                            {{ participant_form.nom }}
                                            {% if participant_form.nom.errors %}
                                                <div class="invalid-feedback d-block">{{ participant_form.nom.errors }}</div>
                                            {% endif %}
                                            {% for hidden in participant_form.hidden_fields %}
                                                {{ hidden }}
                                            {% endfor %}
                                        </td>
                                        <td>
                                            {{ participant_form.fonction }}
                                            {% if participant_form.fonction.errors %}
                                                <div class="invalid-feedback d-block">{{ participant_form.fonction.errors }}</div>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {{ participant_form.organisme }}
                                            {% if participant_form.organisme.errors %}
                                                <div class="invalid-feedback d-block">{{ participant_form.organisme.errors }}</div>
                                            {% endif %}
                                        </td>
                                        <td class="text-center">
                                            {% if participant_form.instance.signature %}
                                                <span class="badge bg-success">Signé</span>
                                            {% else %}
                                                <span class="badge bg-secondary">Non signé</span>
                                            {% endif %}
                                        </td>
                                        <td class="text-center">
                                            <div class="btn-group btn-group-sm" role="group">
                                                <button type="button" class="btn btn-outline-primary edit-participant" data-id="{{ forloop.counter0 }}">
                                                    <i class="fa fa-edit"></i>
                                                </button>
                                                {% if participant_form.DELETE %}
                                                    <button type="button" class="btn btn-outline-danger delete-participant" data-id="{{ forloop.counter0 }}">
                                                        <i class="fa fa-trash"></i>
                                                    </button>
                                                    <div style="display: none;">
                                                        {{ participant_form.DELETE }}
                                                    </div>
                                                {% else %}
                                                    <button type="button" class="btn btn-outline-danger remove-participant" data-id="{{ forloop.counter0 }}">
                                                        <i class="fa fa-trash"></i>
                                                    </button>
                                                {% endif %}
                                            </div>
                                        </td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    
                    {% if not participant_formset.forms %}
                    <div class="text-center py-4">
                        <i class="fa fa-users fa-3x text-muted mb-3"></i>
                        <p class="text-muted">Aucun participant enregistré</p>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- Contrôles effectués -->
            <div class="card shadow-sm mb-4">
                <style>
                    .statut-conforme { color: #0d6efd !important; font-weight: 600; }
                    .statut-non_conforme { color: #198754 !important; font-weight: 600; }
                    .statut-suspendu, .statut-suspendu-uppercase { color: #dc3545 !important; font-weight: 600; }
                    /* For select elements, apply color to the select itself */
                    select.statut-conforme { color: #0d6efd; }
                    select.statut-non_conforme { color: #198754; }
                    select.statut-suspendu { color: #dc3545; }
                </style>
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h1 class="h3 mb-0">Contrôles effectués</h1>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="addControle">
                        <i class="fa fa-plus"></i> Ajouter un contrôle
                    </button>
                </div>
                <div class="card-body">
                 {{ controle_formset.management_form }}
        
                <div class="table-responsive">
                    <table class="table table-hover table-bordered" id="controles-table">
                            <thead class="table-light">
                                <tr>
                                    <th style="width: 12%">Ouvrage</th>
                                    <th style="width: 22%">Point de contrôle</th>
                                    <th style="width: 12%">Résultat</th>
                                    <th style="width: 28%">Observation</th>
                                    <th style="width: 8%">Prise de photo</th>
                                    <th style="width: 5%">Actions</th>
                                </tr>
                            </thead>
                        <tbody id="controles-container">
                            {% for controle_form in controle_formset %}
                                <tr class="controle-form" data-form-id="{{ forloop.counter0 }}">
                                    <td class="controle-ouvrage-cell">
                                        <select class="form-select ouvrage-select" data-target="id_controles-{{ forloop.counter0 }}-point_controle">
                                            <option value="">Sélectionner un ouvrage</option>
                                            {% for ouvrage in ouvrages %}
                                                <option value="{{ ouvrage.id }}"
                                                    {% if controle_form.instance.point_controle and controle_form.instance.point_controle.element.ouvrage_id == ouvrage.id %}selected{% endif %}>
                                                    {{ ouvrage.nom }}
                                                </option>
                                            {% endfor %}
                                        </select>
                                    </td>
                                    <td class="controle-point-cell">
                                        {{ controle_form.point_controle }}
                                        {% if controle_form.point_controle.errors %}
                                            <div class="invalid-feedback d-block">{{ controle_form.point_controle.errors }}</div>
                                        {% endif %}
                                        {% for hidden in controle_form.hidden_fields %}
                                            {{ hidden }}
                                        {% endfor %}
                                    </td>
                                    <td class="controle-statut-cell">
                                        {{ controle_form.statut }}
                                        {% if controle_form.statut.errors %}
                                            <div class="invalid-feedback d-block">{{ controle_form.statut.errors }}</div>
                                        {% endif %}
                                    </td>
                                    <td class="controle-observation-cell">
                                        {{ controle_form.observation }}
                                        {% if controle_form.observation.errors %}
                                            <div class="invalid-feedback d-block">{{ controle_form.observation.errors }}</div>
                                        {% endif %}
                                    </td>
                                    <td class="text-center controle-photo-cell">
                                        <button type="button" class="btn btn-outline-secondary btn-sm photo-button" title="Prendre une photo">
                                            <i class="bx bx-camera"></i>
                                        </button>
                                        <input type="file" accept="image/*" capture="environment" class="d-none photo-input" />
                                        <div class="photo-thumb mt-1"></div>
                                    </td>
                                    <td class="text-center">
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-outline-primary edit-controle" data-id="{{ forloop.counter0 }}">
                                                <i class="fa fa-edit"></i>
                                            </button>
                                            {% if controle_form.DELETE %}
                                                <button type="button" class="btn btn-outline-danger delete-controle" data-id="{{ forloop.counter0 }}">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                                <div style="display: none;">
                                                    {{ controle_form.DELETE }}
                                                </div>
                                            {% else %}
                                                <button type="button" class="btn btn-outline-danger remove-controle" data-id="{{ forloop.counter0 }}">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
        
                {% if not controle_formset.forms %}
                <div class="text-center py-4">
                    <i class="fa fa-clipboard-list fa-3x text-muted mb-3"></i>
                    <p class="text-muted">Aucun contrôle enregistré</p>
                </div>
                {% endif %}
            </div>
        </div>

<!-- Modal pour l'édition des contrôles -->
<div class="modal fade" id="controleModal" tabindex="-1" aria-labelledby="controleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="controleModalLabel">Éditer le contrôle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Ouvrage</label>
                    <select class="form-select" id="edit_ouvrage">
                        <option value="">Sélectionner un ouvrage</option>
                        {% for ouvrage in ouvrages %}
                            <option value="{{ ouvrage.id }}">{{ ouvrage.nom }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Point de contrôle</label>
                    <select class="form-select" id="edit_point_controle">
                        <option value="">Sélectionner un point de contrôle</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Résultat</label>
                    <select class="form-select" id="edit_statut">
                        <option value="conforme">Conforme</option>
                        <option value="non_conforme">Non conforme</option>
                        <option value="non_applicable">Non applicable</option>
                        <option value="en_cours">En cours</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Observation</label>
                    <textarea class="form-control" id="edit_observation" rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                <button type="button" class="btn btn-primary" id="saveControleEdit">Enregistrer</button>
            </div>
        </div>
    </div>
</div>

<!-- Template pour les nouvelles lignes de contrôle -->
<div id="empty-controle-row" style="display: none;">
        <tr class="controle-form" data-form-id="__prefix__">
        <td class="controle-ouvrage-cell">
            <select class="form-select ouvrage-select" data-target="id_controles-__prefix__-point_controle">
                <option value="">Sélectionner un ouvrage</option>
                {% for ouvrage in ouvrages %}
                    <option value="{{ ouvrage.id }}">{{ ouvrage.nom }}</option>
                {% endfor %}
            </select>
        </td>
        <td class="controle-point-cell">
            <select name="controles-__prefix__-point_controle" class="form-select" id="id_controles-__prefix__-point_controle">
                <option value="">Sélectionner un point de contrôle</option>
            </select>
        </td>
        <td class="controle-statut-cell">
            <select name="controles-__prefix__-statut" class="form-select">
                <option value="conforme">Conforme</option>
                <option value="non_conforme">Non conforme</option>
                <option value="non_applicable">Non applicable</option>
                <option value="en_cours">En cours</option>
            </select>
        </td>
        <td class="controle-observation-cell">
            <textarea name="controles-__prefix__-observation" class="form-control" rows="2"></textarea>
        </td>
        <td class="text-center controle-photo-cell">
            <button type="button" class="btn btn-outline-secondary btn-sm photo-button" title="Prendre une photo">
                <i class="bx bx-camera"></i>
            </button>
            <input type="file" accept="image/*" capture="environment" class="d-none photo-input" />
            <div class="photo-thumb mt-1"></div>
        </td>
        <td class="text-center">
            <div class="btn-group btn-group-sm" role="group">
                <button type="button" class="btn btn-outline-primary edit-controle" data-id="__prefix__">
                    <i class="fa fa-edit"></i>
                </button>
                <button type="button" class="btn btn-outline-danger remove-controle" data-id="__prefix__">
                    <i class="fa fa-trash"></i>
                </button>
            </div>
        </td>
    </tr>
</div>

<script>
// Ajouter dans le bloc extra_js existant
document.addEventListener('DOMContentLoaded', function() {
    // ... (code existant pour les participants)

    // File queue for photos taken before the controle has an ID
    const queuedPhotos = new Map(); // key: form index, value: File

    // Helper pour récupérer le token CSRF depuis le cookie
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // Mettre à jour la classe de couleur en fonction de la valeur du statut
    function updateStatutClass(statutSelect) {
        if (!statutSelect) return;
        const val = String((statutSelect.value || '').toLowerCase());
        statutSelect.classList.remove('statut-conforme','statut-non_conforme','statut-suspendu');
        if (val === 'conforme') {
            statutSelect.classList.add('statut-conforme');
        } else if (val === 'non_conforme' || val === 'non conforme' || val === 'nonconforme') {
            statutSelect.classList.add('statut-non_conforme');
        } else if (val === 'suspendu' || val === 'suspendu') {
            statutSelect.classList.add('statut-suspendu');
        }
    }
    
    // ==================== GESTION DES CONTRÔLES ====================
    let currentEditControleRow = null;
    
    // Mettre à jour les indices des formulaires contrôles
    function updateControleIndices() {
        const rows = document.querySelectorAll('#controles-container tr.controle-form:not([style*="display: none"])');
        const totalForms = document.getElementById('id_controles-TOTAL_FORMS');
        
        rows.forEach((row, index) => {
            row.setAttribute('data-form-id', index);
            
            const inputs = row.querySelectorAll('input, select, textarea');
            inputs.forEach(input => {
                if (input.name) {
                    input.name = input.name.replace(/controles-\d+-/, `controles-${index}-`);
                }
                if (input.id) {
                    input.id = input.id.replace(/id_controles-\d+/, `id_controles-${index}`);
                }
            });
            
            const ouvrageSelect = row.querySelector('.ouvrage-select');
            if (ouvrageSelect) {
                ouvrageSelect.setAttribute('data-target', `id_controles-${index}-point_controle`);
            }
            
            const editBtn = row.querySelector('.edit-controle');
            if (editBtn) editBtn.setAttribute('data-id', index);
            
            const deleteBtn = row.querySelector('.delete-controle, .remove-controle');
            if (deleteBtn) deleteBtn.setAttribute('data-id', index);
        });
        
        if (totalForms) {
            totalForms.value = rows.length;
        }
    }
    
    // Fonction pour filtrer les points de contrôle
    function filterControleElements(ouvrageSelect, elementSelect) {
        const ouvrageId = ouvrageSelect.value;
        elementSelect.disabled = true;
        
        if (ouvrageId) {
            fetch(`/api/elements-par-ouvrage/${ouvrageId}/`)
                .then(response => response.json())
                .then(data => {
                    elementSelect.innerHTML = '<option value="">Sélectionner un point de contrôle</option>';
                    data.elements.forEach(element => {
                        const option = document.createElement('option');
                        option.value = element.id;
                        option.textContent = element.nom;
                        elementSelect.appendChild(option);
                    });
                    elementSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Erreur:', error);
                    elementSelect.disabled = false;
                });
        } else {
            elementSelect.innerHTML = '<option value="">Sélectionner un point de contrôle</option>';
            elementSelect.disabled = false;
        }
    }
    
    // Ajouter un contrôle
    function addControle() {
        const container = document.getElementById('controles-container');
        const template = document.getElementById('empty-controle-row');
        const newRow = template.cloneNode(true);
        newRow.style.display = '';
        newRow.id = '';
        
        const formCount = parseInt(document.getElementById('id_controles-TOTAL_FORMS').value);
        const newHtml = newRow.innerHTML.replace(/__prefix__/g, formCount);
        newRow.innerHTML = newHtml;
        
        container.appendChild(newRow);
        updateControleIndices();
        attachControleRowEvents(newRow);
        
        // Initialiser l'écouteur pour l'ouvrage
        const ouvrageSelect = newRow.querySelector('.ouvrage-select');
        const targetId = `id_controles-${formCount}-point_controle`;
        ouvrageSelect.setAttribute('data-target', targetId);
        const elementSelect = newRow.querySelector(`#${targetId}`);
        
        ouvrageSelect.addEventListener('change', function() {
            filterControleElements(this, elementSelect);
        });
    }
    
    // Supprimer un contrôle
    function deleteControle(row) {
        const deleteCheckbox = row.querySelector('input[type="checkbox"][name$="-DELETE"]');
        if (deleteCheckbox) {
            deleteCheckbox.checked = true;
            row.style.display = 'none';
        } else {
            row.remove();
            updateControleIndices();
        }
    }
    
    // Éditer un contrôle
    function editControle(row) {
        currentEditControleRow = row;
        
        // Récupérer les valeurs
        const ouvrageSelect = row.querySelector('.ouvrage-select');
        const pointSelect = row.querySelector('select[name$="-point_controle"]');
        const statutSelect = row.querySelector('select[name$="-statut"]');
        const observationTextarea = row.querySelector('textarea[name$="-observation"]');
        
        // Remplir le modal
        document.getElementById('edit_ouvrage').value = ouvrageSelect ? ouvrageSelect.value : '';
        document.getElementById('edit_statut').value = statutSelect ? statutSelect.value : 'conforme';
        document.getElementById('edit_observation').value = observationTextarea ? observationTextarea.value : '';
        
        // Charger les points de contrôle pour l'ouvrage sélectionné
        if (ouvrageSelect && ouvrageSelect.value) {
            fetch(`/api/elements-par-ouvrage/${ouvrageSelect.value}/`)
                .then(response => response.json())
                .then(data => {
                    const pointSelectModal = document.getElementById('edit_point_controle');
                    pointSelectModal.innerHTML = '<option value="">Sélectionner un point de contrôle</option>';
                    data.elements.forEach(element => {
                        const option = document.createElement('option');
                        option.value = element.id;
                        option.textContent = element.nom;
                        if (pointSelect && pointSelect.value == element.id) {
                            option.selected = true;
                        }
                        pointSelectModal.appendChild(option);
                    });
                });
        }
        
        const modal = new bootstrap.Modal(document.getElementById('controleModal'));
        modal.show();
    }
    
    // Sauvegarder les modifications du contrôle
    function saveControleEdit() {
        if (currentEditControleRow) {
            const ouvrageSelect = currentEditControleRow.querySelector('.ouvrage-select');
            const pointSelect = currentEditControleRow.querySelector('select[name$="-point_controle"]');
            const statutSelect = currentEditControleRow.querySelector('select[name$="-statut"]');
            const observationTextarea = currentEditControleRow.querySelector('textarea[name$="-observation"]');
            
            const newOuvrageId = document.getElementById('edit_ouvrage').value;
            const newPointId = document.getElementById('edit_point_controle').value;
            const newStatut = document.getElementById('edit_statut').value;
            const newObservation = document.getElementById('edit_observation').value;
            
            // Mettre à jour l'ouvrage
            if (ouvrageSelect) {
                ouvrageSelect.value = newOuvrageId;
                // Déclencher l'événement change pour charger les points
                const changeEvent = new Event('change');
                ouvrageSelect.dispatchEvent(changeEvent);
                
                // Attendre un peu pour que les points soient chargés
                setTimeout(() => {
                    if (pointSelect) {
                        pointSelect.value = newPointId;
                    }
                }, 300);
            }
            
            if (statutSelect) statutSelect.value = newStatut;
            if (observationTextarea) observationTextarea.value = newObservation;
            
            const modal = bootstrap.Modal.getInstance(document.getElementById('controleModal'));
            if (modal) modal.hide();
            currentEditControleRow = null;
        }
    }
    
    // Attacher les événements à une ligne contrôle
    function attachControleRowEvents(row) {
        const editBtn = row.querySelector('.edit-controle');
        const deleteBtn = row.querySelector('.delete-controle, .remove-controle');
        
        if (editBtn) {
            editBtn.addEventListener('click', (e) => {
                e.preventDefault();
                editControle(row);
            });
        }
        
        if (deleteBtn) {
            deleteBtn.addEventListener('click', (e) => {
                e.preventDefault();
                deleteControle(row);
            });
        }
        
        // Initialiser l'écouteur pour l'ouvrage
        const ouvrageSelect = row.querySelector('.ouvrage-select');
        if (ouvrageSelect) {
            const targetId = ouvrageSelect.getAttribute('data-target');
            const elementSelect = document.getElementById(targetId);
            if (elementSelect) {
                ouvrageSelect.addEventListener('change', function() {
                    filterControleElements(this, elementSelect);
                });
                
                // Si l'ouvrage a déjà une valeur, charger les points
                if (ouvrageSelect.value) {
                    filterControleElements(ouvrageSelect, elementSelect);
                }
            }
        }



        // Gestion photo: bouton + champ fichier
        const photoBtn = row.querySelector('.photo-button');
        const photoInput = row.querySelector('.photo-input');
        const photoThumb = row.querySelector('.photo-thumb');

        // Appliquer la couleur initiale au select statut de la ligne
        const statutSelectRow = row.querySelector('select[name$="-statut"]');
        if (statutSelectRow) {
            updateStatutClass(statutSelectRow);
            statutSelectRow.addEventListener('change', () => updateStatutClass(statutSelectRow));
        }

        if (photoBtn && photoInput) {
            photoBtn.addEventListener('click', (e) => {
                e.preventDefault();
                photoInput.click();
            });

            photoInput.addEventListener('change', (e) => {
                const file = e.target.files && e.target.files[0];
                if (!file) return;

                // Essayer de récupérer l'ID du contrôle (champ hidden id du formset)
                const idInput = row.querySelector('input[name$="-id"]');
                const controleId = idInput ? idInput.value : null;

                // If controle exists on server (has id), upload immediately
                if (controleId) {
                    const formData = new FormData();
                    formData.append('image', file);

                    fetch(`/controle/${controleId}/photo/`, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-CSRFToken': getCookie('csrftoken')
                        }
                    }).then(r => r.json())
                    .then(data => {
                        if (data && data.success) {
                            if (photoThumb) {
                                photoThumb.innerHTML = `<img src="${data.url}" style="height:40px;border-radius:4px;" />`;
                            }
                        } else {
                            console.error('Upload failed', data);
                            alert('Erreur lors de l\u2019envoi de la photo.');
                        }
                    }).catch(err => {
                        console.error(err);
                        alert('Erreur lors de l\u2019envoi de la photo.');
                    });

                    return;
                }

                // Sinon, mettre en file locale en attendant la sauvegarde du PV
                const formIndex = row.getAttribute('data-form-id');
                if (formIndex === null) {
                    alert('Impossible de déterminer la ligne de contrôle pour la photo.');
                    return;
                }

                queuedPhotos.set(String(formIndex), file);
                // afficher miniatures locales
                if (photoThumb) {
                    const url = URL.createObjectURL(file);
                    photoThumb.innerHTML = `<img src="${url}" style="height:40px;border-radius:4px;" />`;
                }
            });
        }
        }
    }
    
    // Initialisation des contrôles existants
    document.querySelectorAll('#controles-container tr.controle-form').forEach(row => {
        attachControleRowEvents(row);
    });

    // Appliquer la coloration au select du modal d'édition également
    const modalStatut = document.getElementById('edit_statut');
    if (modalStatut) {
        updateStatutClass(modalStatut);
        modalStatut.addEventListener('change', () => updateStatutClass(modalStatut));
    }
    
    // Bouton d'ajout contrôle
    const addControleBtn = document.getElementById('addControle');
    if (addControleBtn) {
        addControleBtn.addEventListener('click', addControle);
    }
    
    // Sauvegarde édition contrôle
    const saveControleButton = document.getElementById('saveControleEdit');
    if (saveControleButton) {
        saveControleButton.addEventListener('click', saveControleEdit);
    }

    // Intercepter l'envoi du formulaire pour joindre les photos en file
    const modificationForm = document.getElementById('modificationForm');
    if (modificationForm) {
        modificationForm.addEventListener('submit', function(e) {
            // Si pas de photos en file, laisser le submit natif
            if (queuedPhotos.size === 0) return;

            e.preventDefault();

            const formData = new FormData(modificationForm);

            // Joindre les photos en file avec des clés 'controles-<index>-photo'
            queuedPhotos.forEach((file, index) => {
                formData.append(`controles-${index}-photo`, file);
            });

            fetch(modificationForm.action || window.location.href, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                }
            }).then(response => {
                if (response.ok) {
                    // Redirection finale (si fournie)
                    window.location = response.url || window.location.href;
                } else {
                    // En cas d'erreur, recharger la page pour afficher les erreurs retournées
                    return response.text().then(html => {
                        document.open(); document.write(html); document.close();
                    });
                }
            }).catch(err => {
                console.error('Erreur lors de l\u2019envoi du formulaire avec photos:', err);
                alert('Erreur lors de l\u2019envoi. Veuillez réessayer.');
            });
        });
    }
    
    // Gestionnaire de changement d'ouvrage dans le modal
    document.getElementById('edit_ouvrage')?.addEventListener('change', function() {
        const ouvrageId = this.value;
        const pointSelect = document.getElementById('edit_point_controle');
        
        if (ouvrageId) {
            fetch(`/api/elements-par-ouvrage/${ouvrageId}/`)
                .then(response => response.json())
                .then(data => {
                    pointSelect.innerHTML = '<option value="">Sélectionner un point de contrôle</option>';
                    data.elements.forEach(element => {
                        const option = document.createElement('option');
                        option.value = element.id;
                        option.textContent = element.nom;
                        pointSelect.appendChild(option);
                    });
                })
                .catch(error => console.error('Erreur:', error));
        } else {
            pointSelect.innerHTML = '<option value="">Sélectionner un point de contrôle</option>';
        }
    });
});
</script>

            <!-- Recommandations -->
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h1 class="h3 mb-0">Recommandations</h1>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="addRecommandation">
                        <i class="fa fa-plus"></i> Ajouter une recommandation
                    </button>
                </div>
                <div class="card-body">
                    {{ recommandation_formset.management_form }}
                    <div id="recommandations-container">
                        {% for recommandation_form in recommandation_formset %}
                            <div class="recommandation-form border rounded p-3 mb-3">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <h6 class="text-primary mb-0">Recommandation #{{ forloop.counter }}</h6>
                                    {% if not recommandation_form.DELETE %}
                                        <button type="button" class="btn btn-sm btn-outline-danger remove-recommandation">
                                            <i class="fa fa-trash"></i> Supprimer
                                        </button>
                                    {% endif %}
                                </div>
                                <div class="row">
                                    <div class="col-md-8 mb-2">
                                        <label class="form-label">Description</label>
                                        {{ recommandation_form.description }}
                                        {% if recommandation_form.description.errors %}
                                            <div class="invalid-feedback d-block">{{ recommandation_form.description.errors }}</div>
                                        {% endif %}
                                    </div>
                                    <div class="col-md-4 mb-2">
                                        <label class="form-label">Priorité</label>
                                        {{ recommandation_form.priorite }}
                                        {% if recommandation_form.priorite.errors %}
                                            <div class="invalid-feedback d-block">{{ recommandation_form.priorite.errors }}</div>
                                        {% endif %}
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <label class="form-label">Délai</label>
                                        {{ recommandation_form.delai }}
                                        {% if recommandation_form.delai.errors %}
                                            <div class="invalid-feedback d-block">{{ recommandation_form.delai.errors }}</div>
                                        {% endif %}
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <div class="form-check mt-4">
                                            {{ recommandation_form.statut }}
                                            <label class="form-check-label" for="{{ recommandation_form.statut.id_for_label }}">
                                                Statut (réalisé/en cours)
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                {% if recommandation_form.DELETE %}
                                    <div class="form-check mt-2">
                                        {{ recommandation_form.DELETE }}
                                        <label class="form-check-label text-danger" for="{{ recommandation_form.DELETE.id_for_label }}">
                                            Marquer pour suppression
                                        </label>
                                    </div>
                                {% endif %}
                                {% for hidden in recommandation_form.hidden_fields %}
                                    {{ hidden }}
                                {% endfor %}
                            </div>
                        {% endfor %}
                    </div>
                </div>
            </div>

            <!-- Boutons d'action -->
            <div class="d-flex gap-2 justify-content-end">
                <button type="submit" class="btn btn-primary">
                    <i class="fa fa-save"></i> Enregistrer les modifications
                </button>
                <a href="{% url 'controle:detail_pv' pv.pk %}" class="btn btn-secondary">
                    <i class="fa fa-times"></i> Annuler
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Modal pour l'édition des participants -->
<div class="modal fade" id="participantModal" tabindex="-1" aria-labelledby="participantModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="participantModalLabel">Éditer le participant</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Nom</label>
                    <input type="text" class="form-control" id="edit_nom">
                </div>
                <div class="mb-3">
                    <label class="form-label">Fonction</label>
                    <input type="text" class="form-control" id="edit_fonction">
                </div>
                <div class="mb-3">
                    <label class="form-label">Organisme</label>
                    <input type="text" class="form-control" id="edit_organisme">
                </div>
                <div class="form-check">
                    <input type="checkbox" class="form-check-input" id="edit_signature_presente">
                    <label class="form-check-label" for="edit_signature_presente">Signature présente</label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                <button type="button" class="btn btn-primary" id="saveParticipantEdit">Enregistrer</button>
            </div>
        </div>
    </div>
</div>

<!-- Templates pour les formulaires vides (JavaScript) -->
<div id="empty-participant-row" style="display: none;">
    <tr class="participant-form" data-form-id="__prefix__">
        <td>
            <input type="text" name="participants-__prefix__-nom" class="form-control" placeholder="Nom du participant">
        </td>
        <td>
            <input type="text" name="participants-__prefix__-fonction" class="form-control" placeholder="Fonction">
        </td>
        <td>
            <input type="text" name="participants-__prefix__-organisme" class="form-control" placeholder="Organisme">
        </td>
        <td class="text-center">
            <input type="hidden" name="participants-__prefix__-signature" value="">
            <span class="text-muted">Non signé</span>
        </td>
        <td class="text-center">
            <div class="btn-group btn-group-sm" role="group">
                <button type="button" class="btn btn-outline-primary edit-participant" data-id="__prefix__">
                    <i class="fa fa-edit"></i>
                </button>
                <button type="button" class="btn btn-outline-danger remove-participant" data-id="__prefix__">
                    <i class="fa fa-trash"></i>
                </button>
            </div>
        </td>
    </tr>
</div>

<div id="empty-controle-form" style="display: none;">
    <div class="controle-form border rounded p-3 mb-3">
        <div class="d-flex justify-content-between align-items-start mb-2">
            <h6 class="text-primary mb-0">Nouveau contrôle</h6>
            <button type="button" class="btn btn-sm btn-outline-danger remove-controle">
                <i class="fa fa-trash"></i> Supprimer
            </button>
        </div>
        <div class="row">
            <div class="col-md-6 mb-2">
                <label class="form-label">Ouvrage</label>
                <select class="form-select ouvrage-select" data-target="id_controles-__prefix__-point_controle">
                    <option value="">Sélectionner un ouvrage</option>
                    {% for ouvrage in ouvrages %}
                        <option value="{{ ouvrage.id }}">{{ ouvrage.nom }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-6 mb-2">
                <label class="form-label">Point de contrôle</label>
                {{ controle_formset.empty_form.point_controle }}
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 mb-2">
                <label class="form-label">Résultat</label>
                {{ controle_formset.empty_form.statut }}
            </div>
            <div class="col-md-6 mb-2">
                <label class="form-label">Observation</label>
                {{ controle_formset.empty_form.observation }}
            </div>
        </div>
        {% for hidden in controle_formset.empty_form.hidden_fields %}
            {{ hidden }}
        {% endfor %}
    </div>
</div>

<div id="empty-recommandation-form" style="display: none;">
    <div class="recommandation-form border rounded p-3 mb-3">
        <div class="d-flex justify-content-between align-items-start mb-2">
            <h6 class="text-primary mb-0">Nouvelle recommandation</h6>
            <button type="button" class="btn btn-sm btn-outline-danger remove-recommandation">
                <i class="fa fa-trash"></i> Supprimer
            </button>
        </div>
        <div class="row">
            <div class="col-md-8 mb-2">
                <label class="form-label">Description</label>
                {{ recommandation_formset.empty_form.description }}
            </div>
            <div class="col-md-4 mb-2">
                <label class="form-label">Priorité</label>
                {{ recommandation_formset.empty_form.priorite }}
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 mb-2">
                <label class="form-label">Délai</label>
                {{ recommandation_formset.empty_form.delai }}
            </div>
            <div class="col-md-6 mb-2">
                <div class="form-check mt-4">
                    {{ recommandation_formset.empty_form.statut }}
                    <label class="form-check-label">Statut (réalisé/en cours)</label>
                </div>
            </div>
        </div>
        {% for hidden in recommandation_formset.empty_form.hidden_fields %}
            {{ hidden }}
        {% endfor %}
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // ==================== GESTION DES PARTICIPANTS ====================
    let currentEditRow = null;
    
    // Mettre à jour les indices des formulaires participants
    function updateParticipantIndices() {
        const rows = document.querySelectorAll('#participants-container tr.participant-form:not([style*="display: none"])');
        const totalForms = document.getElementById('id_participants-TOTAL_FORMS');
        
        rows.forEach((row, index) => {
            row.setAttribute('data-form-id', index);
            
            const inputs = row.querySelectorAll('input, select, textarea');
            inputs.forEach(input => {
                if (input.name) {
                    input.name = input.name.replace(/participants-\d+-/, `participants-${index}-`);
                }
                if (input.id) {
                    input.id = input.id.replace(/id_participants-\d+/, `id_participants-${index}`);
                }
            });
            
            const editBtn = row.querySelector('.edit-participant');
            if (editBtn) editBtn.setAttribute('data-id', index);
            
            const deleteBtn = row.querySelector('.delete-participant, .remove-participant');
            if (deleteBtn) deleteBtn.setAttribute('data-id', index);
        });
        
        if (totalForms) {
            totalForms.value = rows.length;
        }
    }
    
    // Ajouter un participant
    function addParticipant() {
        const container = document.getElementById('participants-container');
        const template = document.getElementById('empty-participant-row');
        const newRow = template.cloneNode(true);
        newRow.style.display = '';
        newRow.id = '';
        
        const formCount = parseInt(document.getElementById('id_participants-TOTAL_FORMS').value);
        const newHtml = newRow.innerHTML.replace(/__prefix__/g, formCount);
        newRow.innerHTML = newHtml;
        
        container.appendChild(newRow);
        updateParticipantIndices();
        attachParticipantRowEvents(newRow);
    }
    
    // Supprimer un participant
    function deleteParticipant(row) {
        const deleteCheckbox = row.querySelector('input[type="checkbox"][name$="-DELETE"]');
        if (deleteCheckbox) {
            deleteCheckbox.checked = true;
            row.style.display = 'none';
        } else {
            row.remove();
            updateParticipantIndices();
        }
    }
    
    // Éditer un participant
    function editParticipant(row) {
        currentEditRow = row;
        
        const nomInput = row.querySelector('input[name$="-nom"]');
        const fonctionInput = row.querySelector('input[name$="-fonction"]');
        const organismeInput = row.querySelector('input[name$="-organisme"]');
        const signatureInput = row.querySelector('input[name$="-signature"]');

        document.getElementById('edit_nom').value = nomInput ? nomInput.value : '';
        document.getElementById('edit_fonction').value = fonctionInput ? fonctionInput.value : '';
        document.getElementById('edit_organisme').value = organismeInput ? organismeInput.value : '';
        document.getElementById('edit_signature_presente').checked = signatureInput && signatureInput.value ? true : false;
        
        const modal = new bootstrap.Modal(document.getElementById('participantModal'));
        modal.show();
    }
    
    // Sauvegarder les modifications
    function saveParticipantEdit() {
        if (currentEditRow) {
            const nomInput = currentEditRow.querySelector('input[name$="-nom"]');
            const fonctionInput = currentEditRow.querySelector('input[name$="-fonction"]');
            const organismeInput = currentEditRow.querySelector('input[name$="-organisme"]');
            const signatureInput = currentEditRow.querySelector('input[name$="-signature"]');

            if (nomInput) nomInput.value = document.getElementById('edit_nom').value;
            if (fonctionInput) fonctionInput.value = document.getElementById('edit_fonction').value;
            if (organismeInput) organismeInput.value = document.getElementById('edit_organisme').value;
            if (signatureInput) signatureInput.value = document.getElementById('edit_signature_presente').checked ? '1' : '';

            // Mettre à jour le badge d'affichage dans la cellule signature
            const sigCell = currentEditRow.querySelector('td.text-center');
            if (sigCell) {
                const badge = sigCell.querySelector('span');
                if (document.getElementById('edit_signature_presente').checked) {
                    if (badge) badge.outerHTML = '<span class="badge bg-success">Signé</span>';
                } else {
                    if (badge) badge.outerHTML = '<span class="badge bg-secondary">Non signé</span>';
                }
            }
            
            const modal = bootstrap.Modal.getInstance(document.getElementById('participantModal'));
            if (modal) modal.hide();
            currentEditRow = null;
        }
    }
    
    // Attacher les événements à une ligne participant
    function attachParticipantRowEvents(row) {
        const editBtn = row.querySelector('.edit-participant');
        const deleteBtn = row.querySelector('.delete-participant, .remove-participant');
        
        if (editBtn) {
            editBtn.addEventListener('click', (e) => {
                e.preventDefault();
                editParticipant(row);
            });
        }
        
        if (deleteBtn) {
            deleteBtn.addEventListener('click', (e) => {
                e.preventDefault();
                deleteParticipant(row);
            });
        }
    }
    
    // ==================== GESTION DES CONTRÔLES ====================
    function filterElements(ouvrageSelect, elementSelect) {
        const ouvrageId = ouvrageSelect.value;
        elementSelect.disabled = true;
        
        if (ouvrageId) {
            fetch(`/api/elements-par-ouvrage/${ouvrageId}/`)
                .then(response => response.json())
                .then(data => {
                    elementSelect.innerHTML = '<option value="">Sélectionner un élément</option>';
                    data.elements.forEach(element => {
                        const option = document.createElement('option');
                        option.value = element.id;
                        option.textContent = element.nom;
                        elementSelect.appendChild(option);
                    });
                    elementSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Erreur:', error);
                    elementSelect.disabled = false;
                });
        } else {
            elementSelect.innerHTML = '<option value="">Sélectionner un élément</option>';
            elementSelect.disabled = false;
        }
    }
    
    // Initialisation des contrôles existants
    document.querySelectorAll('.ouvrage-select').forEach(select => {
        select.addEventListener('change', function() {
            const targetId = this.dataset.target;
            const elementSelect = document.getElementById(targetId);
            if (elementSelect) {
                filterElements(this, elementSelect);
            }
        });
    });
    
    // Ajouter un contrôle
    const addControleBtn = document.getElementById('addControle');
    const controlesContainer = document.getElementById('controles-container');
    const totalControleForms = document.getElementById('id_controles-TOTAL_FORMS');
    
    if (addControleBtn) {
        addControleBtn.addEventListener('click', function() {
            const formCount = parseInt(totalControleForms.value);
            const newForm = document.getElementById('empty-controle-form').cloneNode(true);
            newForm.style.display = 'block';
            newForm.id = '';
            newForm.innerHTML = newForm.innerHTML.replace(/__prefix__/g, formCount);
            
            controlesContainer.appendChild(newForm);
            totalControleForms.value = formCount + 1;
            
            const ouvrageSelect = newForm.querySelector('.ouvrage-select');
            ouvrageSelect.dataset.target = `id_controles-${formCount}-point_controle`;
            ouvrageSelect.addEventListener('change', function() {
                const elementSelect = document.getElementById(`id_controles-${formCount}-point_controle`);
                if (elementSelect) filterElements(this, elementSelect);
            });
            
            newForm.querySelector('.remove-controle').addEventListener('click', function() {
                newForm.remove();
            });
        });
    }
    
    // Ajouter une recommandation
    const addRecommandationBtn = document.getElementById('addRecommandation');
    const recommandationsContainer = document.getElementById('recommandations-container');
    const totalRecommandationForms = document.getElementById('id_recommandations-TOTAL_FORMS');
    
    if (addRecommandationBtn) {
        addRecommandationBtn.addEventListener('click', function() {
            const formCount = parseInt(totalRecommandationForms.value);
            const newForm = document.getElementById('empty-recommandation-form').cloneNode(true);
            newForm.style.display = 'block';
            newForm.id = '';
            newForm.innerHTML = newForm.innerHTML.replace(/__prefix__/g, formCount);
            
            recommandationsContainer.appendChild(newForm);
            totalRecommandationForms.value = formCount + 1;
            
            newForm.querySelector('.remove-recommandation').addEventListener('click', function() {
                newForm.remove();
            });
        });
    }
    
    // Initialisation des événements pour les participants existants
    document.querySelectorAll('#participants-container tr.participant-form').forEach(row => {
        attachParticipantRowEvents(row);
    });
    
    // Bouton d'ajout participant
    const addParticipantBtn = document.getElementById('addParticipant');
    if (addParticipantBtn) {
        addParticipantBtn.addEventListener('click', addParticipant);
    }
    
    // Sauvegarde édition participant
    const saveButton = document.getElementById('saveParticipantEdit');
    if (saveButton) {
        saveButton.addEventListener('click', saveParticipantEdit);
    }
    
    // Gestionnaires de suppression existants
    document.querySelectorAll('.remove-controle').forEach(btn => {
        btn.addEventListener('click', function() {
            const form = this.closest('.controle-form');
            const deleteCheckbox = form.querySelector('input[type="checkbox"][name$="-DELETE"]');
            if (deleteCheckbox) {
                deleteCheckbox.checked = true;
                form.style.display = 'none';
            } else {
                form.remove();
            }
        });
    });
    
    document.querySelectorAll('.remove-recommandation').forEach(btn => {
        btn.addEventListener('click', function() {
            const form = this.closest('.recommandation-form');
            const deleteCheckbox = form.querySelector('input[type="checkbox"][name$="-DELETE"]');
            if (deleteCheckbox) {
                deleteCheckbox.checked = true;
                form.style.display = 'none';
            } else {
                form.remove();
            }
        });
    });
    
    // Validation du formulaire
    document.getElementById('modificationForm').addEventListener('submit', function(e) {
        if (!this.checkValidity()) {
            e.preventDefault();
            e.stopPropagation();
        }
        this.classList.add('was-validated');
    });
});
</script>
{% endblock %}