{% extends 'base.html.twig' %}

{% set jours_fr = {'Mon': 'L', 'Tue': 'M', 'Wed': 'M', 'Thu': 'J', 'Fri': 'V', 'Sat': 'S', 'Sun': 'D'} %}

{% block title %}Planning Client - {{ site.name }}{% endblock %}

{% block body %}
{# Variables de synthèse besoins #}
{% set remainingHours = totalNeededHours - grandTotals.total %}

<!-- Bannière synthèse besoins -->
{% if totalNeededHours > 0 %}
<div class="row mb-3">
    <div class="col-12">
        <div class="alert border-0 py-2 px-3 mb-0 d-flex align-items-center gap-3 flex-wrap"
             style="background: linear-gradient(90deg, #fd7e14 0%, #ffc107 100%); color: #fff;">
            <i class="bi bi-clock-history fs-5"></i>
            <span class="fw-bold fs-6">BESOINS CLIENT :</span>
            <span>Demandé : <strong>{{ totalNeededHours|number_format(2, ',', ' ') }} h</strong></span>
            <span>|</span>
            <span>Affecté : <strong>{{ grandTotals.total|number_format(2, ',', ' ') }} h</strong></span>
            <span>|</span>
            <span class="fw-bold fs-5" style="background:rgba(0,0,0,.15); padding:2px 10px; border-radius:6px;
                  color:{{ remainingHours > 0 ? '#ffcccc' : '#d4edda' }};">
                Reste : {{ remainingHours|number_format(2, ',', ' ') }} h
            </span>
        </div>
    </div>
</div>
{% else %}
<div class="row mb-3">
    <div class="col-12">
        <div class="alert d-flex align-items-center gap-2 py-2" style="background:#fff3cd; border-color:#ffc107;">
            <i class="bi bi-info-circle text-warning"></i>
            <span>Aucun besoin client saisi pour ce mois. Cliquez sur <strong>«&nbsp;+&nbsp;»</strong> dans la ligne <em>BESOINS</em> du tableau.</span>
        </div>
    </div>
</div>
{% endif %}

<!-- Page Title -->
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between">
            <h4 class="mb-sm-0 font-size-18">Planning Client</h4>
            <div class="page-title-right">
                <ol class="breadcrumb m-0">
                    <li class="breadcrumb-item"><a href="{{ path('app_dashboard') }}">Accueil</a></li>
                    <li class="breadcrumb-item"><a href="{{ path('app_planning_client_index') }}">Plannings Client</a></li>
                    <li class="breadcrumb-item active">{{ site.name }}</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Planning Document -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <!-- Header -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <h3 class="mb-3">Planning Client</h3>
                        <p class="mb-1">Le : {{ "now"|date("d/m/Y") }}</p>
                        <p class="mb-1">Agence : <strong>{{ agency.name }}</strong></p>
                        <p class="mb-1">Client : <strong>{{ site.clientName ?? '-' }}</strong></p>
                        <p class="mb-0">Planificateur : Mohammed ELABED</p>
                    </div>
                    <div class="col-md-6">
                    </div>
                </div>

                <!-- Site Info -->
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="table-responsive">
                            <table class="table table-bordered mb-0">
                                <tbody>
                                    <tr class="table-secondary">
                                        <td><strong>{{ site.name }}</strong></td>
                                        <td>{{ site.address }}</td>
                                        <td><strong>{{ site.postalCode }}</strong></td>
                                        <td><strong>{{ site.city|upper }}</strong></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Month Navigation -->
                {% set prevMonth = month == 1 ? 12 : month - 1 %}
                {% set prevYear  = month == 1 ? year - 1 : year %}
                {% set nextMonth = month == 12 ? 1 : month + 1 %}
                {% set nextYear  = month == 12 ? year + 1 : year %}
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <a href="{{ path('app_planning_client_show', {id: site.id, year: prevYear, month: prevMonth}) }}"
                       class="btn btn-outline-secondary btn-sm">
                        <i class="bi bi-chevron-left"></i> Mois précédent
                    </a>
                    <strong>{{ monthName|upper }} {{ year }}</strong>
                    <a href="{{ path('app_planning_client_show', {id: site.id, year: nextYear, month: nextMonth}) }}"
                       class="btn btn-outline-secondary btn-sm">
                        Mois suivant <i class="bi bi-chevron-right"></i>
                    </a>
                </div>

                {# Warning dépassement 48h/semaine #}
                {% if agentOverweeks|length > 0 %}
                    <div class="alert alert-danger d-flex align-items-start mb-3" role="alert">
                        <i class="bi bi-exclamation-triangle-fill me-2 fs-4"></i>
                        <div>
                            <strong>Dépassement temps de travail légal ({{ weeklyLimit }}h/semaine)</strong>
                            <ul class="mb-0 mt-1">
                                {% for agentId, overWeeks in agentOverweeks %}
                                    {% set agentData = agentsByDay[agentId] %}
                                    <li>
                                        <strong>{{ agentData.agent.lastName|upper }} {{ agentData.agent.firstName }}</strong> :
                                        {% for k, h in overWeeks %}
                                            {% set parts = k|split('-') %}
                                            Semaine {{ parts[1] }} ({{ h|number_format(2, ',', ' ') }} h){{ not loop.last ? ', ' : '' }}
                                        {% endfor %}
                                    </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                {% endif %}

                <!-- Calendar Header -->
                <div class="table-responsive">
                    <table class="table table-bordered table-sm planning-table">
                        <thead>
                            <tr class="table-light">
                                <th rowspan="2" style="width: 100px;">{{ monthName|upper }} {{ year }}</th>
                                {% for day in daysInMonth %}
                                    <th class="day-header {{ day.format('N') in ['6', '7'] ? 'bg-light' : '' }}{{ day.format('Y-m-d') in publicHolidays|keys ? ' table-danger' : '' }}">
                                        {{ jours_fr[day.format('D')] }}
                                    </th>
                                {% endfor %}
                                <th rowspan="2" style="width: 60px;">Total</th>
                            </tr>
                            <tr class="table-light">
                                {% for day in daysInMonth %}
                                    <th class="day-header {{ day.format('N') in ['6', '7'] ? 'bg-light' : '' }}{{ day.format('Y-m-d') in publicHolidays|keys ? ' table-danger' : '' }}">
                                        {{ day.format('d') }}
                                    </th>
                                {% endfor %}
                            </tr>
                        </thead>
                        <tbody>

                            {# ── Ligne BESOINS CLIENT (Phase 1) ── #}
                            {% set totalNeedRow = 0 %}
                            {% set totalNeedNight = 0 %}
                            {% set totalNeedDay = 0 %}
                            <tr style="background: linear-gradient(90deg,#fd7e14 0%,#ffc107 100%); color:#fff;">
                                <td class="text-start fw-bold" style="vertical-align:middle; font-size:.85em;">
                                    <i class="bi bi-person-exclamation me-1"></i>BESOINS
                                </td>
                                {% for day in daysInMonth %}
                                    {% set dayNeeds = clientNeeds[day.format('Y-m-d')]|default([]) %}
                                    {% set dayNeedHours = 0 %}
                                    {% set dayNeedNight = 0 %}
                                    {% set dayNeedDay = 0 %}
                                    {% set firstNeedId = null %}
                                    {% set firstStart = '' %}
                                    {% set firstEnd = '' %}
                                    {% set firstEntryId = '' %}
                                    {% set firstAgentLabel = '' %}
                                    {% for n in dayNeeds %}
                                        {% set h = n.calculatedHours %}
                                        {% set dayNeedHours = dayNeedHours + h %}
                                        {% set dayNeedNight = dayNeedNight + n.nightHours %}
                                        {% set dayNeedDay = dayNeedDay + n.dayHours %}
                                        {% if firstNeedId is null %}
                                            {% set firstNeedId = n.id %}
                                            {% set firstStart = n.startTime ? n.startTime|date('H:i') : '' %}
                                            {% set firstEnd = n.endTime ? n.endTime|date('H:i') : '' %}
                                            {% if n.linkedEntry %}
                                                {% set firstEntryId = n.linkedEntry.id %}
                                                {% if n.linkedEntry.agent %}
                                                    {% set firstAgentLabel = n.linkedEntry.agent.lastName|upper ~ ' ' ~ n.linkedEntry.agent.firstName %}
                                                {% endif %}
                                            {% endif %}
                                        {% endif %}
                                    {% endfor %}
                                    {% set totalNeedRow = totalNeedRow + dayNeedHours %}
                                    {% set totalNeedNight = totalNeedNight + dayNeedNight %}
                                    {% set totalNeedDay = totalNeedDay + dayNeedDay %}
                                    <td class="text-center p-0"
                                        style="{{ day.format('N') in ['6','7'] ? 'background:rgba(0,0,0,.1);' : '' }}">
                                        <button type="button"
                                                class="btn p-0 w-100 h-100 need-cell-btn"
                                                style="color:inherit; background:transparent; border:none; min-height:54px; cursor:pointer;"
                                                data-site-id="{{ site.id }}"
                                                data-date="{{ day.format('Y-m-d') }}"
                                                data-need-id="{{ firstNeedId ?? '' }}"
                                                data-start="{{ firstStart }}"
                                                data-end="{{ firstEnd }}"
                                                data-entry-id="{{ firstEntryId }}"
                                                data-agent-label="{{ firstAgentLabel }}"
                                                title="Besoin du {{ day.format('d/m') }}">
                                            {% if dayNeedHours > 0 %}
                                                {% if dayNeeds|length > 1 %}
                                                    <small style="font-size:.68em; line-height:1.3; display:block;">{{ dayNeeds|length }} besoins</small>
                                                {% elseif firstStart %}
                                                    <small style="font-size:.68em; line-height:1.3; display:block;">{{ firstStart }}</small>
                                                    <small style="font-size:.68em; line-height:1.3; display:block;">{{ firstEnd }}</small>
                                                {% endif %}
                                                <small class="fw-bold" style="font-size:.75em;">{{ dayNeedHours|number_format(1, ',') }}h</small>
                                                {% if firstAgentLabel %}
                                                    <i class="bi bi-person-check" title="{{ firstAgentLabel }}" style="font-size:.85em; opacity:.85;"></i>
                                                {% endif %}
                                            {% else %}
                                                <span class="opacity-50" style="font-size:.85em;">+</span>
                                            {% endif %}
                                        </button>
                                    </td>
                                {% endfor %}
                                <td class="fw-bold text-center" style="vertical-align:middle; font-size:.85em;">
                                    <small style="display:block;">{{ totalNeedNight|number_format(2, ',', ' ') }}</small>
                                    <small style="display:block;">{{ totalNeedDay|number_format(2, ',', ' ') }}</small>
                                    <strong>{{ totalNeedRow|number_format(2, ',', ' ') }}</strong>
                                </td>
                            </tr>

                            {# ── Lignes agents (Phase 2) ── #}
                            {% for agentId, agentData in agentsByDay %}
                                {% set overWeeks = agentOverweeks[agentId]|default({}) %}
                                <tr class="{{ overWeeks|length > 0 ? 'table-danger' : '' }}">
                                    <td class="text-start" style="font-size:.8em;">
                                        <strong>{{ agentData.agent.lastName|upper }}</strong>
                                        {% if overWeeks|length > 0 %}
                                            {% set tooltip = '' %}
                                            {% for k, h in overWeeks %}
                                                {% set parts = k|split('-') %}
                                                {% set tooltip = tooltip ~ 'S' ~ parts[1] ~ ' : ' ~ h|number_format(2,',',' ') ~ 'h\n' %}
                                            {% endfor %}
                                            <i class="bi bi-exclamation-triangle-fill text-danger ms-1"
                                               title="Dépassement {{ weeklyLimit }}h/semaine&#10;{{ tooltip }}"
                                               style="cursor:help;"></i>
                                        {% endif %}
                                        <br>
                                        <small>{{ agentData.agent.firstName }}</small>
                                    </td>
                                    {% for day in daysInMonth %}
                                        {% set entry = agentData.entries[day.format('Y-m-d')]|default(null) %}
                                        <td class="{{ entry ? (entry.isNightShift ? 'shift-night' : 'shift-day') : '' }} {{ day.format('N') == '7' ? 'day-sunday' : '' }}">
                                            {% if entry and entry.entryType == 'vacation' %}
                                                <small>
                                                    {{ entry.shiftCode }}<br>
                                                    <span class="text-muted">{{ entry.startTime|date('H:i') }}</span><br>
                                                    <span class="text-muted">{{ entry.endTime|date('H:i') }}</span>
                                                </small>
                                            {% endif %}
                                        </td>
                                    {% endfor %}
                                    <td>
                                        <strong>{{ agentData.totalHours|number_format(2, ',', ' ') }}</strong><br>
                                        <small>{{ agentData.nightHours|number_format(2, ',', ' ') }}</small><br>
                                        <small>{{ agentData.dayHours|number_format(2, ',', ' ') }}</small>
                                    </td>
                                </tr>
                            {% endfor %}

                            <!-- Totaux -->
                            <tr class="table-warning">
                                <td class="text-start" style="vertical-align:middle;">
                                    <strong>TOTAL</strong><br>
                                    <small>N</small><br>
                                    <small>J</small><br>
                                    <small class="fw-bold">T</small><br>
                                    <small style="color:#e65c00; font-size:.7em;">B-N</small><br>
                                    <small style="color:#e65c00; font-size:.7em;">B-J</small><br>
                                    <small style="color:#e65c00; font-size:.7em; font-weight:700;">B-T</small>
                                </td>
                                {% for day in daysInMonth %}
                                    {% set dayTotals = totalsByDay[day.format('Y-m-d')]|default({night: 0, day: 0, total: 0}) %}
                                    {% set dayNeeds  = needsTotalsByDay[day.format('Y-m-d')]|default({night: 0, day: 0, total: 0}) %}
                                    <td class="text-center" style="vertical-align:middle;">
                                        <small>{{ dayTotals.night|number_format(2, ',', ' ') }}</small><br>
                                        <small>{{ dayTotals.day|number_format(2, ',', ' ') }}</small><br>
                                        <small class="fw-bold">{{ dayTotals.total|number_format(2, ',', ' ') }}</small><br>
                                        <small style="color:#e65c00; font-size:.7em;">{{ dayNeeds.night > 0 ? dayNeeds.night|number_format(2,',',' ') : '-' }}</small><br>
                                        <small style="color:#e65c00; font-size:.7em;">{{ dayNeeds.day > 0 ? dayNeeds.day|number_format(2,',',' ') : '-' }}</small><br>
                                        <small style="color:#e65c00; font-size:.7em; font-weight:700;">{{ dayNeeds.total > 0 ? dayNeeds.total|number_format(2,',',' ') : '-' }}</small>
                                    </td>
                                {% endfor %}
                                <td style="vertical-align:middle;">
                                    <small>{{ grandTotals.night|number_format(2, ',', ' ') }}</small><br>
                                    <small>{{ grandTotals.day|number_format(2, ',', ' ') }}</small><br>
                                    <strong>{{ grandTotals.total|number_format(2, ',', ' ') }}</strong><br>
                                    <small style="color:#e65c00; font-size:.75em;">{{ needsGrandTotals.night|number_format(2,',',' ') }}</small><br>
                                    <small style="color:#e65c00; font-size:.75em;">{{ needsGrandTotals.day|number_format(2,',',' ') }}</small><br>
                                    <strong style="color:#e65c00; font-size:.85em;">{{ needsGrandTotals.total|number_format(2,',',' ') }}</strong>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Détails + Synthèse besoins -->
                <div class="row mt-4">
                    <div class="col-md-6">
                        <h5>DÉTAILS</h5>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm">
                                <thead class="table-light">
                                    <tr>
                                        <th style="width: 60px;">Type</th>
                                        <th>Description</th>
                                        <th style="width: 100px;">Affecté</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr><td>SJ</td><td>Semaine Jour</td><td>{{ details.sj|default(0)|number_format(2, ',', ' ') }}</td></tr>
                                    <tr><td>SN</td><td>Semaine Nuit</td><td>{{ details.sn|default(0)|number_format(2, ',', ' ') }}</td></tr>
                                    <tr><td>DJ</td><td>Dimanche Jour</td><td>{{ details.dj|default(0)|number_format(2, ',', ' ') }}</td></tr>
                                    <tr><td>DN</td><td>Dimanche Nuit</td><td>{{ details.dn|default(0)|number_format(2, ',', ' ') }}</td></tr>
                                    <tr><td>DJF</td><td>Dimanche Jour Férié</td><td>{{ details.djf|default(0)|number_format(2, ',', ' ') }}</td></tr>
                                    <tr><td>DNF</td><td>Dimanche Nuit Férié</td><td>{{ details.dnf|default(0)|number_format(2, ',', ' ') }}</td></tr>
                                    <tr><td>JF</td><td>Jour Férié</td><td>{{ details.jf|default(0)|number_format(2, ',', ' ') }}</td></tr>
                                    <tr><td>NF</td><td>Nuit Férié</td><td>{{ details.nf|default(0)|number_format(2, ',', ' ') }}</td></tr>
                                </tbody>
                                <tfoot class="table-secondary fw-bold">
                                    <tr>
                                        <td colspan="2">TOTAL AFFECTÉ</td>
                                        <td>{{ grandTotals.total|number_format(2, ',', ' ') }}</td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h5>SYNTHÈSE BESOINS</h5>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm">
                                <tbody>
                                    <tr>
                                        <td>Heures demandées</td>
                                        <td class="fw-bold text-end">{{ totalNeededHours|number_format(2, ',', ' ') }} h</td>
                                    </tr>
                                    <tr>
                                        <td>Heures affectées</td>
                                        <td class="fw-bold text-end">{{ grandTotals.total|number_format(2, ',', ' ') }} h</td>
                                    </tr>
                                    <tr class="{{ remainingHours > 0 ? 'table-danger' : (totalNeededHours > 0 ? 'table-success' : '') }}">
                                        <td class="fw-bold">Reste à couvrir</td>
                                        <td class="fw-bold text-end fs-5">{{ remainingHours|number_format(2, ',', ' ') }} h</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        {% if remainingHours > 0 %}
                            <div class="alert alert-danger py-2 mb-0">
                                <i class="bi bi-exclamation-triangle-fill me-1"></i>
                                <strong>{{ remainingHours|number_format(2, ',', ' ') }} h</strong> de besoins non couverts !
                            </div>
                        {% elseif totalNeededHours > 0 %}
                            <div class="alert alert-success py-2 mb-0">
                                <i class="bi bi-check-circle-fill me-1"></i>
                                Tous les besoins sont couverts.
                            </div>
                        {% endif %}
                    </div>
                </div>

                <!-- Actions -->
                <div class="row mt-4">
                    <div class="col-12 text-end">
                        <a href="{{ path('app_planning_client_pdf', {id: site.id, year: year, month: month}) }}" class="btn btn-primary">
                            <i class="bi bi-file-pdf me-1"></i> Télécharger PDF
                        </a>
                        <button type="button" class="btn btn-success" id="btnOpenEmailClientModal"
                                data-url="{{ path('app_email_send_client', {id: site.id, year: year, month: month}) }}">
                            <i class="bi bi-envelope me-1"></i> Envoyer par email
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal besoin client -->
<div class="modal fade" id="needModal" tabindex="-1" aria-labelledby="needModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="max-width:420px; margin-left:calc(50vw - 100px); margin-right:0;">
        <div class="modal-content">
            <div class="modal-header py-2" style="background:linear-gradient(90deg,#fd7e14,#ffc107); color:#fff;">
                <h6 class="modal-title" id="needModalLabel">
                    <i class="bi bi-clock me-1"></i> Besoin — <span id="needModalDate"></span>
                </h6>
                <button type="button" class="btn-close btn-close-white btn-sm" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" style="max-height:80vh; overflow-y:auto;">
                <input type="hidden" id="needSiteId" value="{{ site.id }}">
                <input type="hidden" id="needId">
                <input type="hidden" id="needDate">
                <input type="hidden" id="needEntryId">

                {# Plage horaire #}
                <div class="mb-2">
                    <label class="form-label form-label-sm mb-1">Heure de début</label>
                    <input type="time" class="form-control form-control-sm" id="needStartTime">
                </div>
                <div class="mb-2">
                    <label class="form-label form-label-sm mb-1">Heure de fin</label>
                    <input type="time" class="form-control form-control-sm" id="needEndTime">
                </div>

                <hr class="my-2">

                {# Affectation agent (Phase 2) #}
                <div class="mb-2 position-relative">
                    <label class="form-label form-label-sm mb-1">
                        <i class="bi bi-person-badge me-1"></i>Agent (optionnel)
                    </label>
                    <input type="text" class="form-control form-control-sm" id="needAgentInput"
                           placeholder="Nom, prénom ou matricule…" autocomplete="off">
                    <input type="hidden" id="needAgentId">
                    <div id="needAgentDropdown"
                         class="list-group position-absolute w-100 shadow-sm"
                         style="z-index:2000; display:none; max-height:180px; overflow-y:auto; top:100%;"></div>
                </div>

                {# Motif de modification #}
                <div class="mb-2">
                    <label class="form-label form-label-sm mb-1">Motif de modification (optionnel)</label>
                    <select class="form-select form-select-sm" id="needMotif">
                        <option value="">— Aucun —</option>
                        <option value="indisponible">Indisponible</option>
                        <option value="arret_maladie">Arrêt de maladie</option>
                        <option value="accident_travail">Accident de travail</option>
                    </select>
                </div>

                {# Notes #}
                <div class="mb-2">
                    <label class="form-label form-label-sm mb-1">Notes (optionnel)</label>
                    <input type="text" class="form-control form-control-sm" id="needNotes">
                </div>

                {# Répétition — visible uniquement pour création #}
                <div id="needRepeatSection" class="border-top pt-2" style="display:none;">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" id="needRepeat">
                        <label class="form-check-label" for="needRepeat" style="font-size:.82em;">Répéter sur d'autres jours</label>
                    </div>
                    <div id="needRepeatOptions" style="display:none;">
                        <div class="d-flex gap-1 flex-wrap mb-2" id="repeatDowButtons">
                            {% for dow, label in {1:'Lun',2:'Mar',3:'Mer',4:'Jeu',5:'Ven',6:'Sam',7:'Dim'} %}
                            <button type="button"
                                    class="btn btn-sm btn-outline-secondary repeat-dow-btn"
                                    data-value="{{ dow }}"
                                    style="min-width:44px; font-size:.8em; padding:2px 6px;">
                                {{ label }}
                            </button>
                            {% endfor %}
                        </div>
                        <div class="row g-1">
                            <div class="col-6">
                                <label class="form-label mb-0" style="font-size:.75em;">Du</label>
                                <input type="date" class="form-control form-control-sm" id="needRepeatFrom">
                            </div>
                            <div class="col-6">
                                <label class="form-label mb-0" style="font-size:.75em;">Au</label>
                                <input type="date" class="form-control form-control-sm" id="needRepeatTo">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer py-2 justify-content-between">
                <button type="button" class="btn btn-sm btn-outline-danger" id="needDeleteBtn" style="display:none;">
                    <i class="bi bi-trash"></i> Supprimer
                </button>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="button" class="btn btn-sm btn-warning text-white" id="needSaveBtn">
                        <i class="bi bi-save me-1"></i>Enregistrer
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modal envoi email client -->
<div class="modal fade" id="emailClientModal" tabindex="-1" aria-labelledby="emailClientModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="emailClientModalLabel">
                    <i class="bi bi-envelope me-1"></i> Envoyer le planning par email
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="emailClientLoading" class="text-center py-3">
                    <div class="spinner-border text-success" role="status">
                        <span class="visually-hidden">Chargement…</span>
                    </div>
                    <p class="mt-2 text-muted">Chargement des contacts…</p>
                </div>
                <div id="emailClientNoContacts" class="alert alert-warning d-none">
                    <i class="bi bi-exclamation-triangle me-1"></i>
                    Aucun contact avec adresse email n'est associé à ce client.
                </div>
                <form id="emailClientForm" method="post" action="" class="d-none">
                    <input type="hidden" name="_token" value="{{ csrf_token('email_send') }}">
                    <p class="mb-2">Sélectionnez les destinataires :</p>
                    <div id="emailClientContactsList"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                <button type="button" class="btn btn-success d-none" id="emailClientSubmitBtn">
                    <i class="bi bi-send me-1"></i> Envoyer
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block javascripts %}
{{ parent() }}
<script>
(function () {
    const saveUrl    = '{{ path('app_planning_client_need_save') }}';
    const deleteUrl  = (id) => `/planning/client-need/${id}/delete`;
    const searchUrl  = '{{ path('app_planning_agents_search') }}';

    // ── Ouverture du modal ──────────────────────────────────────────────────
    document.querySelectorAll('.need-cell-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const needId  = btn.dataset.needId || '';
            const date    = btn.dataset.date;
            const parts   = date.split('-');

            document.getElementById('needId').value        = needId;
            document.getElementById('needDate').value      = date;
            document.getElementById('needStartTime').value = btn.dataset.start || '';
            document.getElementById('needEndTime').value   = btn.dataset.end   || '';
            document.getElementById('needNotes').value     = '';
            document.getElementById('needMotif').value     = btn.dataset.motif || '';
            document.getElementById('needEntryId').value   = btn.dataset.entryId || '';
            document.getElementById('needAgentId').value   = '';
            document.getElementById('needAgentInput').value = btn.dataset.agentLabel || '';
            document.getElementById('needModalDate').textContent = `${parts[2]}/${parts[1]}/${parts[0]}`;
            document.getElementById('needDeleteBtn').style.display = needId ? 'inline-block' : 'none';
            document.getElementById('needAgentDropdown').style.display = 'none';

            // Répétition — visible uniquement en création
            const repeatSection = document.getElementById('needRepeatSection');
            const repeatOpts    = document.getElementById('needRepeatOptions');
            const repeatChk     = document.getElementById('needRepeat');
            if (!needId) {
                repeatSection.style.display = 'block';
                repeatChk.checked = false;
                repeatOpts.style.display = 'none';
                // Pré-sélectionner le jour de semaine de la date cliquée
                const d = new Date(date + 'T00:00:00');
                const phpDow = d.getDay() === 0 ? 7 : d.getDay();
                document.querySelectorAll('.repeat-dow-btn').forEach(btn => {
                    btn.classList.toggle('active', parseInt(btn.dataset.value) === phpDow);
                    btn.classList.toggle('btn-secondary', parseInt(btn.dataset.value) === phpDow);
                    btn.classList.toggle('btn-outline-secondary', parseInt(btn.dataset.value) !== phpDow);
                });
                // Plage = mois affiché
                const ry = {{ year }}, rm = {{ month }};
                const lastD = new Date(ry, rm, 0).getDate();
                const pad = n => String(n).padStart(2,'0');
                document.getElementById('needRepeatFrom').value = `${ry}-${pad(rm)}-01`;
                document.getElementById('needRepeatTo').value   = `${ry}-${pad(rm)}-${pad(lastD)}`;
            } else {
                repeatSection.style.display = 'none';
            }

            new bootstrap.Modal(document.getElementById('needModal')).show();
        });
    });

    // ── Toggle répétition ──────────────────────────────────────────────────
    document.getElementById('needRepeat').addEventListener('change', function () {
        document.getElementById('needRepeatOptions').style.display = this.checked ? 'block' : 'none';
    });

    // ── Toggle boutons jours ────────────────────────────────────────────────
    document.getElementById('repeatDowButtons').addEventListener('click', e => {
        const btn = e.target.closest('.repeat-dow-btn');
        if (!btn) return;
        const active = btn.classList.toggle('active');
        btn.classList.toggle('btn-secondary', active);
        btn.classList.toggle('btn-outline-secondary', !active);
    });

    // ── Autocomplétion agents ───────────────────────────────────────────────
    let searchTimer = null;
    const agentInput    = document.getElementById('needAgentInput');
    const agentIdInput  = document.getElementById('needAgentId');
    const dropdown      = document.getElementById('needAgentDropdown');

    agentInput.addEventListener('input', () => {
        clearTimeout(searchTimer);
        agentIdInput.value = '';

        const q = agentInput.value.trim();
        if (q.length < 2) { dropdown.style.display = 'none'; return; }

        const date  = document.getElementById('needDate').value;
        const start = document.getElementById('needStartTime').value;
        const end   = document.getElementById('needEndTime').value;

        let url = `${searchUrl}?q=${encodeURIComponent(q)}`;
        if (date)  url += `&date=${date}`;
        if (start) url += `&start=${start}`;
        if (end)   url += `&end=${end}`;

        searchTimer = setTimeout(async () => {
            const resp = await fetch(url);
            if (!resp.ok) return;
            const agents = await resp.json();

            dropdown.innerHTML = '';
            if (agents.length === 0) {
                dropdown.innerHTML = '<span class="list-group-item list-group-item-sm text-muted">Aucun résultat</span>';
            } else {
                agents.forEach(a => {
                    const item = document.createElement('button');
                    item.type = 'button';
                    item.disabled = a.unavailable;
                    item.className = 'list-group-item list-group-item-action list-group-item-sm py-1'
                        + (a.unavailable ? ' list-group-item-danger' : '');
                    item.innerHTML = a.unavailable
                        ? `${a.label} <small class="text-danger ms-1"><i class="bi bi-x-circle-fill"></i> Indisponible</small>`
                        : a.label;
                    if (!a.unavailable) {
                        item.addEventListener('click', () => {
                            agentIdInput.value = a.id;
                            agentInput.value   = a.label;
                            dropdown.style.display = 'none';
                        });
                    }
                    dropdown.appendChild(item);
                });
            }
            dropdown.style.display = 'block';
        }, 250);
    });

    // Fermer le dropdown si clic ailleurs
    document.addEventListener('click', e => {
        if (!agentInput.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.style.display = 'none';
        }
    });

    // ── Sauvegarde ─────────────────────────────────────────────────────────
    document.getElementById('needSaveBtn').addEventListener('click', async () => {
        const startTime = document.getElementById('needStartTime').value;
        const endTime   = document.getElementById('needEndTime').value;
        if (!startTime || !endTime) {
            alert('Veuillez renseigner les heures de début et de fin.');
            return;
        }
        const repeat     = document.getElementById('needRepeat').checked;
        const repeatDays = repeat
            ? [...document.querySelectorAll('.repeat-dow-btn.active')].map(b => parseInt(b.dataset.value))
            : null;
        if (repeat && (!repeatDays || repeatDays.length === 0)) {
            alert('Sélectionnez au moins un jour de la semaine pour la répétition.');
            return;
        }
        const payload = {
            site_id      : document.getElementById('needSiteId').value,
            date         : document.getElementById('needDate').value,
            need_id      : document.getElementById('needId').value    || null,
            entry_id     : document.getElementById('needEntryId').value || null,
            start_time   : startTime || null,
            end_time     : endTime   || null,
            agent_id     : document.getElementById('needAgentId').value   || null,
            notes        : document.getElementById('needNotes').value     || null,
            motif        : document.getElementById('needMotif').value     || null,
            repeat       : repeat,
            repeat_days  : repeatDays,
            repeat_from  : repeat ? document.getElementById('needRepeatFrom').value : null,
            repeat_to    : repeat ? document.getElementById('needRepeatTo').value   : null,
        };
        const resp = await fetch(saveUrl, {
            method : 'POST',
            headers: { 'Content-Type': 'application/json' },
            body   : JSON.stringify(payload),
        });
        if (resp.ok) { location.reload(); }
        else { alert('Erreur lors de la sauvegarde.'); }
    });

    // ── Suppression ────────────────────────────────────────────────────────
    document.getElementById('needDeleteBtn').addEventListener('click', async () => {
        const needId = document.getElementById('needId').value;
        if (!needId || !confirm('Supprimer ce besoin ?')) return;
        const resp = await fetch(deleteUrl(needId), { method: 'POST' });
        if (resp.ok) { location.reload(); }
        else { alert('Erreur lors de la suppression.'); }
    });
})();
</script>

<script>
(function () {
    const btnOpen    = document.getElementById('btnOpenEmailClientModal');
    const modal      = new bootstrap.Modal(document.getElementById('emailClientModal'));
    const loading    = document.getElementById('emailClientLoading');
    const noContacts = document.getElementById('emailClientNoContacts');
    const form       = document.getElementById('emailClientForm');
    const list       = document.getElementById('emailClientContactsList');
    const submitBtn  = document.getElementById('emailClientSubmitBtn');

    btnOpen.addEventListener('click', async () => {
        // Reset state
        loading.classList.remove('d-none');
        noContacts.classList.add('d-none');
        form.classList.add('d-none');
        submitBtn.classList.add('d-none');
        list.innerHTML = '';
        modal.show();

        try {
            const resp = await fetch(btnOpen.dataset.url);
            if (!resp.ok) throw new Error('Erreur réseau');
            const contacts = await resp.json();

            loading.classList.add('d-none');

            if (contacts.length === 0) {
                noContacts.classList.remove('d-none');
                return;
            }

            form.action = btnOpen.dataset.url;
            contacts.forEach(c => {
                const div = document.createElement('div');
                div.className = 'form-check mb-2';
                div.innerHTML = `
                    <input class="form-check-input email-contact-cb" type="checkbox"
                           name="contact_ids[]" value="${c.id}" id="contact_${c.id}" checked>
                    <label class="form-check-label" for="contact_${c.id}">
                        <strong>${c.name}</strong> <span class="text-muted">(${c.email})</span>
                    </label>`;
                list.appendChild(div);
            });

            form.classList.remove('d-none');
            submitBtn.classList.remove('d-none');
        } catch (e) {
            loading.classList.add('d-none');
            noContacts.textContent = 'Impossible de charger les contacts.';
            noContacts.classList.remove('d-none');
        }
    });

    submitBtn.addEventListener('click', () => {
        const checked = form.querySelectorAll('.email-contact-cb:checked');
        if (checked.length === 0) {
            alert('Veuillez sélectionner au moins un destinataire.');
            return;
        }
        form.submit();
    });
})();
</script>
{% endblock %}
