<?= $this->extend('layouts/layout') ?>

<?= $this->section('titulo') ?>Agenda<?= $this->endSection() ?>

<?= $this->section('estilos') ?>
<link rel="stylesheet" href="<?= base_url('css/tef/calendar.css?v='.time()) ?>">
<?= $this->endSection() ?>

<?= $this->section('contenido') ?>

<?php
$view = $view ?? 'month';
$date = $date ?? date('Y-m-d');
$baseDate = new DateTime($date);

$eventsByDate = [];
foreach ($events as $e) {
    $key = substr($e['Start_Date'], 0, 10);
    $eventsByDate[$key][] = $e;
}
?>

<div class="tef-panel">
    <!-- HEADER -->
    <div class="d-flex justify-content-between mb-4">
        <div>
            <h2>Agenda</h2>
            <p class="text-muted">Planeación de actividades</p>
        </div>

        <div class="d-flex gap-2 align-items-center">
            <div class="c-calendar-views">
                <a class="<?= $view==='month'?'active':'' ?>" href="<?= base_url("agenda?view=month&date=$date") ?>">Mes</a>
                <a class="<?= $view==='week'?'active':'' ?>" href="<?= base_url("agenda?view=week&date=$date") ?>">Semana</a>
                <a class="<?= $view==='day'?'active':'' ?>" href="<?= base_url("agenda?view=day&date=$date") ?>">Día</a>
            </div>
            <button id="newEventBtn" class="c-btn c-btn-primary">
                <i class="fas fa-plus me-1"></i> Nuevo evento
            </button>
        </div>
    </div>

    <!-- ===== VISTA MES ===== -->
    <?php if($view==='month'): ?>
        <?php
        $year = $baseDate->format('Y');
        $month = $baseDate->format('m');
        $first = strtotime("$year-$month-01");
        $start = date('N', $first);
        $days = date('t', $first);
        $day = 1;
        ?>
        <div class="c-month-calendar">
            <div class="c-calendar-weekdays">
                <div>Lun</div><div>Mar</div><div>Mié</div><div>Jue</div>
                <div>Vie</div><div>Sáb</div><div>Dom</div>
            </div>
            <div class="c-month-cells">
                <?php for($i=1; $i<=42; $i++): ?>
                    <?php if($i < $start || $day > $days): ?>
                        <div class="c-month-cell is-outside"></div>
                        <?php continue; ?>
                    <?php endif; ?>
                    <?php $current = "$year-$month-".str_pad($day,2,'0',STR_PAD_LEFT); ?>
                    <div class="c-month-cell <?= $current === date('Y-m-d') ? 'is-today' : '' ?>">
                        <div class="c-month-date"><?= $day ?></div>
                        <?php foreach($eventsByDate[$current]??[] as $e): ?>
                            <div class="c-calendar-event <?= $e['FK_User']!=session('PK_User')?'is-foreign':'' ?>"
                                 data-event='<?= json_encode($e, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>'>
                                <strong><?= esc($e['Title']) ?></strong>
                                <div class="c-event-user"><?= esc($e['Name'] ?? 'Usuario') ?></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php $day++; ?>
                <?php endfor; ?>
            </div>
        </div>

        <!-- AGENDA DEL DÍA (MOBILE) -->
        <div class="c-month-agenda" id="monthAgenda">
            <div class="c-month-agenda-header" id="monthAgendaTitle">
                Hoy
            </div>

            <div class="c-month-agenda-list" id="monthAgendaList">
                <!-- eventos dinámicos -->
            </div>
        </div>

    <?php endif; ?>

    <!-- ===== VISTA SEMANA ===== -->
    <?php if($view==='week'): ?>
        <?php
        $weekStart = (clone $baseDate)->modify('monday this week');
        $dayStart = 8; $dayEnd = 20; $hourHeight = 60;
        ?>
        <div class="c-week-calendar">
            <div class="c-week-header-row">
                <div class="c-week-hour-col"></div>
                <?php for($d=0; $d<7; $d++):
                    $dayObj = (clone $weekStart)->modify("+$d days"); ?>
                    <div class="c-week-day-header"><?= $dayObj->format('D d') ?></div>
                <?php endfor; ?>
            </div>

            <div class="c-week-body">
                <?php for($h=$dayStart; $h<=$dayEnd; $h++): ?>
                    <div class="c-week-hour-row">
                        <div class="c-week-hour"><?= sprintf('%02d:00', $h) ?></div>
                        <?php for($d=0; $d<7; $d++): ?><div class="c-week-cell"></div><?php endfor; ?>
                    </div>
                <?php endfor; ?>

                <div class="c-week-events-layer">
                    <?php foreach($events as $e):
                        $s = new DateTime($e['Start_Date']);
                        $en = new DateTime($e['End_Date']);
                        $dayIndex = $s->format('N') - 1;
                        $top = (($s->format('H')*60 + $s->format('i') - $dayStart*60)/60) * $hourHeight;
                        $height = (($en->getTimestamp() - $s->getTimestamp())/3600) * $hourHeight;
                        if($height <= 0) $height = 30;
                    ?>
                        <div class="c-week-event <?= $e['FK_User']!=session('PK_User')?'is-foreign':'' ?>"
                            data-event='<?= json_encode($e, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>'
                            style="
                                top: <?= $top ?>px;
                                height: <?= $height ?>px;
                                left: calc(80px + <?= $dayIndex ?>*(100% - 80px)/7);
                                width: calc((100% - 80px)/7 - 4px);
                            ">
                            <strong><?= esc($e['Title']) ?></strong>
                            <div class="c-event-user"><?= esc($e['Name'] ?? 'Usuario') ?></div>
                        </div>

                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- ===== VISTA DÍA ===== -->
    <?php if($view==='day'): ?>
        <?php $dayStart=8; $dayEnd=20; $hourHeight=60; ?>
        <div class="c-day-calendar">
            <div class="c-day-body">
                <?php for($h=$dayStart; $h<=$dayEnd; $h++): ?>
                    <div class="c-day-hour-row">
                        <div class="c-day-hour"><?= sprintf('%02d:00', $h) ?></div>
                        <div class="c-day-cell"></div>
                    </div>
                <?php endfor; ?>

                <div class="c-day-events">
                    <?php foreach($eventsByDate[$date]??[] as $e):
                        $s = new DateTime($e['Start_Date']);
                        $en = new DateTime($e['End_Date']);
                        $top = (($s->format('H')*60 + $s->format('i') - $dayStart*60)/60) * $hourHeight;
                        $height = (($en->getTimestamp() - $s->getTimestamp())/3600) * $hourHeight;
                        if($height <= 0) $height = 30;
                    ?>
                        <div class="c-day-event <?= $e['FK_User']!=session('PK_User')?'is-foreign':'' ?>"
                            data-event='<?= json_encode($e, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>'
                            style="top:<?= $top ?>px;height:<?= $height ?>px;">
                            <strong><?= esc($e['Title']) ?></strong>
                            <div class="c-event-user"><?= esc($e['Name'] ?? 'Usuario') ?></div>
                        </div>

                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>

</div>

<!-- ================= MODALES ================= -->
<!-- CREAR / EDITAR -->
<div class="modal fade" id="eventModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content tef-panel">

            <div class="modal-header border-0">
                <h5 class="tef-panel-title" id="eventModalTitle">Nuevo evento</h5>
                <button type="button"
                        class="btn-close"
                        data-bs-dismiss="modal"></button>
            </div>

            <form id="eventForm">
                <div class="modal-body">
                    <input type="hidden" name="All_Day" value="0">

                    <div class="tef-input-group mb-3">
                        <label>Asignar a usuario</label>
                        <select name="FK_User"
                                id="eventUser"
                                class="tef-input"
                                required>
                            <option value="">Selecciona un usuario</option>
                            <?php foreach ($users as $u): ?>
                                <option value="<?= $u['PK_User'] ?>">
                                    <?= esc($u['Name'] ?? $u['Email']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="tef-input-group mb-3">
                        <label>Título</label>
                        <input type="text"
                               name="Title"
                               id="eventTitle"
                               class="tef-input"
                               required>
                    </div>

                    <div class="tef-input-group mb-3">
                        <label>Descripción</label>
                        <textarea name="Description"
                                  id="eventDescription"
                                  class="tef-textarea"></textarea>
                    </div>

                    <div class="tef-form-row">
                        <div class="tef-input-group tef-input-md">
                            <label>Inicio</label>
                            <input type="datetime-local"
                                   name="Start_Date"
                                   id="eventStart"
                                   class="tef-input"
                                   required>
                        </div>

                        <div class="tef-input-group tef-input-md">
                            <label>Fin</label>
                            <input type="datetime-local"
                                   name="End_Date"
                                   id="eventEnd"
                                   class="tef-input"
                                   required>
                        </div>
                    </div>

                    <div class="tef-input-group mt-2">
                        <label>
                            <input type="checkbox"
                                   id="eventAllDay"
                                   class="me-2">
                            Evento de todo el día
                        </label>
                    </div>
                </div>

                <div class="modal-footer border-0">
                    <button type="button"
                            class="tef-btn tef-btn-muted"
                            data-bs-dismiss="modal">
                        Cancelar
                    </button>

                    <button type="submit"
                            class="tef-btn tef-btn-primary">
                        Guardar
                    </button>
                </div>
            </form>

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


<!-- DETALLE -->
<div class="modal fade" id="eventDetailModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content tef-panel p-0">

            <div class="modal-header border-0">
                <h5 class="tef-panel-title">Detalles del evento</h5>
                <button type="button"
                        class="btn-close"
                        data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body p-4">
                <p>
                    <strong>Título:</strong>
                    <span id="detailTitle"></span>
                </p>

                <p>
                    <strong>Descripción:</strong>
                    <span id="detailDescription"></span>
                </p>

                <p>
                    <strong>Inicio:</strong>
                    <span id="detailStart"></span>
                </p>

                <p>
                    <strong>Fin:</strong>
                    <span id="detailEnd"></span>
                </p>

                <p>
                    <strong>Todo el día:</strong>
                    <span id="detailAllDay"></span>
                </p>
                <p>
                    <strong>Asignado a:</strong>
                    <span id="user"></span>
                </p>
            </div>

            <div class="modal-footer border-0">
                <?php if (session('rol') == 1): ?>
                    <button id="editEventBtn"
                            class="tef-btn tef-btn-primary">
                        Editar
                    </button>

                    <button id="deleteEventBtn"
                            class="tef-btn tef-btn-danger">
                        Eliminar
                    </button>
                <?php endif; ?>

                <button type="button"
                        class="tef-btn tef-btn-muted"
                        data-bs-dismiss="modal">
                    Cerrar
                </button>
            </div>

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


<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
document.addEventListener('DOMContentLoaded', () => {

    const eventModal  = new bootstrap.Modal(document.getElementById('eventModal'));
    const detailModal = new bootstrap.Modal(document.getElementById('eventDetailModal'));
    const form        = document.getElementById('eventForm');
    const deleteBtn   = document.getElementById('deleteEventBtn');

    let current = null;

    const agendaTitle = document.getElementById('monthAgendaTitle');
    const agendaList  = document.getElementById('monthAgendaList');

    const eventsByDate = <?= json_encode($eventsByDate) ?>;
    const today        = "<?= date('Y-m-d') ?>";
    const currentUser  = <?= session('PK_User') ?>;

    /* =====================================================
       HELPERS
       ===================================================== */

    // FIX zona horaria YYYY-MM-DD
    function parseLocalDate(dateStr) {
        const [y, m, d] = dateStr.split('-');
        return new Date(y, m - 1, d);
    }

    function formatEventDate(start, end, allDay) {
        if (allDay == 1) return 'Todo el día';

        const s = new Date(start.replace(' ', 'T'));
        const e = new Date(end.replace(' ', 'T'));

        const date = s.toLocaleDateString('es-MX', {
            weekday: 'short',
            day: 'numeric',
            month: 'short'
        });

        const startTime = s.toLocaleTimeString('es-MX', {
            hour: '2-digit',
            minute: '2-digit'
        });

        const endTime = e.toLocaleTimeString('es-MX', {
            hour: '2-digit',
            minute: '2-digit'
        });

        return `${date} · ${startTime} – ${endTime}`;
    }

        /* =====================================================
    CLICK EN EVENTOS (DESKTOP)
    ===================================================== */
    if (window.innerWidth > 768) {
        document.querySelectorAll('.c-calendar-event').forEach(el => {
            el.addEventListener('click', () => {
                current = JSON.parse(el.dataset.event);

                document.getElementById('detailTitle').innerText        = current.Title;
                document.getElementById('detailDescription').innerText = current.Description || '—';
                document.getElementById('detailStart').innerText        =
                    formatEventDate(current.Start_Date, current.End_Date, current.All_Day);
                document.getElementById('detailEnd').innerText          = '';
                document.getElementById('detailAllDay').innerText       = current.All_Day == 1 ? 'Sí' : 'No';
                document.getElementById('user').innerText               = current.Name ?? 'Usuario';

                detailModal.show();
            });
        });
    }


    /* =====================================================
       AGENDA MOBILE (VISTA MES)
       ===================================================== */

    function renderAgenda(date) {
        const events = eventsByDate[date] || [];
        const dateObj = parseLocalDate(date);

        agendaTitle.innerText = dateObj.toLocaleDateString('es-MX', {
            weekday: 'long',
            day: 'numeric',
            month: 'long'
        });

        if (!events.length) {
            agendaList.innerHTML =
                `<p class="text-muted text-center">No hay eventos</p>`;
            return;
        }

        agendaList.innerHTML = events.map(e => `
            <div class="c-calendar-event ${e.FK_User != currentUser ? 'is-foreign' : ''}"
                 data-event='${JSON.stringify(e)}'>
                <strong>${e.Title}</strong><br>
                <small class="text-muted">${e.Name ?? 'Usuario'}</small><br>
                <small class="text-muted">
                    ${formatEventDate(e.Start_Date, e.End_Date, e.All_Day)}
                </small>
            </div>
        `).join('');
    }

    /* Inicializar agenda en mobile */
    if (window.innerWidth <= 768) {
        renderAgenda(today);

        document.querySelectorAll('.c-month-cell').forEach(cell => {
            cell.addEventListener('click', () => {
                const dayEl = cell.querySelector('.c-month-date');
                if (!dayEl) return;

                const day = dayEl.innerText.padStart(2, '0');
                const date = "<?= $year ?>-<?= $month ?>-" + day;
                renderAgenda(date);
            });
        });
    }

    /* =====================================================
       CLICK EN EVENTO (AGENDA)
       ===================================================== */
    agendaList?.addEventListener('click', e => {
        const eventEl = e.target.closest('.c-calendar-event');
        if (!eventEl) return;

        current = JSON.parse(eventEl.dataset.event);

        document.getElementById('detailTitle').innerText       = current.Title;
        document.getElementById('detailDescription').innerText = current.Description || '—';
        document.getElementById('detailStart').innerText       =
            formatEventDate(current.Start_Date, current.End_Date, current.All_Day);
        document.getElementById('detailEnd').innerText         = '';
        document.getElementById('detailAllDay').innerText      = current.All_Day == 1 ? 'Sí' : 'No';
        document.getElementById('user').innerText              = current.Name ?? 'Usuario';

        detailModal.show();
    });

    /* =====================================================
       NUEVO EVENTO
       ===================================================== */
    document.getElementById('newEventBtn').onclick = () => {
        form.reset();
        form.action = "<?= base_url('agenda/save') ?>";
        document.getElementById('eventModalTitle').innerText = 'Nuevo evento';
        eventModal.show();
    };

    /* =====================================================
       EDITAR / ELIMINAR
       ===================================================== */
    document.getElementById('editEventBtn').onclick = () => {
        if (!current) return;

        detailModal.hide();
        form.action = `<?= base_url('agenda/update') ?>/${current.PK_Event}`;

        form.FK_User.value     = current.FK_User;
        form.Title.value       = current.Title;
        form.Description.value = current.Description;
        form.Start_Date.value  = current.Start_Date.replace(' ', 'T');
        form.End_Date.value    = current.End_Date.replace(' ', 'T');
        form.All_Day.value     = current.All_Day;
        document.getElementById('eventAllDay').checked = current.All_Day == 1;

        document.getElementById('eventModalTitle').innerText = 'Editar evento';
        eventModal.show();
    };

    deleteBtn.onclick = () => {
        if (!current) return;

        Swal.fire({
            title: '¿Eliminar este evento?',
            text: 'Esta acción no se puede deshacer',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonText: 'Cancelar',
            confirmButtonText: 'Sí, eliminar'
        }).then(result => {
            if (result.isConfirmed) {
                fetch(`<?= base_url('agenda/delete') ?>/${current.PK_Event}`, {
                    method: 'POST'
                })
                .then(r => r.json())
                .then(d => {
                    if (d.status === 'ok') {
                        Swal.fire('Eliminado', d.message, 'success')
                            .then(() => location.reload());
                    } else {
                        Swal.fire('Error', d.message, 'error');
                    }
                });
            }
        });
    };

    /* =====================================================
       FORM
       ===================================================== */
    document.getElementById('eventAllDay').onchange = e => {
        form.All_Day.value = e.target.checked ? 1 : 0;
    };

    form.onsubmit = e => {
        e.preventDefault();

        fetch(form.action, {
            method: 'POST',
            body: new FormData(form)
        })
        .then(r => r.json())
        .then(d => {
            if (d.status === 'ok') {
                Swal.fire('Listo', d.message, 'success')
                    .then(() => location.reload());
            } else {
                Swal.fire('Error', d.message, 'error');
            }
        });
    };
    
    /* =====================================================
    SWIPE CAMBIO DE MES (MOBILE + PC)
    ===================================================== */

    const calendar = document.querySelector('.c-month-calendar');
    if (!calendar) return;

    let startX = 0;
    let endX = 0;
    let isDragging = false;
    const SWIPE_THRESHOLD = 80; // px mínimos

    const baseDate = new Date("<?= $year ?>-<?= $month ?>-01");

    /* ====== NAVEGACIÓN ====== */
    function changeMonth(direction) {
        const newDate = new Date(baseDate);
        newDate.setMonth(baseDate.getMonth() + direction);

        const y = newDate.getFullYear();
        const m = String(newDate.getMonth() + 1).padStart(2, '0');

        window.location.href =
            `<?= base_url('agenda') ?>?view=month&date=${y}-${m}-01`;
    }

    /* ====== TOUCH (MOBILE) ====== */
    calendar.addEventListener('touchstart', e => {
        startX = e.touches[0].clientX;
    });

    calendar.addEventListener('touchend', e => {
        endX = e.changedTouches[0].clientX;
        handleSwipe();
    });

    /* ====== MOUSE / TRACKPAD (PC) ====== */
    calendar.addEventListener('mousedown', e => {
        isDragging = true;
        startX = e.clientX;
    });

    calendar.addEventListener('mouseup', e => {
        if (!isDragging) return;
        endX = e.clientX;
        isDragging = false;
        handleSwipe();
    });

    calendar.addEventListener('mouseleave', () => {
        isDragging = false;
    });

    /* ====== LÓGICA SWIPE ====== */
    function handleSwipe() {
        const diff = endX - startX;

        if (Math.abs(diff) < SWIPE_THRESHOLD) return;

        if (diff > 0) {
            // 👉 Swipe derecha → mes anterior
            changeMonth(-1);
        } else {
            // 👈 Swipe izquierda → mes siguiente
            changeMonth(1);
        }
    }

});
</script>


<?= $this->endSection() ?>
