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

{% set jours_fr = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'] %}

{% block title %}Mon Agenda — {{ monthName|capitalize }} {{ year }}{% endblock %}

{% block body %}
<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">Mon Agenda — Indisponibilités</h4>
            <div class="page-title-right">
                <ol class="breadcrumb m-0">
                    <li class="breadcrumb-item"><a href="{{ path('app_planning_agent_show', {id: agent.id, year: year, month: month}) }}">Mon Planning</a></li>
                    <li class="breadcrumb-item active">Mon Agenda</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-9">
        <div class="card">
            <div class="card-body">

                <!-- Navigation mois -->
                <div class="d-flex align-items-center justify-content-between mb-4">
                    <a href="{{ path('app_agent_agenda_month', {year: prevYear, month: prevMonth}) }}"
                       class="btn btn-outline-secondary btn-sm">
                        <i class="bi bi-chevron-left"></i>
                    </a>
                    <h5 class="mb-0 fw-bold">{{ monthName|upper }} {{ year }}</h5>
                    <a href="{{ path('app_agent_agenda_month', {year: nextYear, month: nextMonth}) }}"
                       class="btn btn-outline-secondary btn-sm">
                        <i class="bi bi-chevron-right"></i>
                    </a>
                </div>

                <!-- Grille calendrier -->
                <div class="table-responsive">
                    <table class="table table-bordered text-center mb-0" id="agendaCalendar">
                        <thead class="table-light">
                            <tr>
                                {% for j in jours_fr %}
                                    <th class="py-2" style="width:14.28%;">{{ j }}</th>
                                {% endfor %}
                            </tr>
                        </thead>
                        <tbody>
                            {% set firstDow = daysInMonth[0].format('N')|number_format %}
                            {% set cellIndex = 0 %}
                            <tr>
                                {# Cellules vides avant le 1er jour #}
                                {% for i in 1..(firstDow - 1) %}
                                    <td class="bg-light"></td>
                                    {% set cellIndex = cellIndex + 1 %}
                                {% endfor %}

                                {% for day in daysInMonth %}
                                    {% set dateKey = day.format('Y-m-d') %}
                                    {% set dow = day.format('N')|number_format %}
                                    {% set isWeekend = dow >= 6 %}
                                    {% set dayUnavails = unavailabilities[dateKey]|default([]) %}
                                    {% set isUnavail = dayUnavails|length > 0 %}

                                    <td class="p-1 align-top day-cell {{ isWeekend ? 'bg-light' : '' }} {{ isUnavail ? 'table-danger' : '' }}"
                                        data-date="{{ dateKey }}"
                                        style="height: 72px; cursor: pointer; position: relative;">
                                        <div class="d-flex justify-content-between align-items-start px-1 pt-1">
                                            <span class="fw-bold" style="font-size:.9em;">{{ day.format('d') }}</span>
                                            {% if isUnavail %}
                                                <span class="badge bg-danger" style="font-size:.65em;">Indispo</span>
                                            {% endif %}
                                        </div>
                                        {% for u in dayUnavails %}
                                            <div class="mt-1">
                                                {% if u.allDay %}
                                                    <small class="text-danger fw-semibold" style="font-size:.7em;">Toute la journée</small>
                                                {% else %}
                                                    <small class="text-danger" style="font-size:.7em;">
                                                        {{ u.startTime|date('H:i') }}–{{ u.endTime|date('H:i') }}
                                                    </small>
                                                {% endif %}
                                                {% if u.reason %}
                                                    <small class="d-block text-muted" style="font-size:.65em;">{{ u.reason }}</small>
                                                {% endif %}
                                            </div>
                                        {% endfor %}
                                        <!-- IDs pour suppression -->
                                        {% for u in dayUnavails %}
                                            <input type="hidden" class="unavail-id" value="{{ u.id }}">
                                        {% endfor %}
                                    </td>

                                    {% set cellIndex = cellIndex + 1 %}
                                    {% if cellIndex % 7 == 0 and not loop.last %}
                                        </tr><tr>
                                    {% endif %}
                                {% endfor %}

                                {# Cellules vides après le dernier jour #}
                                {% set remaining = 7 - (cellIndex % 7) %}
                                {% if remaining < 7 %}
                                    {% for i in 1..remaining %}
                                        <td class="bg-light"></td>
                                    {% endfor %}
                                {% endif %}
                            </tr>
                        </tbody>
                    </table>
                </div>

            </div>
        </div>
    </div>

    <!-- Légende + aide -->
    <div class="col-lg-3">
        <div class="card">
            <div class="card-body">
                <h6 class="card-title">Légende</h6>
                <div class="d-flex align-items-center gap-2 mb-2">
                    <div style="width:20px; height:20px; background:#f8d7da; border:1px solid #f5c2c7; border-radius:3px;"></div>
                    <small>Indisponible</small>
                </div>
                <div class="d-flex align-items-center gap-2 mb-3">
                    <div style="width:20px; height:20px; background:#f8f9fa; border:1px solid #dee2e6; border-radius:3px;"></div>
                    <small>Disponible</small>
                </div>
                <hr>
                <p class="text-muted" style="font-size:.85em;">
                    <i class="bi bi-info-circle me-1"></i>
                    Cliquez sur un jour pour marquer votre indisponibilité. Cliquez à nouveau pour la supprimer.
                </p>
            </div>
        </div>
    </div>
</div>

<!-- Modal ajout indisponibilité -->
<div class="modal fade" id="unavailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header py-2 bg-danger text-white">
                <h6 class="modal-title"><i class="bi bi-calendar-x me-1"></i> Indisponibilité — <span id="unavailModalDate"></span></h6>
                <button type="button" class="btn-close btn-close-white btn-sm" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="unavailDate">

                <div class="mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="unavailAllDay" checked>
                        <label class="form-check-label" for="unavailAllDay">Toute la journée</label>
                    </div>
                </div>

                <div id="unavailTimeFields" style="display:none;">
                    <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="unavailStart">
                    </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="unavailEnd">
                    </div>
                </div>

                <div class="mb-0">
                    <label class="form-label form-label-sm mb-1">Motif</label>
                    <select class="form-select form-select-sm" id="unavailReason">
                        <option value="">— Sélectionner —</option>
                        <option value="indisponibilite">Indisponibilité</option>
                        <option value="accident_travail">Accident du travail</option>
                        <option value="arret_travail">Arrêt de travail</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer py-2">
                <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Annuler</button>
                <button type="button" class="btn btn-sm btn-danger" id="unavailSaveBtn">
                    <i class="bi bi-check-circle me-1"></i>Confirmer
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block javascripts %}
{{ parent() }}
<script>
(function () {
    const addUrl    = '{{ path('app_agent_unavailability_add') }}';
    const deleteUrl = (id) => `/agenda/unavailability/${id}/delete`;

    // Toggle plages horaires
    document.getElementById('unavailAllDay').addEventListener('change', function () {
        document.getElementById('unavailTimeFields').style.display = this.checked ? 'none' : 'block';
    });

    // Clic sur une cellule jour
    document.querySelectorAll('.day-cell').forEach(cell => {
        cell.addEventListener('click', async () => {
            const ids = [...cell.querySelectorAll('.unavail-id')].map(i => i.value);

            // Si déjà indispo → supprimer
            if (ids.length > 0) {
                if (!confirm('Supprimer cette indisponibilité ?')) return;
                for (const id of ids) {
                    await fetch(deleteUrl(id), { method: 'POST' });
                }
                location.reload();
                return;
            }

            // Sinon → ouvrir modal
            const date  = cell.dataset.date;
            const parts = date.split('-');
            document.getElementById('unavailDate').value = date;
            document.getElementById('unavailModalDate').textContent = `${parts[2]}/${parts[1]}/${parts[0]}`;
            document.getElementById('unavailAllDay').checked = true;
            document.getElementById('unavailTimeFields').style.display = 'none';
            document.getElementById('unavailReason').selectedIndex = 0;
            document.getElementById('unavailStart').value  = '';
            document.getElementById('unavailEnd').value    = '';

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

    // Sauvegarde
    document.getElementById('unavailSaveBtn').addEventListener('click', async () => {
        const allDay = document.getElementById('unavailAllDay').checked;
        const payload = {
            date     : document.getElementById('unavailDate').value,
            all_day  : allDay,
            reason   : document.getElementById('unavailReason').value || null,
            start_time: allDay ? null : document.getElementById('unavailStart').value || null,
            end_time  : allDay ? null : document.getElementById('unavailEnd').value   || null,
        };

        const resp = await fetch(addUrl, {
            method : 'POST',
            headers: { 'Content-Type': 'application/json' },
            body   : JSON.stringify(payload),
        });

        if (resp.ok) { location.reload(); }
        else { alert('Erreur lors de l\'enregistrement.'); }
    });
})();
</script>
{% endblock %}
