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

{% block title %}PVs du client - {{ client.nom }} - Contrôle Technique{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- Fil d'Ariane -->
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item">
                <a href="{% url 'controle:liste_clients' %}">
                    <i class="icon-base bx bx-group me-1"></i>Clients
                </a>
            </li>
            <li class="breadcrumb-item active" aria-current="page">
                PVs de {{ client.nom }}
            </li>
        </ol>
    </nav>

    <!-- En-tête avec informations client -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card bg-gradient-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h2 class="text-white mb-2">
                                <i class="icon-base bx bxs-building-house me-2"></i>
                                {{ client.nom }}
                            </h2>
                            <p class="mb-1">
                                <i class="icon-base bx bx-map me-1"></i>
                                {{ client.adresse|default:"Adresse non renseignée" }}
                                {% if client.ville %}, {{ client.ville }} {{ client.code_postal }}{% endif %}
                            </p>
                            <p class="mb-0">
                                {% if client.email %}
                                <i class="icon-base bx bx-envelope me-1"></i>
                                <a href="mailto:{{ client.email }}" class="text-white">{{ client.email }}</a>
                                {% endif %}
                                {% if client.telephone %}
                                <span class="mx-2">|</span>
                                <i class="icon-base bx bx-phone me-1"></i>
                                <a href="tel:{{ client.telephone }}" class="text-white">{{ client.telephone }}</a>
                                {% endif %}
                            </p>
                        </div>
                        <div class="text-end">
                            <span class="badge bg-white text-primary fs-6 p-3">
                                <i class="icon-base bx bx-file me-1"></i>
                                Total: {{ pvs|length }} PV(s)
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistiques rapides -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <span class="fw-semibold d-block mb-1">PVs finaux</span>
                            <h3 class="card-title mb-0">{{ stats.pvs_finaux|default:0 }}</h3>
                        </div>
                        <div class="avatar avatar-lg">
                            <span class="avatar-initial bg-success rounded-circle">
                                <i class="icon-base bx bx-check-circle fs-2"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <span class="fw-semibold d-block mb-1">Brouillons</span>
                            <h3 class="card-title mb-0">{{ stats.pvs_brouillon|default:0 }}</h3>
                        </div>
                        <div class="avatar avatar-lg">
                            <span class="avatar-initial bg-warning rounded-circle">
                                <i class="icon-base bx bx-file fs-2"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <span class="fw-semibold d-block mb-1">Cette année</span>
                            <h3 class="card-title mb-0">{{ stats.pvs_annee|default:0 }}</h3>
                        </div>
                        <div class="avatar avatar-lg">
                            <span class="avatar-initial bg-info rounded-circle">
                                <i class="icon-base bx bx-calendar fs-2"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <span class="fw-semibold d-block mb-1">Dernier PV</span>
                            <h6 class="card-title mb-0">
                                {% with dernier=dernier_pv %}
                                    {% if dernier %}
                                        {{ dernier.date_visite|date:"d/m/Y" }}
                                    {% else %}
                                        -
                                    {% endif %}
                                {% endwith %}
                            </h6>
                        </div>
                        <div class="avatar avatar-lg">
                            <span class="avatar-initial bg-primary rounded-circle">
                                <i class="icon-base bx bx-time fs-2"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

    <!-- Filtres et recherche -->
    <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-3">
                            <label for="search" class="form-label">Rechercher</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fa fa-search"></i></span>
                                <input type="text" class="form-control" id="search" name="search" 
                                       placeholder="N° PV, objet..." value="{{ request.GET.search|default:'' }}">
                            </div>
                        </div>
                        
                        <div class="col-md-2">
                            <label for="type_pv" class="form-label">Type de PV</label>
                            <select name="type_pv" id="type_pv" class="form-select">
                                <option value="">Tous les types</option>
                                {% for type in types_pv %}
                                <option value="{{ type.id }}" {% if request.GET.type_pv == type.id|stringformat:"s" %}selected{% endif %}>
                                    {{ type.nom }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <div class="col-md-2">
                            <label for="statut" class="form-label">Statut</label>
                            <select name="statut" id="statut" class="form-select">
                                <option value="">Tous les statuts</option>
                                <option value="brouillon" {% if request.GET.statut == 'brouillon' %}selected{% endif %}>Brouillon</option>
                                <option value="final" {% if request.GET.statut == 'final' %}selected{% endif %}>Final</option>
                            </select>
                        </div>
                        
                        <div class="col-md-2">
                            <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-2">
                            <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 class="col-md-1 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fa fa-filter"></i>
                            </button>
                        </div>
                        
                        <div class="col-12 text-end">
                            <a href="{% url 'controle:liste_pv_client' client.id %}" class="btn btn-secondary btn-sm">
                                <i class="fa fa-undo me-1"></i>Réinitialiser les filtres
                            </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">
                <h5 class="card-header d-flex justify-content-between align-items-center">
                    <span>
                        <i class="icon-base bx bx-file me-2"></i>
                        Procès-verbaux de {{ client.nom }}
                    </span>
                    <div>
                        <a href="{% url 'controle:creer_pv' %}?client={{ client.id }}" class="btn btn-success btn-sm me-2">
                            <i class="fa fa-plus me-1"></i>Nouveau PV
                        </a>
                        <button class="btn btn-info btn-sm" onclick="exportToExcel()">
                            <i class="fa fa-file-excel me-1"></i>Exporter
                        </button>
                    </div>
                </h5>
                
                <div class="table-responsive text-nowrap">
                    <table class="table table-striped table-hover" id="pvsTable">
                        <thead>
                            <tr>
                                <th>N° PV</th>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Objet du contrôle</th>
                                <th>Lieu</th>
                                <th>Statut</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody class="table-border-bottom-0">
                            {% for pv in pvs %}
                            <tr>
                                <td>
                                    <span class="badge bg-secondary">#{{ pv.numero }}</span>
                                </td>
                                <td>
                                    <strong>{{ pv.date_visite|date:"d/m/Y" }}</strong>
                                    <small class="text-muted d-block">{{ pv.date_visite|date:"H:i" }}</small>
                                </td>
                                <td>
                                    <span class="badge bg-info">{{ pv.type_pv.nom|default:"-" }}</span>
                                </td>
                                <td>
                                    {{ pv.objet_controle.nom_projet|truncatechars:50 }}
                                </td>
                                <td>
                                    <i class="icon-base bx bx-map me-1"></i>
                                    {{ pv.lieu|truncatechars:30|default:"-" }}
                                </td>
                                <td>
                                    {% if pv.statut == 'final' %}
                                    <span class="badge bg-success">Final</span>
                                    {% else %}
                                    <span class="badge bg-warning">Brouillon</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <!-- Voir détail -->
                                        <a href="{% url 'controle:detail_pv' pv.id %}" class="btn btn-icon btn-info" title="Détails">
                                            <span class="icon-base bx bx-show-alt 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>
                                        
                                        <!-- Générer PDF -->
                                        <a href="{% url 'controle:generer_pdf' pv.id %}" class="btn btn-icon btn-primary" title="PDF" target="_blank">
                                            <span class="icon-base bx bx-file-pdf icon-md"></span>
                                        </a>
                                        
                                        <!-- Envoyer par email -->
                                        <button type="button" class="btn btn-icon btn-secondary" 
                                                onclick="envoyerPV({{ pv.id }})" title="Envoyer par email">
                                            <span class="icon-base bx bx-envelope icon-md"></span>
                                        </button>
                                        
                                        <!-- Dupliquer -->
                                        <button type="button" class="btn btn-icon btn-success" 
                                                onclick="dupliquerPV({{ pv.id }})" title="Dupliquer">
                                            <span class="icon-base bx bx-copy icon-md"></span>
                                        </button>
                                        
                                        <!-- Supprimer -->
                                        <button type="button" class="btn btn-icon btn-danger" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#supprimerPVModal{{ pv.id }}" title="Supprimer">
                                            <span class="icon-base bx bx-trash-alt icon-md"></span>
                                        </button>
                                    </div>
                                </td>
                            </tr>

                            <!-- Modal de suppression PV -->
                            <div class="modal fade" id="supprimerPVModal{{ pv.id }}" tabindex="-1"
                                 aria-labelledby="supprimerPVModalLabel{{ pv.id }}" aria-hidden="true">
                                <div class="modal-dialog modal-sm">
                                    <div class="modal-content">
                                        <div class="modal-header bg-danger text-white">
                                            <h5 class="modal-title" id="supprimerPVModalLabel{{ pv.id }}">
                                                <i class="fa fa-exclamation-triangle me-2"></i>Confirmation
                                            </h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
                                        </div>
                                        <div class="modal-body">
                                            <p>Êtes-vous sûr de vouloir supprimer le PV :</p>
                                            <p class="fw-bold text-center">#{{ pv.numero }} - {{ pv.objet_controle.nom_projet|truncatechars:50 }}</p>
                                            <p class="text-danger"><small>Cette action est irréversible.</small></p>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                                <i class="fa fa-times me-1"></i>Annuler
                                            </button>
                                            <form method="POST" action="{% url 'controle:supprimer_pv' pv.id %}">
                                                {% csrf_token %}
                                                <button type="submit" class="btn btn-danger">
                                                    <i class="fa fa-trash me-1"></i>Supprimer
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% empty %}
                            <tr>
                                <td colspan="7" class="text-center py-5">
                                    <i class="fa fa-file-alt fa-4x text-muted mb-3"></i>
                                    <p class="text-muted fs-5">Aucun procès-verbal trouvé pour ce client</p>
                                    <a href="{% url 'controle:creer_pv' %}?client={{ client.id }}" class="btn btn-success">
                                        <i class="fa fa-plus me-1"></i>Créer un premier PV
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

                <!-- Pied de tableau avec pagination -->
                {% if pvs.has_other_pages %}
                <div class="card-footer d-flex justify-content-between align-items-center">
                    <div class="text-muted">
                        <small>Affichage de {{ pvs.start_index }} à {{ pvs.end_index }} sur {{ pvs.paginator.count }} PV(s)</small>
                    </div>
                    
                    <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_pv %}&type_pv={{ request.GET.type_pv }}{% 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_pv %}&type_pv={{ request.GET.type_pv }}{% 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_pv %}&type_pv={{ request.GET.type_pv }}{% 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>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Modal d'envoi par email -->
<div class="modal fade" id="emailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="icon-base bx bx-envelope me-2"></i>Envoyer le PV par email
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
            </div>
            <form id="emailForm" method="POST" action="">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="destinataire" class="form-label">Destinataire <span class="text-danger">*</span></label>
                        <input type="email" class="form-control" id="destinataire" name="destinataire" 
                               value="{{ client.email|default:'' }}" required>
                        <small class="text-muted">Adresse email du destinataire</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="sujet" class="form-label">Sujet</label>
                        <input type="text" class="form-control" id="sujet" name="sujet" 
                               value="Procès-verbal de contrôle technique">
                    </div>
                    
                    <div class="mb-3">
                        <label for="message" class="form-label">Message</label>
                        <textarea class="form-control" id="message" name="message" rows="4">Bonjour,

Veuillez trouver ci-joint le procès-verbal de contrôle technique.

Cordialement,
L'équipe de contrôle</textarea>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle me-2"></i>
                        Le PV sera joint au format PDF.
                    </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-primary">
                        <i class="fa fa-paper-plane me-1"></i>Envoyer
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

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

<!-- DataTables CSS (optionnel pour améliorer les tableaux) -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css">

<style>
/* Style pour l'en-tête dégradé */
.bg-gradient-primary {
    background: linear-gradient(45deg, #0d6efd, #0a58ca);
}

/* Style pour les avatars */
.avatar-lg {
    width: 60px;
    height: 60px;
}
.avatar-initial {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
}

/* Animation au survol des boutons */
.btn-group .btn {
    transition: transform 0.2s;
}
.btn-group .btn:hover {
    transform: translateY(-2px);
    z-index: 10;
}

/* Style pour les cartes de statistiques */
.card .avatar {
    transition: transform 0.3s;
}
.card:hover .avatar {
    transform: scale(1.1);
}
</style>

<script>
    let pvIdToSend = null;

    function envoyerPV(pvId) {
        pvIdToSend = pvId;
        const form = document.getElementById('emailForm');
        form.action = `/pv/${pvId}/email/`;  // Adaptez selon votre URL
        
        const modal = new bootstrap.Modal(document.getElementById('emailModal'));
        modal.show();
    }

    function dupliquerPV(pvId) {
        if (confirm('Voulez-vous dupliquer ce procès-verbal ?')) {
            window.location.href = `/pv/${pvId}/dupliquer/`;  // Adaptez selon votre URL
        }
    }

    function exportToExcel() {
        // Récupérer les données du tableau
        const table = document.getElementById('pvsTable');
        const rows = table.querySelectorAll('tr');
        const csvData = [];
        
        // Parcourir les lignes
        rows.forEach(row => {
            const rowData = [];
            const cols = row.querySelectorAll('td, th');
            cols.forEach((col, index) => {
                // Exclure la colonne des actions (dernière colonne)
                if (index < cols.length - 1) {
                    rowData.push(col.innerText.trim());
                }
            });
            csvData.push(rowData.join(','));
        });
        
        // Créer et télécharger le fichier CSV
        const csvContent = csvData.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.href = url;
        link.setAttribute('download', 'pvs_{{ client.nom|slugify }}.csv');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    document.addEventListener('DOMContentLoaded', function() {
        // 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);

        // Initialisation de DataTables (optionnel)
        if (typeof $.fn.DataTable !== 'undefined') {
            $('#pvsTable').DataTable({
                paging: false,
                searching: false,
                ordering: true,
                info: false,
                language: {
                    url: '//cdn.datatables.net/plug-ins/1.11.5/i18n/fr-FR.json'
                }
            });
        }

        // Validation du formulaire email
        document.getElementById('emailForm')?.addEventListener('submit', function(e) {
            const email = document.getElementById('destinataire').value;
            if (!email || !email.includes('@')) {
                e.preventDefault();
                alert('Veuillez saisir une adresse email valide');
            }
        });
    });
</script>

<!-- DataTables JS (optionnel) -->
{% if debug %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
{% endif %}
{% endblock %}