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

{% block title %}Liste des procès-verbaux - Contrôle Technique{% endblock %}

{% block content %}


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

    <div class="navbar-nav-right d-flex align-items-center justify-content-end" id="navbar-collapse">
        <!-- Titre de la section -->
        <div class="navbar-nav align-items-center me-auto">
            <div class="nav-item d-flex align-items-center">
                <span class="w-px-22 h-px-22"><i class="icon-base bx bx-file-find icon-md"></i></span>
                <h4>Gestion : Liste des procès-verbaux</h4>
            </div>
        </div>

        <!-- Boutons d'action -->
        <ul class="navbar-nav flex-row align-items-center ms-md-auto">
            <a href="{% url 'controle:creer_pv' %}" class="btn btn-success btn-sm me-2">
                <i class="fa fa-plus"></i> Nouveau PV
            </a>
            <button type="button" class="btn btn-info btn-sm me-2" data-bs-toggle="modal" data-bs-target="#filtresModal">
                <i class="fa fa-filter"></i> Filtres
            </button>
             <a href="#" class="btn btn-secondary btn-sm me-2"> 
                <i class="fa fa-download"></i> Exporter
            </a>
            <li class="nav-item lh-1 me-4">
                <span>...</span>
            </li>
        </ul>
    </div>
</nav> 

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

    <!-- Barre de recherche rapide -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-4">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fa fa-search"></i></span>
                                <input type="text" class="form-control" name="search" placeholder="Rechercher par client, lieu, objet..." value="{{ request.GET.search|default:'' }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-info w-100">
                                <i class="fa fa-search me-1"></i>Rechercher
                            </button>
                        </div>
                        <div class="col-md-2">
                            <a href="{% url 'controle:liste_pv' %}" class="btn btn-secondary w-100">
                                <i class="fa fa-undo me-1"></i>Réinitialiser
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Liste des PVs -->
    <div class="row">   
        <div class="col-xxl-12 mb-6 order-0">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Procès-verbaux de contrôle</h5>
                    <span class="badge bg-danger">Total : {{ pvs|length }} PV(s)</span>
                </div>
                
                <div class="table-responsive text-nowrap">
                    <table class="table table-striped table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>N° PV</th>
                                <th>Type</th>
                                <th>Client</th>
                                <th>Date visite</th>
                                <th>Lieu</th>
                                <th>Participants</th>
                                <th>Contrôles</th>
                                <th>Statut</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody class="table-border-bottom-0">
                            {% for pv in pvs %}   
                            <tr>
                                <td>
                                    <strong>PV-{{ pv.id|stringformat:"04d" }}</strong>
                                </td>
                                <td>
                                    <span class="badge bg-info">{{ pv.type_pv.code }}</span>
                                    <small class="d-block text-muted">{{ pv.type_pv.libelle|truncatechars:20 }}</small>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <i class="fa fa-user-circle me-2 text-primary"></i>
                                        <div>
                                            <strong>{{ pv.client.nom }}</strong>
                                            <small class="d-block text-muted">{{ pv.client.email|default:"-" }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div>
                                        <i class="fa fa-calendar me-1 text-muted"></i>
                                        {{ pv.date_visite|date:"d/m/Y" }}
                                    </div>
                                    <small class="text-muted">
                                        <i class="fa fa-clock me-1"></i>
                                        {{ pv.date_visite|date:"H:i" }}
                                    </small>
                                </td>
                                <td>
                                    <i class="fa fa-map-marker-alt me-1 text-danger"></i>
                                    {{ pv.lieu|truncatechars:30 }}
                                </td>
                                <td class="text-center">
                                    {% with count=pv.participants.count %}
                                    <span class="badge bg-{% if count > 0 %}success{% else %}secondary{% endif %}">
                                        <i class="fa fa-users me-1"></i>{{ count }}
                                    </span>
                                    {% endwith %}
                                </td>
                                <td class="text-center">
                                    {% with count=pv.controles.count %}
                                    <span class="badge bg-{% if count > 0 %}success{% else %}warning{% endif %}">
                                        <i class="fa fa-clipboard-check me-1"></i>{{ count }}
                                    </span>
                                    {% endwith %}
                                </td>
                                <td>
                                    {% if pv.statut == 'brouillon' %}
                                        <span class="badge bg-secondary">Brouillon</span>
                                    {% elif pv.statut == 'signe' %}
                                        <span class="badge bg-success">Signé</span>
                                    {% elif pv.statut == 'envouye' %}
                                        <span class="badge bg-info">Envoyé</span>
                                    {% elif pv.statut == 'archive' %}
                                        <span class="badge bg-dark">Archivé</span>
                                    {% else %}
                                        <span class="badge bg-warning">{{ pv.statut }}</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <!-- Visualiser -->
                                        <a href="{% url 'controle:visualiser_pv' pv.id %}" class="btn btn-icon btn-info" title="Visualiser">
                                            <span class="icon-base bx bx-show icon-md"></span>
                                        </a>
                                        
                                        <!-- Modifier -->
                                        <a href="{% url 'controle:modifier_pv' pv.id %}" class="btn btn-icon btn-warning" title="Modifier">
                                            <span class="icon-base bx bx-edit-alt icon-md"></span>
                                        </a>
                                        
                                        <!-- Dupliquer 
                                        <button type="button" class="btn btn-icon btn-secondary" title="Dupliquer" 
                                                onclick="dupliquerPV({{ pv.id }})">
                                            <span class="icon-base bx bx-copy icon-md"></span>
                                        </button>-->
                                        
                                        <!-- Signature -->
                                        {% if pv.statut == 'BROUILLON' %}
                                        <a href="{% url 'controle:signer_pv' pv.id %}" class="btn btn-icon btn-success" title="Signer">
                                            <span class="icon-base bx bx-pen icon-md"></span>
                                        </a>
                                        {% endif %}
                                        
                                        <!-- Plus d'options -->
                                        <div class="btn-group">
                                            <button type="button" class="btn btn-icon btn-danger dropdown-toggle" 
                                                    data-bs-toggle="dropdown" aria-expanded="false">
                                                <span class="icon-base bx bx-dots-vertical-rounded icon-md"></span>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <li>
                                                    <a class="dropdown-item" href="{% url 'controle:imprimer_pv' pv.id %}">
                                                        <i class="fa fa-print me-2"></i>Imprimer
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item" href="{% url 'controle:exporter_pv_pdf' pv.id %}">
                                                        <i class="fa fa-file-pdf me-2"></i>Exporter en PDF
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item" href="{% url 'controle:envoyer_pv_email' pv.id %}">
                                                        <i class="fa fa-envelope me-2"></i>Envoyer par email
                                                    </a>
                                                </li>
                                                <li><hr class="dropdown-divider"></li>
                                                <li>
                                                    <a class="dropdown-item text-danger" href="{% url 'controle:supprimer_pv' pv.id %}" 
                                                       onclick="confirmerSuppression({{ pv.id }})">
                                                        <i class="fa fa-trash me-2"></i>Supprimer
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="9" class="text-center py-5">
                                    <i class="fa fa-file-alt fa-4x text-muted mb-3"></i>
                                    <h5 class="text-muted">Aucun procès-verbal trouvé</h5>
                                    <p class="text-muted mb-3">Commencez par créer votre premier procès-verbal</p>
                                    <a href="{% url 'controle:creer_pv' %}" class="btn btn-success">
                                        <i class="fa fa-plus me-1"></i>Créer un PV
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                
                <!-- Pied de tableau avec pagination -->
                <div class="card-footer d-flex justify-content-between align-items-center">
                    <div class="text-muted">
                        <small>Affichage de {{ pvs.start_index|default:0 }} à {{ pvs.end_index|default:0 }} sur {{ pvs.paginator.count|default:0 }} PV(s)</small>
                    </div>
                    
                    {% if pvs.has_other_pages %}
                    <nav aria-label="Navigation des pages">
                        <ul class="pagination pagination-sm mb-0">
                            {% if pvs.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ pvs.previous_page_number }}{% if request.GET.search %}&search={{ request.GET.search }}{% endif %}{% if request.GET.type %}&type={{ request.GET.type }}{% endif %}{% if request.GET.statut %}&statut={{ request.GET.statut }}{% endif %}{% if request.GET.date_debut %}&date_debut={{ request.GET.date_debut }}{% endif %}{% if request.GET.date_fin %}&date_fin={{ request.GET.date_fin }}{% endif %}">
                                    <i class="fa fa-chevron-left"></i>
                                </a>
                            </li>
                            {% endif %}

                            {% for i in pvs.paginator.page_range %}
                                {% if pvs.number == i %}
                                <li class="page-item active">
                                    <span class="page-link">{{ i }}</span>
                                </li>
                                {% elif i > pvs.number|add:'-3' and i < pvs.number|add:'3' %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ i }}{% if request.GET.search %}&search={{ request.GET.search }}{% endif %}{% if request.GET.type %}&type={{ request.GET.type }}{% endif %}{% if request.GET.statut %}&statut={{ request.GET.statut }}{% endif %}{% if request.GET.date_debut %}&date_debut={{ request.GET.date_debut }}{% endif %}{% if request.GET.date_fin %}&date_fin={{ request.GET.date_fin }}{% endif %}">
                                        {{ i }}
                                    </a>
                                </li>
                                {% endif %}
                            {% endfor %}

                            {% if pvs.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ pvs.next_page_number }}{% if request.GET.search %}&search={{ request.GET.search }}{% endif %}{% if request.GET.type %}&type={{ request.GET.type }}{% endif %}{% if request.GET.statut %}&statut={{ request.GET.statut }}{% endif %}{% if request.GET.date_debut %}&date_debut={{ request.GET.date_debut }}{% endif %}{% if request.GET.date_fin %}&date_fin={{ request.GET.date_fin }}{% endif %}">
                                    <i class="fa fa-chevron-right"></i>
                                </a>
                            </li>
                            {% endif %}
                        </ul>
                    </nav>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal des filtres avancés -->
<div class="modal fade" id="filtresModal" tabindex="-1" aria-labelledby="filtresModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title" id="filtresModalLabel">
                    <i class="fa fa-filter me-2"></i>Filtres avancés
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
            </div>
            <form method="GET" action="{% url 'controle:liste_pv' %}">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="type" class="form-label">Type de PV</label>
                            <select class="form-select" id="type" name="type">
                                <option value="">Tous les types</option>
                                {% for type in types_pv %}
                                <option value="{{ type.id }}" {% if request.GET.type == type.id|stringformat:"s" %}selected{% endif %}>
                                    {{ type.code }} - {{ type.libelle }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="statut" class="form-label">Statut</label>
                            <select class="form-select" id="statut" name="statut">
                                <option value="">Tous les statuts</option>
                                <option value="BROUILLON" {% if request.GET.statut == 'BROUILLON' %}selected{% endif %}>Brouillon</option>
                                <option value="SIGNE" {% if request.GET.statut == 'SIGNE' %}selected{% endif %}>Signé</option>
                                <option value="ENVOYE" {% if request.GET.statut == 'ENVOYE' %}selected{% endif %}>Envoyé</option>
                                <option value="ARCHIVE" {% if request.GET.statut == 'ARCHIVE' %}selected{% endif %}>Archivé</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="client" class="form-label">Client</label>
                            <select class="form-select" id="client" name="client">
                                <option value="">Tous les clients</option>
                                {% for client in clients %}
                                <option value="{{ client.id }}" {% if request.GET.client == client.id|stringformat:"s" %}selected{% endif %}>
                                    {{ client.nom }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="lieu" class="form-label">Lieu</label>
                            <input type="text" class="form-control" id="lieu" name="lieu" value="{{ request.GET.lieu|default:'' }}" placeholder="Ex: Dakar, Thiès...">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="date_debut" class="form-label">Date début</label>
                            <input type="date" class="form-control" id="date_debut" name="date_debut" value="{{ request.GET.date_debut|default:'' }}">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="date_fin" class="form-label">Date fin</label>
                            <input type="date" class="form-control" id="date_fin" name="date_fin" value="{{ request.GET.date_fin|default:'' }}">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fa fa-times me-1"></i>Annuler
                    </button>
                    <button type="submit" class="btn btn-info">
                        <i class="fa fa-filter me-1"></i>Appliquer les filtres
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal de confirmation de suppression -->
<div class="modal fade" id="supprimerModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fa fa-exclamation-triangle me-2"></i>Confirmation
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
            </div>
            <div class="modal-body">
                <p>Êtes-vous sûr de vouloir supprimer ce procès-verbal ?</p>
                <p class="text-danger"><small>Cette action est irréversible.</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fa fa-times me-1"></i>Annuler
                </button>
                <form id="deleteForm" method="POST" style="display: inline;">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-danger">
                        <i class="fa fa-trash me-1"></i>Supprimer
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

{% endblock %}

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

<script>
    // Attendre que le DOM soit chargé
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM chargé - Initialisation');
        
        // Vérifier la disponibilité de Bootstrap
        if (typeof bootstrap !== 'undefined') {
            // Auto-fermeture des alertes après 5 secondes
            setTimeout(function() {
                document.querySelectorAll('.alert').forEach(function(alert) {
                    try {
                        var bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    } catch(e) {
                        console.error('Erreur lors de la fermeture de l\'alerte:', e);
                    }
                });
            }, 5000);
        }
    });

    // Fonction pour dupliquer un PV
    function dupliquerPV(pvId) {
        if (confirm('Voulez-vous créer une copie de ce procès-verbal ?')) {
            window.location.href = '/pv/dupliquer/' + pvId + '/';
        }
    }

    // Fonction pour confirmer la suppression
    function confirmerSuppression(pvId) {
        var modal = new bootstrap.Modal(document.getElementById('supprimerModal'));
        var deleteForm = document.getElementById('deleteForm');
        deleteForm.action = '/pv/supprimer/' + pvId + '/';
        modal.show();
    }

    // Version jQuery si disponible
    if (typeof $ !== 'undefined') {
        $(document).ready(function() {
            // Initialisation des tooltips
            $('[title]').tooltip();
            
            // Gestionnaire pour les dropdowns
            $('.dropdown-toggle').dropdown();
        });
    }
</script>
{% endblock %}