{% extends "base.html" %}
{% block title %}Horaires et suivi annuel — GMAO{% endblock %}
{% block content %}
<div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div><h1 class="h3"><i class="bi bi-clock-history me-2"></i>Horaires de travail et suivi des heures</h1><p class="text-muted mb-0">Période comptable : {{ period_start.strftime('%d/%m/%Y') }} au {{ period_end.strftime('%d/%m/%Y') }}.</p></div>
    <div class="btn-group"><a class="btn btn-outline-secondary" href="{{ url_for('planning.time_tracking', year=year-1) }}">{{ year-1 }}</a><a class="btn btn-outline-secondary" href="{{ url_for('planning.time_tracking', year=year+1) }}">{{ year+1 }}</a></div>
  </div>

  {% if managed_users %}
  <div class="card border-primary mb-3"><div class="card-body py-2">
    <form id="planning-user-selector" method="get">
      <input type="hidden" name="year" value="{{ year }}">
      <label class="form-label fw-semibold mb-1" for="planning-user">Horaires de travail de :</label>
      <select id="planning-user" name="user_id" class="form-select" onchange="this.form.submit()">
        {% for user in managed_users %}<option value="{{ user.id }}" {% if user.id == target_user_id %}selected{% endif %}>{{ user.full_name or user.username }}</option>{% endfor %}
      </select>
    </form>
    <small class="text-muted">Les horaires et pauses affichés appartiennent à cette personne.</small>
  </div></div>
  {% else %}<p class="text-muted">Horaires affichés pour : <strong>{{ target_user.full_name or target_user.username }}</strong></p>{% endif %}

  <div class="row g-3 mb-3">
    <div class="col-md-3"><div class="card border-primary h-100"><div class="card-body"><small>À réaliser</small><h3>{{ '%d h %02d'|format(required_minutes // 60, required_minutes % 60) }}</h3><small class="text-muted">1607 h moins pénibilité</small></div></div></div>
    <div class="col-md-3"><div class="card border-info h-100"><div class="card-body"><small>Prévu par calendrier</small><h3>{{ '%d h %02d'|format(planned_minutes // 60, planned_minutes % 60) }}</h3></div></div></div>
    <div class="col-md-3"><div class="card border-success h-100"><div class="card-body"><small>Réalisé saisi</small><h3>{{ '%d h %02d'|format(actual_minutes // 60, actual_minutes % 60) }}</h3></div></div></div>
    <div class="col-md-3"><div class="card {% if balance_minutes > 0 %}border-danger{% else %}border-success{% endif %} h-100"><div class="card-body"><small>Solde réalisé / dû</small><h3 class="{% if balance_minutes > 0 %}text-danger{% else %}text-success{% endif %}">{{ '%d h %02d'|format((balance_minutes|abs) // 60, (balance_minutes|abs) % 60) }}</h3><small>{% if balance_minutes > 0 %}heures à faire{% else %}heures en excédent{% endif %}</small></div></div></div>
  </div>

  <div class="card mb-3"><div class="card-header"><strong>Récapitulatif mensuel</strong><small class="d-block text-muted">Les heures de travail prévues excluent les permanences, affichées séparément.</small></div><div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Mois</th><th>Travail prévu</th><th>Permanences</th><th>Retards</th><th>Heures supplémentaires</th><th>Formations</th></tr></thead><tbody>{% for item in monthly_summary %}<tr><td><strong>{{ months[item.month.month] }} {{ item.month.year }}</strong></td><td>{{ '%d h %02d'|format(item.planned // 60, item.planned % 60) }}</td><td>{{ '%d h %02d'|format(item.permanence // 60, item.permanence % 60) }}</td><td class="{% if item.retard %}text-danger{% endif %}">{{ '%d h %02d'|format(item.retard // 60, item.retard % 60) }}</td><td class="{% if item.supplementaire %}text-success{% endif %}">{{ '%d h %02d'|format(item.supplementaire // 60, item.supplementaire % 60) }}</td><td>{{ '%d h %02d'|format(item.formation // 60, item.formation % 60) }}</td></tr>{% else %}<tr><td colspan="6" class="text-muted">Aucune donnée pour cette période.</td></tr>{% endfor %}</tbody></table></div></div>

  <div class="row g-3">
    <div class="col-lg-5">
      <div class="card mb-3"><div class="card-header"><strong>Objectif annuel {{ year }}</strong></div><div class="card-body">
        <form method="post" action="{{ url_for('planning.save_time_config') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="year" value="{{ year }}"><input type="hidden" name="user_id" value="{{ target_user_id }}">
          <div class="row g-2"><div class="col-6"><label class="form-label">Durée annuelle (h)</label><input class="form-control" type="number" step="0.01" name="target_hours" value="{{ '%.2f'|format(time_config.target_minutes / 60) }}"></div><div class="col-6"><label class="form-label">Déduction pénibilité (h)</label><input class="form-control" type="number" step="0.01" min="0" name="hardship_hours" value="{{ '%.2f'|format(time_config.hardship_deduction_minutes / 60) }}"></div></div>
          <label class="form-label mt-2">Notes</label><textarea class="form-control" name="notes" rows="2">{{ time_config.notes or '' }}</textarea><button class="btn btn-primary mt-2">Enregistrer</button>
        </form>
      </div></div>

      <div class="card mb-3"><div class="card-header d-flex justify-content-between"><strong>Horaires types (maximum 6)</strong><span class="badge bg-primary">{{ templates|length }}/6</span></div><div class="card-body">
        {% for template in templates %}<div class="border-bottom py-2"><div class="d-flex justify-content-between"><span><strong>{{ template.name }}</strong><br><small>{{ template.start_time.strftime('%H:%M') }}–{{ template.end_time.strftime('%H:%M') }}{% if template.lunch_start %} · pause {{ template.lunch_start.strftime('%H:%M') }}–{{ template.lunch_end.strftime('%H:%M') }}{% endif %} · <strong>durée : {{ template.duration_minutes // 60 }} h {{ '%02d'|format(template.duration_minutes % 60) }}</strong></small></span><form method="post" action="{{ url_for('planning.delete_time_template', id=template.id) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button></form></div><form method="post" action="{{ url_for('planning.edit_time_template', id=template.id) }}" class="row g-1 mt-1"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><div class="col-3"><label class="form-label small mb-0">Nom</label><input class="form-control form-control-sm" name="name" value="{{ template.name }}"></div><div class="col-2"><label class="form-label small mb-0">Début</label><input class="form-control form-control-sm" type="time" name="start_time" value="{{ template.start_time.strftime('%H:%M') }}"></div><div class="col-2"><label class="form-label small mb-0">Fin</label><input class="form-control form-control-sm" type="time" name="end_time" value="{{ template.end_time.strftime('%H:%M') }}"></div><div class="col-2"><label class="form-label small mb-0">Début pause</label><input class="form-control form-control-sm" type="time" name="lunch_start" value="{{ template.lunch_start.strftime('%H:%M') if template.lunch_start else '' }}"></div><div class="col-2"><label class="form-label small mb-0">Fin pause</label><input class="form-control form-control-sm" type="time" name="lunch_end" value="{{ template.lunch_end.strftime('%H:%M') if template.lunch_end else '' }}"></div><div class="col-1 d-flex align-items-end"><button class="btn btn-sm btn-outline-primary w-100" title="Modifier">OK</button></div></form></div>{% else %}<p class="text-muted">Aucun profil défini.</p>{% endfor %}
        {% if templates|length < 6 %}<form method="post" action="{{ url_for('planning.save_time_template') }}" class="mt-3"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input class="form-control mb-2" name="name" placeholder="Nom : journée normale, été…" required><div class="row g-2"><div class="col-6"><label class="form-label small mb-0">Début du travail</label><input class="form-control" type="time" name="start_time" required></div><div class="col-6"><label class="form-label small mb-0">Fin du travail</label><input class="form-control" type="time" name="end_time" required></div><div class="col-6"><label class="form-label small mb-0">Début de pause</label><input class="form-control" type="time" name="lunch_start"></div><div class="col-6"><label class="form-label small mb-0">Fin de pause</label><input class="form-control" type="time" name="lunch_end"></div></div><button class="btn btn-outline-primary btn-sm mt-2">Ajouter l’horaire type</button></form>{% endif %}
      </div></div>
    </div>

    <div class="col-lg-7">
      <div class="card mb-3"><div class="card-header"><strong>Affectation par jour</strong></div><div class="card-body"><div class="row g-2">
        {% for day_num, day_name in days.items() %}<div class="col-md-6"><form method="post" action="{{ url_for('planning.assign_time_template') }}" class="input-group"><span class="input-group-text">{{ day_name }}</span><input type="hidden" name="day_of_week" value="{{ day_num }}"><select class="form-select" name="template_id" onchange="this.form.submit()"><option value="">Non travaillé</option>{% for template in templates %}<option value="{{ template.id }}" {% if assignments.get(day_num) and assignments[day_num].template_id == template.id %}selected{% endif %}>{{ template.name }}</option>{% endfor %}</select></form></div>{% endfor %}
      </div></div></div>

      <div class="card mb-3"><div class="card-header"><strong>Importer les calendriers</strong></div><div class="card-body"><div class="row g-2"><div class="col-md-6"><form method="post" action="{{ url_for('planning.import_school_vacations') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="year" value="{{ year }}"><div class="input-group"><select class="form-select" name="zone"><option value="C" selected>Zone C</option><option value="B">Zone B</option><option value="A">Zone A</option></select><button class="btn btn-outline-primary">Importer vacances</button></div><small class="text-muted">Changer de zone remplace les périodes scolaires importées pour l’autre zone.</small></form></div><div class="col-md-6"><form method="post" action="{{ url_for('planning.import_public_holidays') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="year" value="{{ year }}"><button class="btn btn-outline-primary">Importer jours fériés {{ year }}</button></form></div></div></div></div>

      <div class="card mb-3"><div class="card-header"><strong>Vacances personnalisées</strong><small class="d-block text-muted">Ajoutez une période manuelle ou supprimez une période existante. Les jours fériés sont gérés séparément.</small></div><div class="card-body"><form method="post" action="{{ url_for('planning.add_manual_vacation') }}" class="row g-2 align-items-end"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="year" value="{{ year }}"><div class="col-md-4"><label class="form-label">Intitulé</label><input class="form-control" name="name" placeholder="Ex. fermeture exceptionnelle" required></div><div class="col-md-3"><label class="form-label">Début</label><input class="form-control" type="date" name="start_date" required></div><div class="col-md-3"><label class="form-label">Fin</label><input class="form-control" type="date" name="end_date" required></div><div class="col-md-2"><button class="btn btn-outline-success w-100">Ajouter</button></div></form><div class="table-responsive mt-3"><table class="table table-sm align-middle mb-0"><thead><tr><th>Période</th><th>Dates</th><th>Origine</th><th></th></tr></thead><tbody>{% for closure in closures if closure.closure_type in ('vacances', 'vacances_scolaires') %}<tr><td>{{ closure.name }}</td><td>{{ closure.start_date.strftime('%d/%m/%Y') }} → {{ closure.end_date.strftime('%d/%m/%Y') }}</td><td>{% if closure.closure_type == 'vacances_scolaires' %}<span class="badge bg-info text-dark">Importée</span>{% else %}<span class="badge bg-secondary">Manuelle</span>{% endif %}</td><td><form method="post" action="{{ url_for('planning.delete_vacation', id=closure.id) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="btn btn-sm btn-outline-danger" title="Supprimer"><i class="bi bi-trash"></i></button></form></td></tr>{% else %}<tr><td colspan="4" class="text-muted">Aucune période de vacances enregistrée.</td></tr>{% endfor %}</tbody></table></div></div></div>

      <div class="card mb-3"><div class="card-header"><strong>Permanences dans les vacances</strong><small class="d-block text-muted">Sélectionnez plusieurs dates puis l’horaire type à appliquer.</small></div><div class="card-body"><form method="post" action="{{ url_for('planning.save_permanences') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="year" value="{{ year }}"><div class="row g-2 align-items-end"><div class="col-md-8"><label class="form-label">Horaire type</label><select class="form-select" name="template_id" required><option value="">Choisir…</option>{% for template in templates %}<option value="{{ template.id }}">{{ template.name }} ({{ template.start_time.strftime('%H:%M') }}–{{ template.end_time.strftime('%H:%M') }})</option>{% endfor %}</select></div><div class="col-md-4"><button class="btn btn-success w-100" {% if not templates %}disabled{% endif %}>Affecter les dates sélectionnées</button></div></div>{% for group in permanence_groups %}<div class="border-top mt-3 pt-2"><h6 class="mb-2"><i class="bi bi-calendar2-week me-1"></i>{{ group.closure.name }} <small class="text-muted">({{ group.closure.start_date.strftime('%d/%m/%Y') }} au {{ group.closure.end_date.strftime('%d/%m/%Y') }})</small></h6><div class="row g-2">{% for option in group.options %}<div class="col-xl-3 col-lg-4 col-md-6"><label class="border rounded p-2 d-block"><input type="checkbox" name="work_dates" value="{{ option.date.isoformat() }}" {% if option.entry %}checked{% endif %}> <strong>{{ days.get(option.date.weekday()) }} {{ option.date.strftime('%d/%m/%Y') }}</strong><br><small>{% if option.entry and option.entry.template %}{{ option.entry.template.name }} · {{ option.entry.start_time.strftime('%H:%M') }}–{{ option.entry.end_time.strftime('%H:%M') }}{% else %}Pas de permanence{% endif %}</small></label></div>{% endfor %}</div></div>{% else %}<div class="text-muted mt-3">Aucune période de vacances importée pour cette période. Importez d’abord le calendrier scolaire.</div>{% endfor %}</form>
      {% set selected_permanences = permanence_options|selectattr('entry')|list %}
      <hr><h6><i class="bi bi-list-check me-1"></i>Récapitulatif des permanences</h6>
      {% if selected_permanences %}<div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Date</th><th>Vacances</th><th>Horaire type</th><th>Horaires détaillés</th><th></th></tr></thead><tbody>{% for option in selected_permanences %}<tr><td><strong>{{ days.get(option.date.weekday()) }}</strong><br>{{ option.date.strftime('%d/%m/%Y') }}</td><td>{{ option.closure.name }}</td><td>{{ option.entry.template.name if option.entry.template else 'Horaire personnalisé' }}</td><td>{{ option.entry.start_time.strftime('%H:%M') }}–{{ option.entry.end_time.strftime('%H:%M') }}{% if option.entry.lunch_start and option.entry.lunch_end %}<br><small class="text-muted">Pause {{ option.entry.lunch_start.strftime('%H:%M') }}–{{ option.entry.lunch_end.strftime('%H:%M') }}</small>{% endif %}</td><td><form method="post" action="{{ url_for('planning.delete_permanence', id=option.entry.id) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="btn btn-sm btn-outline-danger" title="Supprimer"><i class="bi bi-trash"></i></button></form></td></tr>{% endfor %}</tbody></table></div>{% else %}<p class="text-muted mb-0">Aucune permanence enregistrée pour cette période.</p>{% endif %}</div></div>

      <div class="card mb-3"><div class="card-header"><strong>Saisir un retard ou une heure supplémentaire</strong></div><div class="card-body"><form method="post" action="{{ url_for('planning.save_time_entry') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><div class="row g-2"><div class="col-md-3"><input class="form-control" type="date" name="work_date" required></div><div class="col-md-2"><input class="form-control" type="number" name="planned_minutes" placeholder="Prévu (min)" value="0"></div><div class="col-md-2"><input class="form-control" type="number" name="actual_minutes" placeholder="Réalisé (min)" value="0"></div><div class="col-md-2"><select class="form-select" name="entry_type"><option value="travail">Travail</option><option value="retard">Retard</option><option value="supplementaire">Heures sup.</option><option value="permanence">Permanence</option></select></div><div class="col-md-3"><input class="form-control" name="note" placeholder="Note"></div></div><button class="btn btn-primary mt-2">Enregistrer la journée</button></form></div></div>
    </div>
  </div>

  <div class="card"><div class="card-header"><strong>Historique {{ year }}</strong></div><div class="table-responsive"><table class="table table-sm mb-0"><thead><tr><th>Date</th><th>Type</th><th>Prévu</th><th>Réalisé</th><th>Écart</th><th>Note</th></tr></thead><tbody>{% for entry in entries[:50] %}<tr><td>{{ entry.work_date.strftime('%d/%m/%Y') }}</td><td>{{ entry.entry_type }}</td><td>{{ entry.planned_minutes }} min</td><td>{{ entry.actual_minutes }} min</td><td class="{% if entry.variance_minutes < 0 %}text-danger{% elif entry.variance_minutes > 0 %}text-success{% endif %}">{{ '+' if entry.variance_minutes > 0 else '' }}{{ entry.variance_minutes }} min</td><td>{{ entry.note or '—' }}</td></tr>{% else %}<tr><td colspan="6" class="text-muted">Aucune saisie.</td></tr>{% endfor %}</tbody></table></div></div>
</div>
<script>
document.querySelectorAll('form[action*="assign_time_template"]').forEach(function (form) { var input = document.createElement('input'); input.type = 'hidden'; input.name = 'year'; input.value = '{{ year }}'; form.appendChild(input); });
document.querySelectorAll('form[action*="/planning/time/"]').forEach(function (form) {
  if (!form.querySelector('input[name="user_id"]')) {
    var input = document.createElement('input'); input.type = 'hidden'; input.name = 'user_id'; input.value = '{{ target_user_id }}'; form.appendChild(input);
  }
});
document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('input[name="work_dates"][checked]').forEach(function (input) {
    input.disabled = true;
    input.closest('label').classList.add('bg-light', 'text-muted');
    input.closest('label').title = 'Permanence déjà enregistrée — suppression possible dans le récapitulatif.';
  });
});
</script>
{% endblock %}
