{% extends "base.html" %}
{% block title %}{{ contract.name }} - Contrat GMAO{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-start mb-3">
        <div>
            <h2 class="h4"><i class="bi bi-file-earmark-text"></i> {{ contract.name }}</h2>
            {% if contract.contract_number %}<span class="text-muted">N° {{ contract.contract_number }}</span>{% endif %}
        </div>
        <div class="d-flex gap-2">
            <a href="{{ url_for('contracts.edit', id=contract.id) }}" class="btn btn-outline-primary btn-sm">
                <i class="bi bi-pencil"></i> Modifier
            </a>
            <form method="POST" action="{{ url_for('contracts.delete', id=contract.id) }}" onsubmit="return confirm('Supprimer ce contrat ?')">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <button type="submit" class="btn btn-outline-danger btn-sm">
                    <i class="bi bi-trash"></i> Supprimer
                </button>
            </form>
        </div>
    </div>

    <div class="alert alert-{{ contract.status_color }}">
        <strong>Statut : {{ contract.status }}</strong>
        {% if contract.is_active %} — Contrat actif{% endif %}
        {% if contract.is_expiring_soon %} — Expire dans {{ contract.days_until_expiry }} jours{% endif %}
        {% if contract.must_send_notice_now %}
         — <strong>Preavis a envoyer avant le {{ contract.notice_deadline_calculated.strftime('%d/%m/%Y') }}</strong>
        {% endif %}
    </div>

    <div class="row g-3">
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h6><i class="bi bi-building text-success"></i> Entreprise</h6>
                    {% if contract.company %}
                    <a href="{{ url_for('companies.detail', id=contract.company.id) }}"><strong>{{ contract.company.name }}</strong></a>
                    {% else %}—{% endif %}
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h6><i class="bi bi-box text-info"></i> Lot / Equipement</h6>
                    {% if contract.lot %}<span class="badge bg-info">Lot: {{ contract.lot.name }}</span>{% endif %}
                    {% if contract.equipment %}<span class="badge bg-secondary">{{ contract.equipment.name }}</span>{% endif %}
                    {% if not contract.lot and not contract.equipment %}—{% endif %}
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mt-3">
        <div class="card-body">
            <h6><i class="bi bi-shield-check text-success"></i> Maintenance couverte par ce contrat</h6>
            {% if covered_tasks %}
            <div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Tâche / lot</th><th>Périodicité</th><th>Équipements / périmètre</th><th>Échéances</th></tr></thead><tbody>
            {% for task in covered_tasks %}<tr><td><strong>{{ task.tache or 'Tâche sans nom' }}</strong><div class="small text-muted">{{ task.lot.name if task.lot else 'Lot non défini' }}</div></td><td>{{ task.periodicite or (task.jours_entre_interventions|string + ' jours' if task.jours_entre_interventions else 'À définir') }}</td><td>{% if task.scope_mode == 'manual' %}Sélection manuelle ({{ task.equipment_scope|length }}){% else %}Équipements actifs du lot{% endif %}</td><td>{% set occurrences = covered_occurrences|selectattr('lot_task_id','equalto',task.id)|list %}{{ occurrences|length }} occurrence(s){% if occurrences %}<div class="small text-muted">Dernière : {{ occurrences[0].scheduled_date.strftime('%d/%m/%Y') if occurrences[0].scheduled_date else '—' }}</div>{% endif %}</td></tr>{% endfor %}
            </tbody></table></div>
            {% else %}<p class="text-muted mb-0">Aucune tâche préventive n'est encore rattachée à ce contrat.</p>{% endif %}
        </div>
    </div>

    <div class="card border-0 shadow-sm mt-3">
        <div class="card-header d-flex justify-content-between"><span><i class="bi bi-calendar-check"></i> Visites du prestataire</span>
            <form method="post" action="{{ url_for('contracts.generate_visits', id=contract.id) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="btn btn-sm btn-outline-primary">Générer sur 12 mois</button></form>
        </div>
        <div class="card-body border-bottom"><form method="post" action="{{ url_for('contracts.create_visit', id=contract.id) }}" class="row g-2 align-items-end"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><div class="col-md-2"><label class="form-label">Date prévue</label><input required type="date" name="scheduled_date" class="form-control"></div><div class="col-md-2"><label class="form-label">Mode</label><select name="passage_mode" class="form-select"><option value="appointment">Sur rendez-vous</option><option value="date_only">Date connue, heure inconnue</option><option value="open_window">Passage libre / sans rendez-vous</option></select></div><div class="col-md-2"><label class="form-label">Début</label><input type="time" name="start_time" class="form-control"></div><div class="col-md-2"><label class="form-label">Fin</label><input type="time" name="end_time" class="form-control"></div><div class="col-md-2"><label class="form-label">Fin de fenêtre</label><input type="date" name="window_end" class="form-control"></div><div class="col-md-2"><label class="form-label">Accompagnement</label><select name="accompaniment_mode" class="form-select"><option value="none">Aucun</option><option value="punctual">Ponctuel</option><option value="full">Complet</option></select></div><div class="col-md-2"><label class="form-label">Temps technicien (min)</label><input type="number" min="0" name="accompaniment_minutes" class="form-control"></div><div class="col-12"><button class="btn btn-primary btn-sm">Ajouter un passage</button><a class="btn btn-outline-secondary btn-sm ms-2" href="{{ url_for('contracts.visits_dashboard') }}">Passages &amp; contrôles</a></div></form></div><div class="table-responsive"><table class="table table-sm mb-0"><thead><tr><th>Date / fenêtre</th><th>Mode</th><th>Statut</th><th>Compte rendu</th><th></th></tr></thead><tbody>
        {% for visit in contract.visits %}<tr><td>{{ visit.scheduled_date.strftime('%d/%m/%Y') }}{% if visit.window_end %} → {{ visit.window_end.strftime('%d/%m/%Y') }}{% endif %}{% if visit.start_time %}<div class="small text-muted">{{ visit.start_time.strftime('%H:%M') }}{% if visit.end_time %}–{{ visit.end_time.strftime('%H:%M') }}{% endif %}</div>{% endif %}</td><td>{{ visit.display_mode }}{% if visit.accompaniment_mode != 'none' %}<div class="small">Accompagnement : {{ visit.accompaniment_minutes or ('toute la durée' if visit.accompaniment_mode == 'full' else 'à définir') }}</div>{% endif %}</td><td><span class="badge bg-{{ 'success' if visit.status == 'realisee' else ('warning text-dark' if visit.status == 'non_venue' else 'primary') }}">{{ visit.status|replace('_',' ') }}</span></td><td>{{ visit.report or '—' }}</td><td>{% if visit.status == 'passage_libre' %}<form method="post" action="{{ url_for('contracts.arrived_visit', id=contract.id, visit_id=visit.id) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="btn btn-sm btn-outline-primary">Entreprise arrivée</button></form>{% elif visit.status not in ('realisee','non_venue') %}<form method="post" action="{{ url_for('contracts.complete_visit', id=contract.id, visit_id=visit.id) }}" class="d-flex gap-1 mb-1"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input name="report" class="form-control form-control-sm" placeholder="Compte rendu"><button class="btn btn-sm btn-success">Réalisée</button></form><form method="post" action="{{ url_for('contracts.no_show_visit', id=contract.id, visit_id=visit.id) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="btn btn-sm btn-outline-warning">Non venue</button></form>{% endif %}</td></tr>
        {% else %}<tr><td colspan="4" class="text-center text-muted">Aucune visite générée</td></tr>{% endfor %}
        </tbody></table></div>
    </div>

    <div class="card border-0 shadow-sm mt-3">
        <div class="card-body">
            <h6><i class="bi bi-calendar3 text-primary"></i> Dates</h6>
            <table class="table table-sm table-borderless">
                <tr><td class="text-muted" style="width:30%">Signe le</td><td>{{ contract.signed_date.strftime('%d/%m/%Y') if contract.signed_date else '—' }}</td></tr>
                <tr><td class="text-muted">Date de debut</td><td><strong>{{ contract.start_date.strftime('%d/%m/%Y') if contract.start_date else '—' }}</strong></td></tr>
                <tr><td class="text-muted">Date de fin</td><td>
                    {% if contract.end_date %}
                    <strong>{{ contract.end_date.strftime('%d/%m/%Y') }}</strong>
                    {% if contract.days_until_expiry is not none %}
                        {% if contract.days_until_expiry < 0 %}<span class="badge bg-danger">Expire</span>
                        {% elif contract.days_until_expiry <= 90 %}<span class="badge bg-warning text-dark">{{ contract.days_until_expiry }}j restants</span>
                        {% else %}<small class="text-muted">({{ contract.days_until_expiry }}j)</small>{% endif %}
                    {% endif %}
                    {% else %}<span class="text-muted">Duree indeterminee</span>{% endif %}
                </td></tr>
                <tr><td class="text-muted">Visites extérieures</td><td>{% if contract.visit_interval_days %}Tous les {{ contract.visit_interval_days }} jours · prochaine visite {{ contract.next_visit_date.strftime('%d/%m/%Y') if contract.next_visit_date else 'à planifier' }}{% else %}—{% endif %}</td></tr>
            </table>
        </div>
    </div>

    <div class="card border-0 shadow-sm mt-3">
        <div class="card-body">
            <h6><i class="bi bi-arrow-repeat text-primary"></i> Reconduction et preavis</h6>
            <table class="table table-sm table-borderless">
                <tr><td class="text-muted" style="width:30%">Tacite reconduction</td><td>
                    {% if contract.tacit_renewal %}<span class="badge bg-primary">Oui</span> (tous les {{ contract.renewal_period_days }} jours)
                    {% else %}<span class="badge bg-secondary">Non</span>{% endif %}
                </td></tr>
                <tr><td class="text-muted">Delai de preavis</td><td>{{ contract.notice_period_days }} jours avant la fin{% if not contract.notice_period_days %}—{% endif %}</td></tr>
                <tr><td class="text-muted">Date limite preavis</td><td>
                    {% if contract.notice_deadline_calculated %}
                    <strong>{{ contract.notice_deadline_calculated.strftime('%d/%m/%Y') }}</strong>
                    {% if contract.must_send_notice_now %}<span class="badge bg-warning text-dark ms-2">URGENT</span>{% endif %}
                    {% else %}—{% endif %}
                </td></tr>
            </table>
        </div>
    </div>

    {% if contract.annual_amount or contract.notes %}
    <div class="card border-0 shadow-sm mt-3">
        <div class="card-body">
            {% if contract.annual_amount %}
            <h6><i class="bi bi-cash-coin text-success"></i> Montant annuel</h6>
            <strong>{{ "%.2f"|format(contract.annual_amount) }} EUR</strong>
            {% endif %}
            {% if contract.notes %}
            <hr>
            <h6><i class="bi bi-sticky text-secondary"></i> Notes</h6>
            <p class="mb-0" style="white-space: pre-wrap;">{{ contract.notes }}</p>
            {% endif %}
        </div>
    </div>
    {% endif %}
</div>
{% endblock %}
