{% extends "base.html" %}
{% block title %}{{ 'Nouvelle tâche' if creating else 'Modifier la tâche' }} — {{ lot.name }}{% endblock %}
{% block content %}
<div class="container-fluid" style="max-width:1100px">
  <nav aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="{{ url_for('lots.index') }}">Lots</a></li><li class="breadcrumb-item"><a href="{{ url_for('lots.detail', id=lot.id) }}">{{ lot.name }}</a></li><li class="breadcrumb-item active">Règle préventive</li></ol></nav>
  <h1 class="h3 mb-3">{{ 'Nouvelle tâche préventive' if creating else 'Modifier la tâche préventive' }}</h1>
  <form method="post" class="card"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <div class="card-body">
      <div class="row g-3">
        <div class="col-md-3"><label class="form-label">Numéro</label><input class="form-control" name="num_tache" value="{{ task.num_tache or '' }}"></div>
        <div class="col-md-9"><label class="form-label">Tâche *</label><input class="form-control" name="tache" required value="{{ task.tache or '' }}"></div>
        <div class="col-12"><label class="form-label">Périodicité lisible</label><input class="form-control" name="periodicite" value="{{ task.periodicite or '' }}" placeholder="Ex. tous les ans pendant les vacances d'été"></div>
        <div class="col-md-4"><label class="form-label">Déclenchement</label><select class="form-select" name="trigger_type"><option value="calendar" {% if task.trigger_type == 'calendar' %}selected{% endif %}>Calendrier</option><option value="season" {% if task.trigger_type == 'season' %}selected{% endif %}>Saison</option><option value="event" {% if task.trigger_type == 'event' %}selected{% endif %}>Événement</option><option value="weather" {% if task.trigger_type == 'weather' %}selected{% endif %}>Météo</option><option value="meter" {% if task.trigger_type == 'meter' %}selected{% endif %}>Compteur</option></select></div>
        <div class="col-md-4"><label class="form-label">Intervalle (jours)</label><input class="form-control" type="number" min="1" name="jours_entre_interventions" value="{{ task.jours_entre_interventions or '' }}"></div>
        <div class="col-md-4"><label class="form-label">Anticipation (jours)</label><input class="form-control" type="number" min="0" name="advance_days" value="{{ task.advance_days or 0 }}"></div>
        <div class="col-md-4"><label class="form-label">Durée par cible (minutes)</label><input class="form-control" type="number" min="1" name="duree_minutes" value="{{ task.duree_minutes or '' }}"></div>
        <div class="col-md-4"><label class="form-label">Type de durée</label><select class="form-select" name="duration_mode"><option value="unit" {% if task.duration_mode == 'unit' %}selected{% endif %}>Par élément (× quantité)</option><option value="fixed" {% if task.duration_mode == 'fixed' %}selected{% endif %}>Forfait par cible</option><option value="zone" {% if task.duration_mode == 'zone' %}selected{% endif %}>Durée définie par la zone</option></select><div class="form-text">Sans durée, la tâche reste à renseigner et n'est pas planifiée.</div></div>
        <div class="col-md-4"><label class="form-label">Événement</label><input class="form-control" name="trigger_event" value="{{ task.trigger_event or '' }}" placeholder="orage, gel…"></div>
        <div class="col-md-4"><label class="form-label">Seuil compteur</label><input class="form-control" type="number" step="0.01" name="meter_threshold" value="{{ task.meter_threshold or '' }}"></div>
        <div class="col-md-3"><label class="form-label">Début de saison</label><input class="form-control" type="number" min="1" max="12" name="season_start_month" value="{{ task.season_start_month or '' }}"></div>
        <div class="col-md-3"><label class="form-label">Fin de saison</label><input class="form-control" type="number" min="1" max="12" name="season_end_month" value="{{ task.season_end_month or '' }}"></div>
        <div class="col-md-6"><label class="form-label">Portée</label><select class="form-select" name="application_scope"><option value="auto" {% if task.application_scope == 'auto' %}selected{% endif %}>Automatique selon le type d’équipement</option><option value="group" {% if task.application_scope == 'group' %}selected{% endif %}>Une tâche par groupe/localisation</option><option value="unit" {% if task.application_scope == 'unit' %}selected{% endif %}>Une tâche par unité individualisée</option></select><div class="form-text">Pour 30 chaises, « groupe » crée une seule tâche dans la salle.</div></div>
        <div class="col-md-6"><label class="form-label">Périmètre des équipements</label><select class="form-select" name="scope_mode"><option value="dynamic" {% if task.scope_mode != 'manual' %}selected{% endif %}>Dynamique : équipements actifs de ce lot</option><option value="manual" {% if task.scope_mode == 'manual' %}selected{% endif %}>Manuel : uniquement la sélection ci-dessous</option></select></div>
        <div class="col-12"><label class="form-label" for="equipment-filter">Équipements concernés (périmètre manuel)</label><input id="equipment-filter" class="form-control mb-2" type="search" placeholder="Filtrer par équipement, salle, zone ou bâtiment" oninput="filterEquipmentScope(this.value)"><div class="d-flex gap-2 mb-2"><button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectVisibleEquipment(true)">Tout sélectionner</button><button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectVisibleEquipment(false)">Tout désélectionner</button></div><select id="equipment-scope" class="form-select" name="equipment_ids" multiple size="6" aria-describedby="scope-help">{% for equipment in equipments %}<option value="{{ equipment.id }}" data-search="{{ equipment.name }} {{ equipment.room.name if equipment.room else '' }} {{ equipment.room.zone.name if equipment.room and equipment.room.zone else '' }} {{ equipment.room.building.name if equipment.room and equipment.room.building else '' }}" {% if equipment in task.equipment_scope %}selected{% endif %}>{{ equipment.name }}{% if equipment.room %} — {{ equipment.room.name }}{% endif %}</option>{% endfor %}</select><div id="scope-help" class="form-text">La sélection s'applique aux équipements filtrés. Les nouveaux équipements du lot sont inclus automatiquement en mode dynamique.</div></div>
        <div class="col-md-6"><label class="form-label">Si l’équipement est indisponible</label><select class="form-select" name="unavailable_policy"><option value="suspend" {% if task.unavailable_policy == 'suspend' %}selected{% endif %}>Suspendre et reprendre après réparation</option><option value="keep" {% if task.unavailable_policy == 'keep' %}selected{% endif %}>Maintenir la tâche</option><option value="postpone" {% if task.unavailable_policy == 'postpone' %}selected{% endif %}>Ne pas générer avant remise en service</option></select></div>
        <div class="col-md-6"><label class="form-label">Après réparation</label><select class="form-select" name="after_repair_policy"><option value="preserve" {% if task.after_repair_policy == 'preserve' %}selected{% endif %}>Conserver l’échéance d’origine</option><option value="reset" {% if task.after_repair_policy == 'reset' %}selected{% endif %}>Repartir de la date de réparation</option></select></div>
        <div class="col-md-6"><label class="form-label">Entreprise exécutante</label><select class="form-select" name="company_id"><option value="">Interne / non définie</option>{% for company in companies %}<option value="{{ company.id }}" {% if task.company_id == company.id %}selected{% endif %}>{{ company.name }}</option>{% endfor %}</select></div>
        <div class="col-md-6"><label class="form-label">Contrat associé</label><select class="form-select" name="contract_id"><option value="">Aucun contrat</option>{% for contract in contracts %}<option value="{{ contract.id }}" {% if task.contract_id == contract.id %}selected{% endif %}>{{ contract.name }}{% if contract.contract_number %} — {{ contract.contract_number }}{% endif %}</option>{% endfor %}</select></div>
        <div class="col-md-6"><label class="form-label">Exécutant</label><select class="form-select" name="executor_type"><option value="undefined" {% if task.executor_type == 'undefined' %}selected{% endif %}>Non défini</option><option value="internal" {% if task.executor_type == 'internal' %}selected{% endif %}>Équipe du collège</option><option value="external_company" {% if task.executor_type == 'external_company' %}selected{% endif %}>Entreprise extérieure</option><option value="department" {% if task.executor_type == 'department' %}selected{% endif %}>Département / autre service</option><option value="mixed" {% if task.executor_type == 'mixed' %}selected{% endif %}>Mixte</option></select></div>
        <div class="col-md-6"><label class="form-label">Nature de la tâche</label><select class="form-select" name="task_nature"><option value="unknown" {% if task.task_nature == 'unknown' %}selected{% endif %}>À confirmer</option><option value="preventive" {% if task.task_nature == 'preventive' %}selected{% endif %}>Préventive</option><option value="conditional_curative" {% if task.task_nature == 'conditional_curative' %}selected{% endif %}>Conditionnelle / curative</option><option value="regulatory" {% if task.task_nature == 'regulatory' %}selected{% endif %}>Réglementaire</option><option value="contractual" {% if task.task_nature == 'contractual' %}selected{% endif %}>Contractuelle</option></select></div>
        <div class="col-12"><fieldset class="border rounded p-3"><legend class="float-none w-auto px-2 fs-6">Exécution interrompable</legend><div class="row g-2"><div class="col-md-3 form-check"><input class="form-check-input" type="checkbox" name="interruptible" id="interruptible" {% if task.interruptible %}checked{% endif %}><label class="form-check-label" for="interruptible">Pause autorisée</label></div><div class="col-md-3 form-check"><input class="form-check-input" type="checkbox" name="splittable" id="splittable" {% if task.splittable %}checked{% endif %}><label class="form-check-label" for="splittable">Fractionnable</label></div><div class="col-md-3"><label class="form-label" for="minimum_segment_minutes">Segment minimum (min)</label><input class="form-control" type="number" min="1" name="minimum_segment_minutes" id="minimum_segment_minutes" value="{{ task.minimum_segment_minutes or '' }}"></div><div class="col-md-3 form-check"><input class="form-check-input" type="checkbox" name="allow_next_day_resume" id="allow_next_day_resume" {% if task.allow_next_day_resume %}checked{% endif %}><label class="form-check-label" for="allow_next_day_resume">Reprise le lendemain</label></div><div class="col-md-4 form-check"><input class="form-check-input" type="checkbox" name="requires_safe_pause" id="requires_safe_pause" {% if task.requires_safe_pause %}checked{% endif %}><label class="form-check-label" for="requires_safe_pause">Remise en sécurité avant pause</label></div></div></fieldset></div>
        <div class="col-md-3 form-check ms-2 mt-5"><input class="form-check-input" type="checkbox" name="is_safety_critical" id="safety" {% if task.is_safety_critical %}checked{% endif %}><label class="form-check-label" for="safety">Tâche de sécurité</label></div>
        <div class="col-md-2 form-check ms-2 mt-5"><input class="form-check-input" type="checkbox" name="is_active" id="active" {% if task.is_active %}checked{% endif %}><label class="form-check-label" for="active">Active</label></div>
      </div>
    </div>
    <div class="card-footer d-flex justify-content-end gap-2"><a class="btn btn-outline-secondary" href="{{ url_for('lots.detail', id=lot.id) }}">Annuler</a><button class="btn btn-primary"><i class="bi bi-check-lg"></i> Enregistrer</button></div>
  </form>
</div>
<script>
function filterEquipmentScope(value) { const q = value.toLowerCase(); document.querySelectorAll('#equipment-scope option').forEach(o => { o.hidden = q && !(o.dataset.search || '').toLowerCase().includes(q); }); }
function selectVisibleEquipment(selected) { document.querySelectorAll('#equipment-scope option').forEach(o => { if (!o.hidden) o.selected = selected; }); }
</script>
{% endblock %}
