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

{% block title %}Création d'un procès-verbal{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- Barre de progression améliorée -->
    <div class="row mb-6">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-between align-items-center mb-2">
                        <h5 class="mb-0" id="step-display-title">Étape 1: Informations générales</h5>
                        <span class="badge bg-label-primary" id="card-step-label">1/3</span>
                    </div>
                    <div class="progress" style="height: 8px;">
                        <div id="main-progress-bar" class="progress-bar bg-primary" role="progressbar" style="width: 33%"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-xl">
            <div class="card mb-6">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Nouveau Procès-Verbal</h5>
                    <small class="text-body float-end">Contrôle Technique</small>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data" id="formProcesVerbal" novalidate>
                        {% csrf_token %}
                        <input type="hidden" name="current_step" id="current_step" value="1" />
                      
                        <!-- Étape 1: Informations générales -->
                        <!-- Étape 1: Informations générales -->
<div class="step-content active" id="step1">
    
    <div class="mb-6">
        <label class="form-label required" for="id_type_pv">Type de procès-verbal</label>
        <select name="type_pv" id="id_type_pv" class="form-select" required>
            <option value="">Sélectionnez un type de PV</option>
            {% for type_pv in form.fields.type_pv.queryset %}
            <option value="{{ type_pv.id }}" 
                {% if form.instance.type_pv.id == type_pv.id %}selected{% endif %}>
                {{ type_pv.type_pv }}
            </option>
            {% endfor %}
        </select>
        <div class="invalid-feedback">Veuillez sélectionner un type de procès-verbal</div>
    </div>
                                                
    <div class="mb-6">
        <label class="form-label required" for="id_client">Client / Maître d'ouvrage</label>
        <select name="client" id="id_client" class="form-select" required>
            <option value="">Sélectionnez un client</option>
            {% for client in form.fields.client.queryset %}
            <option value="{{ client.id }}" 
                {% if form.client.value|stringformat:"s" == client.id|stringformat:"s" %}selected{% endif %}>
                {{ client.nom }}
            </option>
            {% endfor %}
        </select>
        <div class="invalid-feedback">Veuillez sélectionner un client</div>
    </div>

    <div class="mb-6">
        <label class="form-label required" for="id_objet_controle">Objet du contrôle / Projet</label>
        <select name="objet_controle" id="id_objet_controle" class="form-select" required>
            <option value="">Sélectionnez un projet</option>
            {% for projet in projets %}
            <option value="{{ projet.id }}" data-client="{{ projet.client.id }}" data-adresse="{{ projet.adresse|escapejs }}"
                {% if form.objet_controle.value|stringformat:"s" == projet.id|stringformat:"s" %}selected{% endif %}>
                {{ projet.nom_projet }}
            </option>
            {% endfor %}
        </select>
        <div class="invalid-feedback">Veuillez sélectionner un projet</div>
    </div>
    
    <div class="row">
        <div class="col-md-6 mb-6">
            <label class="form-label required" for="id_date_visite">Date de visite</label>
            <input type="datetime-local" name="date_visite" id="id_date_visite" 
                   class="form-control" 
                   value="{{ form.date_visite.value|date:'Y-m-d\TH:i'|default:'' }}" 
                   required>
            <div class="invalid-feedback">Veuillez saisir la date de visite</div>
        </div>
        
        <div class="col-md-6 mb-6">
            <label class="form-label required" for="id_lieu">Lieu / Adresse du chantier</label>
            <div class="input-group input-group-merge">
                <span class="input-group-text"><i class="bx bx-map"></i></span>
                <input type="text" name="lieu" id="id_lieu" class="form-control" 
                       value="{{ form.lieu.value|default:'' }}"
                       placeholder="Rue 12, Point E, Dakar" required>
            </div>
            <div class="invalid-feedback">Veuillez saisir le lieu du chantier</div>
        </div>
    </div>
    
    

<style>
.projet-card {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.3s;
}

.projet-card:hover {
    background-color: #f8f9fa;
    border-color: #0d6efd;
}

.projet-card.selected {
    background-color: #cfe2ff;
    border-color: #0d6efd;
}

.projet-nom {
    font-weight: bold;
    margin-bottom: 5px;
}

.projet-description {
    font-size: 12px;
    color: #6c757d;
}

.btn-ajouter-projet {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 6px;
    cursor: pointer;
}

.btn-ajouter-projet:hover {
    background-color: #218838;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const clientSelect = document.getElementById('id_client');
    const projetSelect = document.getElementById('id_objet_controle');
    const lieuInput = document.getElementById('id_lieu');
    const originalOptions = Array.from(projetSelect.options).map(option => ({
        value: option.value,
        text: option.text,
        clientId: option.dataset.client || '',
        adresse: option.dataset.adresse || '',
        selected: option.selected
    }));

    function updateLieuFromProjet() {
        const selectedOption = projetSelect.selectedOptions[0];
        if (selectedOption && selectedOption.dataset.adresse) {
            lieuInput.value = selectedOption.dataset.adresse;
        }
    }

    function refreshProjetOptions() {
        const clientId = clientSelect.value;
        const previousValue = projetSelect.value;
        projetSelect.innerHTML = '';

        const placeholder = document.createElement('option');
        placeholder.value = '';
        placeholder.disabled = true;
        placeholder.selected = true;
        placeholder.textContent = clientId ? 'Sélectionnez un projet' : 'Sélectionnez un client d\'abord';
        projetSelect.appendChild(placeholder);

        let hasProjet = false;
        originalOptions.forEach(opt => {
            if (!opt.value || !clientId) {
                return;
            }
            if (opt.clientId === clientId) {
                const option = document.createElement('option');
                option.value = opt.value;
                option.textContent = opt.text;
                option.dataset.adresse = opt.adresse;
                if (opt.selected || opt.value === previousValue) {
                    option.selected = true;
                    placeholder.selected = false;
                    hasProjet = true;
                }
                projetSelect.appendChild(option);
                hasProjet = true;
            }
        });

        if (clientId && !hasProjet) {
            const emptyOption = document.createElement('option');
            emptyOption.value = '';
            emptyOption.disabled = true;
            emptyOption.textContent = 'Aucun projet disponible pour ce client';
            projetSelect.appendChild(emptyOption);
        }

        projetSelect.disabled = !clientId;
        updateLieuFromProjet();
    }

    projetSelect.addEventListener('change', updateLieuFromProjet);
    clientSelect.addEventListener('change', refreshProjetOptions);
    refreshProjetOptions();
});
</script>
</div>

<!-- Étape 2: Participants & Signatures -->
<div class="step-content" id="step2" style="display:none;">
    <div class="alert alert-info mb-6">
        <i class="bx bx-info-circle me-1"></i>
        Ajoutez les signatures des personnes présentes lors du contrôle.
    </div>
    {{ participant_formset.management_form }}
    <div id="participants-container" class="row g-3">
        {% for participant_form in participant_formset %}
        <div class="col-12 col-md-6" id="participant-col-{{ forloop.counter0 }}">
            <div class="card participant-card h-100" id="participant-{{ forloop.counter0 }}">
                <div class="card-body d-flex flex-column">
                    <div class="d-flex align-items-center mb-3">
                        <div class="avatar rounded-circle bg-primary text-white d-flex align-items-center justify-content-center me-3" style="width:48px;height:48px;font-weight:600;">
                            {{ participant_form.nom.value|default_if_none:''|slice:":1"|upper }}
                        </div>
                        <div class="flex-grow-1">
                            <label class="form-label mb-1">Nom du participant</label>
                            {{ participant_form.nom }}
                            {% if participant_form.nom.errors %}
                            <div class="text-danger small">{{ participant_form.nom.errors }}</div>
                            {% endif %}
                        </div>
                        <div class="ms-2">
                            {% if participant_form.instance.pk %}
                            <div class="form-check">
                                {{ participant_form.DELETE }}
                                <label class="form-check-label text-danger">Supprimer</label>
                            </div>
                            {% elif not forloop.first %}
                            <button type="button" class="btn btn-sm btn-outline-danger remove-participant">
                                <i class="bx bx-trash"></i>
                            </button>
                            {% endif %}
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label mb-1">Fonction</label>
                        {{ participant_form.fonction }}
                        {% if participant_form.fonction.errors %}
                        <div class="text-danger small">{{ participant_form.fonction.errors }}</div>
                        {% endif %}
                    </div>
                    <div class="mb-3">
                        <label class="form-label mb-1">Organisme</label>
                        {{ participant_form.organisme }}
                        {% if participant_form.organisme.errors %}
                        <div class="text-danger small">{{ participant_form.organisme.errors }}</div>
                        {% endif %}
                    </div>

                    <div class="mb-3">
                        <label class="form-label mb-1">Signature</label>
                        <div class="signature-pad-wrapper border bg-white rounded p-2" style="height:150px;">
                            <canvas class="signature-pad" width="600" height="150" data-participant-index="{{ forloop.counter0 }}" style="width:100%;height:100%;touch-action: none;"></canvas>
                        </div>
                        <div class="mt-2 d-flex align-items-center gap-2">
                            <button type="button" class="btn btn-sm btn-outline-secondary clear-sig" data-participant-index="{{ forloop.counter0 }}">
                                <i class="bx bx-eraser"></i> Effacer
                            </button>
                            <button type="button" class="btn btn-sm btn-primary save-sig" data-participant-index="{{ forloop.counter0 }}">
                                <i class="bx bx-save"></i> Sauvegarder
                            </button>
                            <span class="badge bg-success ms-2 sig-saved-badge" style="display:none;">Sauvegardée</span>
                        </div>
                        {{ participant_form.signature }}
                    </div>

                    <div class="mt-auto text-end">
                        <!-- Espace pour actions futures -->
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

    <div class="mt-3">
        <button type="button" class="btn btn-outline-primary" id="addParticipant">
            <i class="bx bx-plus"></i> Ajouter un participant
        </button>
    </div>

    <style>
    .participant-card .avatar { font-size: 18px; }
    .signature-pad-wrapper { position: relative; }
    .sig-saved-badge { font-size: 0.75rem; }
    </style>

    <script src="{% static 'js/signature.js' %}"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialiser un SignaturePad pour chaque canvas présent
        const pads = {};
        document.querySelectorAll('.signature-pad').forEach(canvas => {
            const idx = canvas.dataset.participantIndex;
            pads[idx] = new SignaturePad(canvas, { lineWidth: 2, lineColor: '#111' });

            // Si le champ signature contient déjà une dataURL, on l'affiche
            const hiddenInput = document.querySelector(`input[name='participants-${idx}-signature']`);
            if (hiddenInput && hiddenInput.value) {
                const img = new Image();
                img.src = hiddenInput.value;
                img.onload = () => {
                    const ctx = canvas.getContext('2d');
                    ctx.clearRect(0,0,canvas.width,canvas.height);
                    ctx.drawImage(img,0,0,canvas.width,canvas.height);
                    const badge = canvas.closest('.participant-card').querySelector('.sig-saved-badge');
                    if (badge) badge.style.display = 'inline-block';
                };
            }
        });

        // Boutons Effacer
        document.querySelectorAll('.clear-sig').forEach(btn => {
            btn.addEventListener('click', function() {
                const idx = this.dataset.participantIndex;
                if (pads[idx]) pads[idx].clear();
                const hidden = document.querySelector(`input[name='participants-${idx}-signature']`);
                if (hidden) { hidden.value = ''; }
                const badge = document.querySelector(`#participant-${idx} .sig-saved-badge`);
                if (badge) badge.style.display = 'none';
            });
        });

        // Boutons Sauvegarder (place la dataURL dans le champ caché)
        document.querySelectorAll('.save-sig').forEach(btn => {
            btn.addEventListener('click', function() {
                const idx = this.dataset.participantIndex;
                if (!pads[idx]) return;
                const dataURL = pads[idx].toDataURL();
                const hidden = document.querySelector(`input[name='participants-${idx}-signature']`);
                if (hidden) {
                    hidden.value = dataURL;
                    // Indicateur visuel
                    const badge = this.closest('.participant-card').querySelector('.sig-saved-badge');
                    if (badge) {
                        badge.style.display = 'inline-block';
                        setTimeout(() => { badge.style.opacity = 1; }, 10);
                    }
                }
            });
        });

        // Ajouter un participant (cloner le dernier formulaire du formset)
        const addBtn = document.getElementById('addParticipant');
        if (addBtn) {
            addBtn.addEventListener('click', function() {
                const container = document.getElementById('participants-container');
                const totalForms = document.querySelector('input[name="participants-TOTAL_FORMS"]');
                const current = parseInt(totalForms.value, 10);
                const templateForm = container.querySelector('[id^="participant-col-"]:last-child');
                const clone = templateForm.cloneNode(true);

                // Mettre à jour les ids et noms des champs clonés
                clone.id = `participant-col-${current}`;
                clone.querySelectorAll('[name]').forEach(el => {
                    if (el.name) {
                        el.name = el.name.replace(/participants-\d+-/, `participants-${current}-`);
                        el.id = el.id ? el.id.replace(/participants-\d+-/, `participants-${current}-`) : el.id;
                        if (el.type === 'text' || el.tagName.toLowerCase() === 'input' || el.tagName.toLowerCase() === 'textarea') el.value = '';
                    }
                });

                // Mettre à jour le canvas data-index
                const canvas = clone.querySelector('.signature-pad');
                if (canvas) {
                    canvas.dataset.participantIndex = current;
                    const ctx = canvas.getContext('2d'); ctx.clearRect(0,0,canvas.width,canvas.height);
                }

                // Cacher le badge sauvegarde
                const badge = clone.querySelector('.sig-saved-badge'); if (badge) badge.style.display = 'none';

                container.appendChild(clone);
                totalForms.value = current + 1;

                // Initialiser le pad pour le nouveau canvas
                const newCanvas = clone.querySelector('.signature-pad');
                if (newCanvas) {
                    const idx = newCanvas.dataset.participantIndex;
                    pads[idx] = new SignaturePad(newCanvas, { lineWidth: 2, lineColor: '#111' });
                    // reattach buttons
                    clone.querySelectorAll('.clear-sig').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const i = this.dataset.participantIndex;
                            if (pads[i]) pads[i].clear();
                            const hidden = document.querySelector(`input[name='participants-${i}-signature']`);
                            if (hidden) hidden.value = '';
                        });
                    });
                    clone.querySelectorAll('.save-sig').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const i = this.dataset.participantIndex;
                            const dataURL = pads[i].toDataURL();
                            const hidden = document.querySelector(`input[name='participants-${i}-signature']`);
                            if (hidden) hidden.value = dataURL;
                        });
                    });
                }
            });
        }
    });
    </script>
</div>
                            
                        <!-- Étape 3: Points de contrôle - Présentation en deux colonnes -->
                        <div class="step-content" id="step3" style="display:none;">
                            <div class="alert alert-warning mb-6">
                                <i class="bx bx-error-circle me-1"></i>
                                Renseignez les différents éléments d'ouvrage et leurs points de contrôle.
                            </div>
                            
                            <!-- Structure en deux colonnes -->
                            <div class="row">
                                <!-- Colonne de gauche : Ouvrages et leurs éléments -->
                                <div class="col-md-5">
                                    <div class="card">
                                        <div class="card-header bg-light">
                                            <h6 class="mb-0"><i class="bx bx-building-house me-1"></i> Ouvrages et éléments</h6>
                                        </div>
                                        <div class="card-body p-0" style="max-height: 500px; overflow-y: auto;">
                                            {% regroup elements_ouvrage by ouvrage as ouvrage_list %}
                                            {% for ouvrage in ouvrage_list %}
                                            <div class="ouvrage-section border-bottom">
                                                <div class="bg-primary bg-opacity-10 p-3">
                                                    <strong class="text-primary">
                                                        <i class="bx bx-folder me-1"></i>
                                                        {{ ouvrage.grouper.nom }} ({{ ouvrage.grouper.code }})
                                                    </strong>
                                                </div>
                                                <div class="list-group list-group-flush">
                                                    {% for element in ouvrage.list %}
                                                    <div class="list-group-item list-group-item-action element-item" 
                                                         data-element-id="{{ element.id }}"
                                                         data-element-name="{{ element.nom|escapejs }}"
                                                         style="cursor: pointer;"
                                                         onclick="selectElement({{ element.id }})">
                                                        <div class="d-flex justify-content-between align-items-center">
                                                            <div>
                                                                <span class="badge bg-secondary me-2">{{ element.code }}</span>
                                                                {{ element.nom }}
                                                            </div>
                                                            <span class="badge {% if element.etat == 'CONFORME' %}bg-success{% elif element.etat == 'NON_CONFORME' %}bg-danger{% else %}bg-warning{% endif %}">
                                                                {{ element.get_etat_display }}
                                                            </span>
                                                        </div>
                                                        {% if element.description %}
                                                        <small class="text-muted d-block mt-1">{{ element.description|truncatechars:100 }}</small>
                                                        {% endif %}
                                                    </div>
                                                    {% endfor %}
                                                </div>
                                            </div>
                                            {% empty %}
                                            <div class="text-center p-4 text-muted">
                                                <i class="bx bx-info-circle fs-3 mb-2"></i>
                                                <p>Aucun élément d'ouvrage disponible.</p>
                                            </div>
                                            {% endfor %}
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Colonne de droite : Points de contrôle pour l'élément sélectionné -->
                                <div class="col-md-7">
                                    <div class="card">
                                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                                            <h6 class="mb-0"><i class="bx bx-check-circle me-1"></i> Points de contrôle</h6>
                                            <span class="badge bg-primary" id="selected-element-name">Aucun élément sélectionné</span>
                                        </div>
                                        <div class="card-body" id="points-controle-container" style="min-height: 400px; max-height: 500px; overflow-y: auto;">
                                            <div class="text-center text-muted p-5" id="no-element-selected-message">
                                                <i class="bx bx-arrow-back bx-lg mb-3"></i>
                                                <p>Sélectionnez un élément d'ouvrage dans la colonne de gauche pour afficher ses points de contrôle.</p>
                                            </div>
                                            
                                            <!-- Les points de contrôle seront chargés dynamiquement ici via JavaScript -->
                                            <div id="points-controle-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Bouton pour valider les contrôles -->
                            <div class="row mt-4">
                                <div class="col-12 text-end">
                                    <button type="button" class="btn btn-success" id="validateControles" style="display: none;">
                                        <i class="bx bx-check"></i> Valider les contrôles de cet élément
                                    </button>
                                </div>
                            </div>
                            
                            <!-- Résumé des contrôles saisis -->
                            <div class="row mt-4">
                                <div class="col-12">
                                    <div class="card bg-light">
                                        <div class="card-body">
                                            <h6 class="mb-3">Récapitulatif des contrôles</h6>
                                            <div class="row text-center">
                                                <div class="col-3">
                                                    <div class="border rounded p-2 bg-white">
                                                        <span class="badge bg-success mb-1">Conforme</span>
                                                        <h4 class="mb-0" id="countConforme">0</h4>
                                                    </div>
                                                </div>
                                                <div class="col-3">
                                                    <div class="border rounded p-2 bg-white">
                                                        <span class="badge bg-danger mb-1">Non conforme</span>
                                                        <h4 class="mb-0" id="countNonConforme">0</h4>
                                                    </div>
                                                </div>
                                                <div class="col-3">
                                                    <div class="border rounded p-2 bg-white">
                                                        <span class="badge bg-warning mb-1">Suspendu</span>
                                                        <h4 class="mb-0" id="countSuspendu">0</h4>
                                                    </div>
                                                </div>
                                                <div class="col-3">
                                                    <div class="border rounded p-2 bg-white">
                                                        <span class="badge bg-secondary mb-1">Total</span>
                                                        <h4 class="mb-0" id="countTotal">0</h4>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Observations générales -->
                            <div class="row mt-4">
                                <div class="col-12">
                                    <div class="card">
                                        <div class="card-body">
                                            <label class="form-label fw-bold">Observations Générales</label>
                                            <textarea name="observations_generales" class="form-control" rows="4" 
                                                      placeholder="Saisissez vos remarques finales et conclusions...">{{ form.observations_generales.value|default:'' }}</textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Champs cachés pour stocker les résultats de contrôle -->
                            <div id="controles-hidden-inputs"></div>
                            <div id="points-controle-storage" style="display:none;"></div>
                        </div>

                        <!-- Navigation buttons -->
                        <div class="mt-6 d-flex justify-content-between">
                            <button type="button" class="btn btn-outline-secondary" id="prevBtn" disabled>
                                <i class="bx bx-chevron-left"></i> Précédent
                            </button>
                            
                            <div>
                                <button type="button" class="btn btn-outline-danger me-2" id="cancelBtn">
                                    <i class="bx bx-x"></i> Annuler
                                </button>
                                <button type="button" class="btn btn-primary" id="nextBtn">
                                    Suivant <i class="bx bx-chevron-right"></i>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Template pour nouveau participant -->
<template id="participant-template">
    <div class="participant-item mb-6 p-4 border rounded">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="mb-0">Nouveau participant</h6>
            <button type="button" class="btn btn-sm btn-outline-danger remove-participant">
                <i class="bx bx-trash"></i>
            </button>
        </div>
        
        <div class="mb-3">
            <label class="form-label required">Nom du participant</label>
            <input type="text" name="participants-__prefix__-nom" class="form-control participant-name" placeholder="Nom complet" required>
        </div>
        
        <div class="mb-3">
            <label class="form-label required">Signature</label>
            <div class="signature-pad-wrapper border bg-light rounded" style="height: 150px;">
                <canvas class="signature-pad" width="500" height="150" style="width: 100%; height: 100%;" data-participant-index="__prefix__"></canvas>
            </div>
            <div class="mt-2 d-flex gap-2">
                <button type="button" class="btn btn-sm btn-outline-secondary clear-sig" data-participant-index="__prefix__">
                    <i class="bx bx-eraser"></i> Effacer
                </button>
                <button type="button" class="btn btn-sm btn-outline-primary save-sig" data-participant-index="__prefix__">
                    <i class="bx bx-save"></i> Sauvegarder
                </button>
            </div>
            <input type="hidden" name="participants-__prefix__-signature" class="signature-data" id="signature-__prefix__">
        </div>
    </div>
</template>

<!-- Template pour un point de contrôle -->
<template id="point-controle-template">
    <div class="point-controle-item mb-3 p-3 border rounded" data-point-id="">
        <div class="d-flex justify-content-between align-items-start">
            <div class="flex-grow-1 me-3">
                <label class="form-label fw-bold point-label"></label>
                <p class="point-description text-muted small mb-2"></p>
            </div>
            <div style="min-width: 200px;">
                <select class="form-select form-select-sm statut-select" required>
                    <option value="">Statut</option>
                    <option value="CONFORME">Conforme</option>
                    <option value="NON_CONFORME">Non conforme</option>
                    <option value="SUSPENDU">Suspendu</option>
                </select>
            </div>
        </div>
        <div class="observation-field mt-2" style="display: none;">
            <textarea class="form-control form-control-sm" rows="2" placeholder="Observation (requise pour non conforme ou suspendu)"></textarea>
        </div>
        <div class="photo-field mt-2" style="display: none;">
            <label class="form-label small"><i class="bx bx-camera me-1"></i>Photo (optionnelle pour non conforme / suspendu)</label>
            <input type="file" accept="image/*" capture="environment" class="form-control form-control-sm photo-input" />
            <img class="photo-preview mt-2" src="" style="max-height:120px; display:none; border:1px solid #e9ecef; border-radius:4px;" />
        </div>
    </div>
</template>

<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.0.0/dist/signature_pad.umd.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Configuration
        let currentStep = 1;
        const totalSteps = 3;
        const form = document.getElementById('formProcesVerbal');
        const persistedStepInput = document.getElementById('current_step');
        if (persistedStepInput && persistedStepInput.value) {
            const restoredStep = parseInt(persistedStepInput.value, 10);
            if (!Number.isNaN(restoredStep) && restoredStep >= 1 && restoredStep <= totalSteps) {
                currentStep = restoredStep;
            }
        }
        
        // État des contrôles
        let controlesState = {};
        let currentElementId = null;
        let pointsControleData = {};
        
        // Stocker les instances SignaturePad
        let signaturePads = [];
        
        // Initialisation des signatures
        function initializeSignaturePads() {
            signaturePads = [];
            document.querySelectorAll('.signature-pad').forEach((canvas, index) => {
                try {
                    const signaturePad = new SignaturePad(canvas, {
                        backgroundColor: 'rgb(255, 255, 255)',
                        penColor: 'rgb(0, 0, 0)',
                        minWidth: 1,
                        maxWidth: 2.5,
                        throttle: 16
                    });
                    
                    signaturePads.push(signaturePad);
                    
                    const participantItem = canvas.closest('.participant-item');
                    if (!participantItem) return;
                    
                    const participantIndex = canvas.getAttribute('data-participant-index') || index;
                    const signatureInput = participantItem.querySelector('input[name*="signature"]');
                    
                    // Restaurer la signature existante
                    if (signatureInput && signatureInput.value) {
                        try {
                            signaturePad.fromDataURL(signatureInput.value);
                        } catch(e) {
                            console.error('Erreur chargement signature:', e);
                        }
                    }
                    
                    const clearBtn = participantItem.querySelector(`.clear-sig[data-participant-index="${participantIndex}"]`);
                    if (clearBtn) {
                        clearBtn.addEventListener('click', (e) => {
                            e.preventDefault();
                            signaturePad.clear();
                            if (signatureInput) signatureInput.value = '';
                        });
                    }
                    
                    const saveBtn = participantItem.querySelector(`.save-sig[data-participant-index="${participantIndex}"]`);
                    if (saveBtn) {
                        saveBtn.addEventListener('click', (e) => {
                            e.preventDefault();
                            if (signaturePad.isEmpty()) {
                                showNotification('Veuillez d\'abord dessiner une signature', 'warning');
                                return;
                            }
                            const signatureData = signaturePad.toDataURL();
                            if (signatureInput) {
                                signatureInput.value = signatureData;
                                showNotification('Signature sauvegardée', 'success');
                            }
                        });
                    }
                } catch (error) {
                    console.error('Erreur initialisation signature:', error);
                }
            });
        }
        
        // Ajouter un participant
        document.getElementById('addParticipant')?.addEventListener('click', function() {
            const container = document.getElementById('participants-container');
            const totalForms = document.getElementById('id_participants-TOTAL_FORMS');
            const formCount = parseInt(totalForms.value);
            const newIndex = formCount;
            
            // Créer le nouveau formulaire avec les bons noms de champs
            const newForm = document.createElement('div');
            newForm.className = 'participant-item mb-6 p-4 border rounded';
            newForm.id = `participant-${newIndex}`;
            
            newForm.innerHTML = `
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0">Participant ${newIndex + 1}</h6>
                    <button type="button" class="btn btn-sm btn-outline-danger remove-participant">
                        <i class="bx bx-trash"></i>
                    </button>
                </div>
                
                <div class="mb-3">
                    <label class="form-label required">Nom du participant</label>
                    <input type="text" name="participants-${newIndex}-nom" class="form-control" 
                           placeholder="Nom complet" required id="id_participants-${newIndex}-nom">
                </div>
                
                <div class="mb-3">
                    <label class="form-label required">Signature</label>
                    <div class="signature-pad-wrapper border bg-light rounded" style="height: 150px;">
                        <canvas class="signature-pad" width="500" height="150" 
                                style="width: 100%; height: 100%;"
                                data-participant-index="${newIndex}"></canvas>
                    </div>
                    <div class="mt-2 d-flex gap-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary clear-sig" data-participant-index="${newIndex}">
                            <i class="bx bx-eraser"></i> Effacer
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-primary save-sig" data-participant-index="${newIndex}">
                            <i class="bx bx-save"></i> Sauvegarder
                        </button>
                    </div>
                    <input type="hidden" name="participants-${newIndex}-signature" 
                           id="id_participants-${newIndex}-signature">
                </div>
            `;
            
            container.appendChild(newForm);
            
            // Mettre à jour TOTAL_FORMS
            totalForms.value = newIndex + 1;
            
            // Initialiser la signature pour le nouveau participant
            initializeSignaturePads();
            
            // Ajouter l'événement de suppression
            newForm.querySelector('.remove-participant').addEventListener('click', function() {
                newForm.remove();
                reindexParticipants();
            });
        });
        
        // Ré-indexer les participants après suppression
        function reindexParticipants() {
            const items = document.querySelectorAll('.participant-item');
            const totalForms = document.getElementById('id_participants-TOTAL_FORMS');
            
            items.forEach((item, idx) => {
                item.id = `participant-${idx}`;
                const title = item.querySelector('h6');
                if (title) title.textContent = `Participant ${idx + 1}`;
                
                // Mettre à jour le champ nom
                const nameInput = item.querySelector('input[name*="-nom"]');
                if (nameInput) nameInput.name = `participants-${idx}-nom`;
                
                // Mettre à jour le champ signature
                const signatureInput = item.querySelector('input[name*="-signature"]');
                if (signatureInput) {
                    signatureInput.name = `participants-${idx}-signature`;
                    signatureInput.id = `id_participants-${idx}-signature`;
                }
                
                // Mettre à jour les attributs data des boutons et canvas
                item.querySelectorAll('.clear-sig, .save-sig, .signature-pad').forEach(el => {
                    el.setAttribute('data-participant-index', idx);
                });
            });
            
            totalForms.value = items.length;
            
            // Réinitialiser les signatures
            initializeSignaturePads();
        }
        
        // Suppression des participants existants
        document.querySelectorAll('.remove-participant').forEach(btn => {
            btn.addEventListener('click', function() {
                this.closest('.participant-item').remove();
                reindexParticipants();
            });
        });
        
        // Gestionnaires d'événements pour la navigation
        document.getElementById('prevBtn').addEventListener('click', () => changeStep(-1));
        document.getElementById('nextBtn').addEventListener('click', () => changeStep(1));
        document.getElementById('cancelBtn').addEventListener('click', cancelForm);
        document.getElementById('validateControles')?.addEventListener('click', validateElementControles);
        
        // Validation en temps réel
        document.querySelectorAll('[required]').forEach(field => {
            field.addEventListener('input', () => validateField(field));
        });
        
        // Charger les points de contrôle (appel déplacé après définition)
        
        function changeStep(direction) {
            if (direction === 1 && !validateStep(currentStep)) {
                showStepError(currentStep);
                return;
            }
            
            document.getElementById(`step${currentStep}`).style.display = 'none';
            currentStep += direction;
            
            if (direction === 1 && currentStep > totalSteps) {
                submitForm();
                return;
            }
            
            document.getElementById(`step${currentStep}`).style.display = 'block';
            updateUI();
            document.getElementById('current_step').value = currentStep;
            
            if (currentStep === 2) {
                initializeSignaturePads();
            }
            
            if (currentStep === 3) {
                updateRecapControles();
            }
        }
        
        function validateStep(step) {
            const stepElement = document.getElementById(`step${step}`);
            const requiredFields = stepElement.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!validateField(field)) {
                    isValid = false;
                }
            });
            
            return isValid;
        }
        
        function validateField(field) {
            if (!field.value.trim()) {
                field.classList.add('is-invalid');
                return false;
            } else {
                field.classList.remove('is-invalid');
                return true;
            }
        }
        
        function showStepError(step) {
            const stepNames = ['informations générales', 'participants', 'points de contrôle'];
            showNotification(`Veuillez remplir tous les champs obligatoires de l'étape ${stepNames[step-1]}.`, 'warning');
        }
        
        function updateUI() {
            const percent = (currentStep / totalSteps) * 100;
            document.getElementById('main-progress-bar').style.width = percent + '%';
            
            const titles = ['Informations générales', 'Participants & Signatures', 'Points de contrôle'];
            document.getElementById('step-display-title').innerText = `Étape ${currentStep}: ${titles[currentStep-1]}`;
            document.getElementById('card-step-label').innerText = `${currentStep}/${totalSteps}`;
            
            document.getElementById('prevBtn').disabled = currentStep === 1;
            
            const nextBtn = document.getElementById('nextBtn');
            if (currentStep === totalSteps) {
                nextBtn.innerHTML = '<i class="bx bx-check"></i> Enregistrer le PV';
                nextBtn.classList.remove('btn-primary');
                nextBtn.classList.add('btn-success');
            } else {
                nextBtn.innerHTML = 'Suivant <i class="bx bx-chevron-right"></i>';
                nextBtn.classList.remove('btn-success');
                nextBtn.classList.add('btn-primary');
            }
        }
        
        function submitForm() {
            // Sauvegarder toutes les signatures avant soumission
            document.querySelectorAll('.participant-card').forEach((card, idx) => {
                const signatureInput = card.querySelector('input[name*="-signature"]');
                const canvas = card.querySelector('.signature-pad');
                
                if (canvas && signatureInput && canvas.toDataURL) {
                    const canvasData = canvas.toDataURL();
                    
                    // Vérifier si ce n'est pas un canvas vide
                    if (canvasData !== 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==') {
                        signatureInput.value = canvasData;
                    }
                }
            });
            
            // Tenter de sauvegarder les contrôles de l'élément en cours avant soumission
            if (document.querySelectorAll('#points-controle-list .point-controle-item').length) {
                const validControls = validateElementControles();
                if (!validControls) {
                    return;
                }
            }

            // Vérifier l'étape 3
            if (Object.keys(controlesState).length === 0) {
                if (!confirm('Aucun contrôle n\'a été saisi. Voulez-vous continuer ?')) {
                    return;
                }
            }
            
            // Debug: Afficher les données qui vont être soumises
            console.log('=== SOUMISSION DU FORMULAIRE ===');
            const formData = new FormData(form);
            for (let pair of formData.entries()) {
                if (pair[0].includes('signature')) {
                    console.log(pair[0], 'signature_data_length:', pair[1].length);
                } else {
                    console.log(pair[0], pair[1]);
                }
            }
            
            form.submit();
        }
        
        function cancelForm() {
            if (confirm('Êtes-vous sûr de vouloir annuler la création de ce procès-verbal ?')) {
                window.location.href = '{% url "controle:liste_pv" %}';
            }
        }
        
        function showNotification(message, type = 'info') {
            alert(message);
        }
        
        // Données de points de contrôle par élément
        let pointsControleByElement = {};

        function loadPointsControle() {
            pointsControleByElement = {
                {% for element in elements_ouvrage %}
                "{{ element.id }}": [
                    {% for point_controle in element.points_controle.all %}
                    {
                        id: "{{ point_controle.id }}",
                        label: "{{ point_controle.point_de_controle|escapejs }}"
                    }{% if not forloop.last %},{% endif %}
                    {% endfor %}
                ]{% if not forloop.last %},{% endif %}
                {% endfor %}
            };
        }

        window.selectElement = function(elementId) {
            if (currentElementId && currentElementId !== elementId) {
                moveCurrentPointsToStorage(currentElementId);
            }
            currentElementId = elementId;
            document.querySelectorAll('.element-item').forEach(item => {
                item.classList.toggle('active', item.dataset.elementId === String(elementId));
            });
            const selectedItem = document.querySelector(`.element-item[data-element-id="${elementId}"]`);
            const elementName = selectedItem ? selectedItem.dataset.elementName || selectedItem.textContent.trim() : 'Élément sélectionné';
            document.getElementById('selected-element-name').innerText = elementName;
            displayPointsControle(elementId);
        };

        function moveCurrentPointsToStorage(elementId) {
            if (!elementId) return;
            const pointsContainer = document.getElementById('points-controle-list');
            const storage = document.getElementById('points-controle-storage');
            if (!pointsContainer || !storage) return;

            let storageSlot = document.getElementById(`stored-points-${elementId}`);
            if (!storageSlot) {
                storageSlot = document.createElement('div');
                storageSlot.id = `stored-points-${elementId}`;
                storageSlot.style.display = 'none';
                storage.appendChild(storageSlot);
            }

            while (pointsContainer.firstChild) {
                storageSlot.appendChild(pointsContainer.firstChild);
            }
        }

        function displayPointsControle(elementId) {
            const pointsContainer = document.getElementById('points-controle-list');
            const noElementMessage = document.getElementById('no-element-selected-message');
            const validateBtn = document.getElementById('validateControles');

            const storage = document.getElementById('points-controle-storage');
            const storedSlot = storage ? document.getElementById(`stored-points-${elementId}`) : null;
            const points = pointsControleByElement[String(elementId)] || [];

            if (storedSlot && storedSlot.children.length) {
                pointsContainer.innerHTML = '';
                while (storedSlot.firstChild) {
                    pointsContainer.appendChild(storedSlot.firstChild);
                }
            } else {
                moveCurrentPointsToStorage();
                pointsContainer.innerHTML = '';
            }

            if (!points.length && (!storedSlot || !storedSlot.children.length)) {
                noElementMessage.style.display = 'block';
                pointsContainer.style.display = 'none';
                validateBtn.style.display = 'none';
                return;
            }

            noElementMessage.style.display = 'none';
            pointsContainer.style.display = 'block';
            validateBtn.style.display = 'inline-flex';

            const savedState = controlesState[String(elementId)] || { points: [] };
            const savedPoints = savedState.points.reduce((acc, item) => {
                acc[item.pointId] = item;
                return acc;
            }, {});

            points.forEach(point => {
                const template = document.getElementById('point-controle-template');
                const pointNode = template.content.cloneNode(true);
                const item = pointNode.querySelector('.point-controle-item');
                item.dataset.pointId = point.id;

                const label = pointNode.querySelector('.point-label');
                const description = pointNode.querySelector('.point-description');
                const statusSelect = pointNode.querySelector('.statut-select');
                const observationField = pointNode.querySelector('.observation-field');
                const observationTextarea = observationField.querySelector('textarea');
                const photoField = pointNode.querySelector('.photo-field');
                const photoInput = photoField ? photoField.querySelector('.photo-input') : null;
                const photoPreview = photoField ? photoField.querySelector('.photo-preview') : null;

                label.textContent = point.label;
                description.textContent = '';

                if (savedPoints[point.id]) {
                    statusSelect.value = savedPoints[point.id].statut;
                    observationTextarea.value = savedPoints[point.id].observation || '';
                    if (['NON_CONFORME', 'SUSPENDU'].includes(savedPoints[point.id].statut)) {
                        observationField.style.display = 'block';
                        observationTextarea.required = true;
                        if (photoField) photoField.style.display = 'block';
                        if (photoInput) photoInput.required = false;
                    }
                }

                statusSelect.addEventListener('change', () => {
                    const photoField = pointNode.querySelector('.photo-field');
                    const photoInput = photoField ? photoField.querySelector('.photo-input') : null;
                    const photoPreview = photoField ? photoField.querySelector('.photo-preview') : null;

                    if (['NON_CONFORME', 'SUSPENDU'].includes(statusSelect.value)) {
                        observationField.style.display = 'block';
                        observationTextarea.required = true;
                        if (photoField) photoField.style.display = 'block';
                        if (photoInput) photoInput.required = false; // optional but available
                    } else {
                        observationField.style.display = 'none';
                        observationTextarea.required = false;
                        observationTextarea.value = '';
                        if (photoField) {
                            photoField.style.display = 'none';
                            if (photoInput) { photoInput.value = ''; }
                            if (photoPreview) { photoPreview.style.display = 'none'; photoPreview.src = ''; }
                        }
                    }
                });

                // Préparer le champ photo (nom dynamique pour POST)
                const photoFieldNode = pointNode.querySelector('.photo-field');
                if (photoFieldNode) {
                    const photoInput = photoFieldNode.querySelector('.photo-input');
                    const photoPreview = photoFieldNode.querySelector('.photo-preview');
                    if (photoInput) {
                        photoInput.name = `controle_${elementId}_${point.id}_photo`;
                        photoInput.addEventListener('change', (e) => {
                            const file = e.target.files && e.target.files[0];
                            if (!file) {
                                photoPreview.style.display = 'none';
                                photoPreview.src = '';
                                return;
                            }
                            const reader = new FileReader();
                            reader.onload = function(evt) {
                                photoPreview.src = evt.target.result;
                                photoPreview.style.display = 'block';
                            };
                            reader.readAsDataURL(file);
                        });
                    }
                }

                pointsContainer.appendChild(pointNode);
            });
        }

        function validateElementControles() {
            if (!currentElementId) {
                showNotification('Veuillez d\'abord sélectionner un élément.', 'warning');
                return false;
            }

            const pointItems = document.querySelectorAll('#points-controle-list .point-controle-item');
            const elementName = document.getElementById('selected-element-name').innerText;
            const points = [];
            let valid = true;

            pointItems.forEach(item => {
                const pointId = item.dataset.pointId;
                const statusSelect = item.querySelector('.statut-select');
                const observationTextarea = item.querySelector('.observation-field textarea');
                const statut = statusSelect.value;
                const observation = observationTextarea ? observationTextarea.value.trim() : '';

                if (!statut) {
                    return;
                }
                if (['NON_CONFORME', 'SUSPENDU'].includes(statut) && !observation) {
                    observationTextarea.classList.add('is-invalid');
                    valid = false;
                } else if (observationTextarea) {
                    observationTextarea.classList.remove('is-invalid');
                }

                points.push({ pointId, statut, observation });
            });

            if (!valid) {
                showNotification('Veuillez ajouter une observation pour chaque point non conforme ou suspendu.', 'warning');
                return false;
            }
            if (!points.length) {
                showNotification('Veuillez sélectionner au moins un statut pour cet élément.', 'warning');
                return false;
            }

            controlesState[String(currentElementId)] = {
                elementName,
                points
            };
            renderHiddenControlInputs();
            updateRecapControles();
            showNotification('Contrôles enregistrés pour cet élément.', 'success');
            return true;
        }

        function renderHiddenControlInputs() {
            const hiddenContainer = document.getElementById('controles-hidden-inputs');
            hiddenContainer.innerHTML = '';

            Object.entries(controlesState).forEach(([elementId, data]) => {
                data.points.forEach(point => {
                    const statutInput = document.createElement('input');
                    statutInput.type = 'hidden';
                    statutInput.name = `controle_${elementId}_${point.pointId}_statut`;
                    statutInput.value = point.statut;
                    hiddenContainer.appendChild(statutInput);

                    const observationInput = document.createElement('input');
                    observationInput.type = 'hidden';
                    observationInput.name = `controle_${elementId}_${point.pointId}_observation`;
                    observationInput.value = point.observation || '';
                    hiddenContainer.appendChild(observationInput);
                });
            });
        }

        function updateRecapControles() {
            let conforme = 0;
            let nonConforme = 0;
            let suspendu = 0;
            let total = 0;

            Object.values(controlesState).forEach(data => {
                data.points.forEach(point => {
                    total += 1;
                    if (point.statut === 'CONFORME') {
                        conforme += 1;
                    } else if (point.statut === 'NON_CONFORME') {
                        nonConforme += 1;
                    } else if (point.statut === 'SUSPENDU') {
                        suspendu += 1;
                    }
                });
            });

            document.getElementById('countConforme').innerText = conforme;
            document.getElementById('countNonConforme').innerText = nonConforme;
            document.getElementById('countSuspendu').innerText = suspendu;
            document.getElementById('countTotal').innerText = total;
        }

        // Initialiser les données et signatures au chargement
        loadPointsControle();
        initializeSignaturePads();

        // Restaurer l'étape affichée si le formulaire a été renvoyé avec des erreurs
        if (currentStep > 1) {
            for (let i = 1; i <= totalSteps; i++) {
                document.getElementById(`step${i}`).style.display = (i === currentStep ? 'block' : 'none');
            }
            updateUI();
        }
    });
</script>

<style>
    /* Styles supplémentaires */
    .required:after {
        content: " *";
        color: #dc3545;
    }
    
    .is-invalid {
        border-color: #dc3545 !important;
    }
    
    .is-invalid:focus {
        box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
    }
    
    .signature-pad-wrapper {
        position: relative;
        background: #fff;
        cursor: crosshair;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
    }
    
    .signature-pad {
        display: block;
        touch-action: none;
        user-select: none;
        width: 100%;
        height: 150px;
    }
    
    .participant-item {
        transition: all 0.3s ease;
    }
    
    .participant-item:hover {
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }
    
    .element-item {
        transition: all 0.2s ease;
        border-left: 3px solid transparent;
    }
    
    .element-item:hover {
        background-color: #f8f9fa;
    }
    
    .element-item.active {
        border-left-color: #0d6efd;
        background-color: #e7f1ff;
    }
    
    .point-controle-item {
        background-color: #fff;
        transition: all 0.2s ease;
    }
    
    .point-controle-item:hover {
        background-color: #f8f9fa;
    }
    
    .observation-field {
        animation: slideDown 0.3s ease;
    }
    
    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .btn:disabled {
        cursor: not-allowed;
        opacity: 0.6;
    }
    
    @media (max-width: 768px) {
        .signature-pad {
            height: 150px;
        }
        
        .col-md-5, .col-md-7 {
            margin-bottom: 1rem;
        }
    }
</style>
{% endblock %}