<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once '../../services/crm/CrmService.php';

require_login();
require_permission('module.crm');

$page_title = 'Calendario Operativo';

$crm = new CrmService();
$assignableUsers = $crm->getAssignableUsers();
$currentUser = current_user();

// Control de renderizado SPA tradicional
$is_spa = isset($_SERVER['HTTP_X_SPA_REQUEST']) && $_SERVER['HTTP_X_SPA_REQUEST'] === 'true';

if (!$is_spa) {
    require_once '../../layouts/header.php';
    require_once '../../layouts/sidebar.php';
}
?>

<main class="app-main no-scroll-main">
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content flex-content">
        
        <!-- Cabecera homologada con Filtros y Botón de Acción -->
        <div class="page-header header-responsive" style="flex-shrink: 0; margin-bottom: 16px;">
            <div class="page-header-content">
                <span class="label">CRM · Gestión de Tiempos</span>
                <h1>Calendario Operativo</h1>
                <p class="text-secondary text-truncate" style="max-width: 100%;">Vista operativa y asignación de carga de trabajo del equipo.</p>
            </div>

            <div class="cluster top-actions-cluster">
                <button type="button" class="btn btn-outline btn-icon-mobile" id="btnToggleFilters" title="Filtrar eventos">
                    <i data-lucide="sliders-horizontal"></i>
                    <span class="mobile-hidden">Filtros</span>
                </button>

                <button type="button" class="btn btn-primary btn-icon-mobile" onclick="window.openManualEventModal(null)" title="Nuevo evento">
                    <i data-lucide="plus"></i>
                    <span class="mobile-hidden">Nuevo evento</span>
                </button>
            </div>
        </div>

        <!-- Barra de Filtros Colapsable -->
        <div class="filter-bar-container is-collapsed" id="calendarFiltersBar" style="flex-shrink: 0;">
            <div class="form-field" style="flex: 1; min-width: 0; margin: 0;">
                <select id="calFilterArea" class="select" style="width: 100%;">
                    <option value="">Todas las áreas</option>
                    <option value="comercial">Comercial</option>
                    <option value="administracion">Administración</option>
                    <option value="operaciones">Operaciones</option>
                </select>
            </div>
            <div class="form-field" style="flex: 1; min-width: 0; margin: 0;">
                <select id="calFilterUser" class="select" style="width: 100%;">
                    <option value="">Todos los ejecutivos</option>
                    <?php foreach ($assignableUsers as $user): ?>
                        <option value="<?php echo (int)$user['id']; ?>"><?php echo safe_text($user['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <!-- Contenedor Maestro Adaptable sin Scroll -->
        <div class="card flex-card" style="flex: 1 1 0%; min-height: 0; display: flex; flex-direction: column; border-radius: var(--radius-xl); border: 1px solid var(--border-default); background: var(--surface-1); padding: var(--space-4); overflow: hidden;">
            <div class="card-body" style="padding: 0; flex: 1 1 0%; min-height: 0; display: flex; flex-direction: column; height: 100%; overflow: hidden;">
                <div id="calendar-workspace" style="flex: 1 1 0%; min-height: 0; height: 100%; width: 100%;">
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; width: 100%; color: var(--text-muted);">
                        <i data-lucide="loader" class="spin-icon" style="width: 32px; height: 32px; margin-bottom: 12px;"></i>
                        <p>Cargando espacio de trabajo...</p>
                    </div>
                </div>
            </div>
        </div>

    </section>

    <!-- MODAL CENTRAL PARA CREACIÓN MANUAL DE EVENTOS -->
    <div id="manualEventModal" class="product-modal-backdrop" style="z-index: 10000;">
        <div class="product-modal-box" style="max-width: 520px;">
            <div class="product-modal-header">
                <div>
                    <h2 class="h3">Crear Nuevo Evento</h2>
                    <span class="text-secondary text-sm">Registra una actividad en la agenda interna y Google Calendar</span>
                </div>
                <button type="button" class="icon-btn" onclick="window.closeManualEventModal()"><i data-lucide="x"></i></button>
            </div>
            <div class="product-modal-body">
                <form id="form-create-manual-event" action="/modules/calendar/event_store.php" method="POST" style="margin: 0;">
                    <div class="form-grid form-grid-2">
                        
                        <div class="form-field form-field-full is-required">
                            <label class="label">Título del evento</label>
                            <input type="text" name="title" class="input" required placeholder="Ej: Reunión técnica o motivo interno">
                        </div>

                        <div class="form-field is-required">
                            <label class="label">Tipo de evento</label>
                            <select name="event_type" class="select" required>
                                <option value="accion">Acción (Llamada/Reunión)</option>
                                <option value="libre">Evento Libre (Motivos diversos)</option>
                                <option value="cierre">Cierre Estimado</option>
                                <option value="vencimiento">Vencimiento de Pago</option>
                                <option value="pago">Pago Recibido</option>
                            </select>
                        </div>

                        <div class="form-field is-required">
                            <label class="label">Ejecutivo responsable</label>
                            <select name="owner_user_id" class="select" required>
                                <option value="">Seleccionar responsable</option>
                                <?php foreach ($assignableUsers as $user): ?>
                                    <option value="<?php echo (int)$user['id']; ?>" <?php echo $user['id'] == ($currentUser['id'] ?? 0) ? 'selected' : ''; ?>>
                                        <?php echo safe_text($user['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-field is-required">
                            <label class="label">Fecha de inicio</label>
                            <input type="date" name="start_date" id="evtStartDate" class="input" required>
                        </div>

                        <div class="form-field time-control-group">
                            <label class="label">Hora de inicio</label>
                            <input type="time" name="start_time" value="10:00" class="input">
                        </div>

                        <div class="form-field time-control-group">
                            <label class="label">Hora de término</label>
                            <input type="time" name="end_time" value="10:30" class="input">
                        </div>

                        <div class="form-field">
                            <label class="label mobile-hidden" style="visibility: hidden;">&nbsp;</label>
                            <label style="cursor: pointer; display: flex; align-items: center; gap: 12px; height: 40px; padding: 0 14px; background: var(--surface-2); border: 1px solid var(--border-default); border-radius: var(--radius-md); user-select: none; transition: background 0.2s;">
                                <div class="custom-switch">
                                    <input type="checkbox" name="is_all_day" value="1" id="evtIsAllDay" onchange="window.toggleTimeFields(this.checked)">
                                    <span class="custom-switch-slider"></span>
                                </div>
                                <span style="font-size: 0.9rem; font-weight: 600; color: var(--text-primary);">Todo el día</span>
                            </label>
                        </div>

                    </div>
                </form>
            </div>
            <div class="product-modal-footer">
                <button type="button" class="btn btn-outline" onclick="window.closeManualEventModal()">Cancelar</button>
                <button type="submit" form="form-create-manual-event" class="btn btn-primary" id="btnSaveManualEvent">
                    <i data-lucide="save"></i><span>Agendar Evento</span>
                </button>
            </div>
        </div>
    </div>

    <style>
        /* Estilos del Switch */
        .custom-switch { position: relative; display: inline-block; width: 40px; height: 22px; flex-shrink: 0; }
        .custom-switch input { opacity: 0; width: 0; height: 0; }
        .custom-switch-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: var(--surface-3); transition: .2s; border-radius: 22px; border: 1px solid var(--border-default); }
        .custom-switch-slider:before { position: absolute; content: ""; height: 14px; width: 14px; left: 3px; bottom: 3px; background-color: var(--text-muted); transition: .2s; border-radius: 50%; }
        .custom-switch input:checked + .custom-switch-slider { background-color: var(--color-primary); border-color: var(--color-primary); }
        .custom-switch input:checked + .custom-switch-slider:before { transform: translateX(18px); background-color: #ffffff; }

        /* Estilo Barra de Filtros Homologada */
        .filter-bar-container { position: relative; z-index: 50; display: flex; gap: 12px; flex-wrap: nowrap; padding: 12px 16px; background: var(--surface-1); border: 1px solid var(--border-default); border-radius: var(--radius-xl); margin-bottom: 16px; align-items: center; }
        .filter-bar-container.is-collapsed { display: none !important; }

        /* 🚀 ESTILOS DE ALTURAS Y FLUIDEZ (CONTENCIÓN TOTAL EN MOBILE Y DESKTOP) */
        .no-scroll-main { height: 100vh !important; height: 100dvh !important; overflow: hidden !important; display: flex; flex-direction: column; }
        .flex-content { flex: 1 1 0% !important; min-height: 0 !important; display: flex !important; flex-direction: column !important; padding-bottom: 24px !important; overflow: hidden !important; }
        .flex-card { flex: 1 1 0% !important; min-height: 0 !important; height: 100% !important; display: flex !important; flex-direction: column !important; overflow: hidden !important; }
        
        @media (max-width: 760px) {
            .flex-content { padding: 16px 16px 24px 16px !important; gap: 12px !important; }
            
            .page-header { margin: 0 !important; display: flex !important; flex-direction: row !important; flex-wrap: nowrap !important; align-items: center !important; justify-content: space-between !important; width: 100%; flex-shrink: 0; }
            .page-header-content { flex: 1; min-width: 0; padding-right: 12px; }
            .page-header-content h1 { font-size: 1.35rem !important; margin-bottom: 4px !important; }
            .top-actions-cluster { width: auto !important; justify-content: flex-end !important; display: flex; gap: 8px; flex-shrink: 0; }
            .btn-icon-mobile { padding: 0 !important; width: 42px !important; height: 42px !important; display: flex; align-items: center; justify-content: center; }
            
            .filter-bar-container { display: grid !important; grid-template-columns: 1fr 1fr !important; gap: 8px !important; width: 100%; padding: 12px !important; margin: 0 !important; box-sizing: border-box; flex-shrink: 0; }
            .filter-bar-container .form-field { width: 100% !important; margin: 0 !important; }
            .filter-bar-container select.select { padding-left: 10px !important; padding-right: 28px !important; font-size: 0.85rem; }
            
            /* En móvil la tarjeta también respeta la contención del flex */
            .flex-card { padding: 12px !important; border: 1px solid var(--border-default) !important; background: var(--surface-1) !important; border-radius: var(--radius-xl) !important; margin: 0 !important; box-sizing: border-box; width: 100%; }
        }

        /* REGLAS DEL TOOLBAR DE FULLCALENDAR */
        .fc { font-family: inherit; --fc-border-color: var(--border-subtle); --fc-page-bg-color: transparent; height: 100% !important; }
        
        .fc .fc-toolbar { 
            display: flex !important; 
            flex-direction: row !important; 
            flex-wrap: wrap !important; 
            justify-content: space-between !important; 
            align-items: center !important; 
            gap: 12px !important; 
            margin-bottom: var(--space-4) !important; 
            flex-shrink: 0;
        }
        
        .fc .fc-toolbar-chunk:nth-child(1) { display: flex !important; align-items: center; justify-content: flex-start !important; }
        .fc .fc-toolbar-chunk:nth-child(2) { display: flex !important; align-items: center; justify-content: center !important; }
        .fc .fc-toolbar-chunk:nth-child(3) { display: flex !important; align-items: center; justify-content: flex-end !important; gap: 8px; }

        @media (max-width: 760px) {
            .fc .fc-toolbar { margin-bottom: 12px !important; }
            .fc .fc-toolbar-chunk:nth-child(1) { flex: 0 0 100% !important; justify-content: center !important; text-align: center !important; margin-bottom: 4px; }
            .fc .fc-toolbar-chunk:nth-child(2) { flex: 1 !important; justify-content: flex-start !important; }
            .fc .fc-toolbar-chunk:nth-child(3) { flex: 1 !important; justify-content: flex-end !important; }
            
            .fc .fc-toolbar-title { font-size: 1.3rem !important; }
            .fc .fc-button-primary { padding: 6px 10px !important; font-size: 0.75rem !important; }
            .fc .fc-button-group { gap: 4px !important; }
        }

        .fc .fc-toolbar-title { font-size: 1.25rem !important; font-weight: 700; color: var(--text-primary); text-transform: capitalize; }
        .fc .fc-button-group { gap: 8px; display: inline-flex; background: transparent !important; }
        .fc .fc-button-group > .fc-button { border-radius: 8px !important; margin-left: 0 !important; }
        
        .fc .fc-button-primary { background-color: var(--surface-3) !important; border-color: var(--border-default) !important; color: var(--text-primary) !important; text-transform: capitalize; border-radius: 8px !important; font-size: 0.82rem; font-weight: 500; padding: 6px 12px; }
        .fc .fc-button-primary:hover { background-color: var(--surface-4) !important; border-color: var(--border-strong) !important; }
        .fc .fc-button-active { background-color: var(--color-primary-soft) !important; color: var(--color-primary) !important; border-color: var(--color-primary) !important; font-weight: 600; }
        
        .fc th { background: var(--surface-2); padding: 10px 0 !important; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.5px; }
        .fc-theme-standard td, .fc-theme-standard th { border-color: var(--border-subtle) !important; }
        .fc-event { cursor: pointer; padding: 4px 6px; border-radius: var(--radius-md); font-size: 0.78rem; box-shadow: var(--shadow-sm); border: 1px solid transparent; margin: 1px 2px !important; }
        .fc-day-today { background: color-mix(in srgb, var(--color-primary) 4%, transparent) !important; }
        .fc-event-title { font-weight: 600; }
        .fc .fc-scroller-harness { min-height: 0; }
    </style>

    <script>
    (function() {
        if(window.lucide) window.lucide.createIcons();

        let calendarInstance = null;
        const bindSpa = window.ICY_SPA_ON || function(target, eventName, handler, options) {
            if (!target) return function() {};
            target.addEventListener(eventName, handler, options || false);
            return function() { target.removeEventListener(eventName, handler, options || false); };
        };
        const registerSpaCleanup = window.ICY_SPA_REGISTER_CLEANUP || function() {};
        const spaTimeout = window.ICY_SPA_SET_TIMEOUT || function(callback, delay) { return window.setTimeout(callback, delay); };

        registerSpaCleanup(function() {
            if (calendarInstance && typeof calendarInstance.destroy === 'function') {
                calendarInstance.destroy();
            }
            calendarInstance = null;
            delete window.openManualEventModal;
            delete window.closeManualEventModal;
            delete window.toggleTimeFields;
        });

        function ensureFullCalendarThenInit() {
            if (window.FullCalendar) {
                initCalendarInstance();
            } else {
                var script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js';
                script.onload = function() {
                    var loc = document.createElement('script');
                    loc.src = 'https://cdn.jsdelivr.net/npm/@fullcalendar/core@6.1.15/locales/es.global.min.js';
                    loc.onload = initCalendarInstance;
                    document.head.appendChild(loc);
                };
                document.head.appendChild(script);
            }
        }

        function initCalendarInstance() {
            var calendarEl = document.getElementById('calendar-workspace');
            if (!calendarEl) return;
            calendarEl.innerHTML = ''; 

            // 🚀 Siempre 100% para que el scroll lo maneje internamente FullCalendar
            calendarInstance = new FullCalendar.Calendar(calendarEl, {
                initialView: window.innerWidth < 768 ? 'timeGridDay' : 'dayGridMonth',
                locale: 'es', 
                firstDay: 1, 
                timeZone: 'America/Santiago',
                height: '100%',
                selectable: true,
                selectLongPressDelay: 0, 
                handleWindowResize: true,
                headerToolbar: {
                    left: 'title',
                    center: 'prev,next today',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay' 
                },
                buttonText: { today: 'Hoy', month: 'Mes', week: 'Semana', day: 'Día' },
                events: function(info, successCallback, failureCallback) {
                    var area = document.getElementById('calFilterArea').value;
                    var userId = document.getElementById('calFilterUser').value;
                    var url = '/modules/calendar/api_events.php?start=' + info.startStr.substring(0,10) + '&end=' + info.endStr.substring(0,10) + '&area=' + area + '&user_id=' + userId;

                    fetch(url)
                        .then(res => res.json())
                        .then(data => successCallback(data))
                        .catch(err => failureCallback(err));
                },
                select: function(info) {
                    spaTimeout(() => {
                        if (typeof window.openManualEventModal === 'function') {
                            window.openManualEventModal(info.startStr.substring(0, 10));
                        }
                    }, 200);
                    calendarInstance.unselect();
                },
                eventClick: function(info) {
                    var oppId = info.event.extendedProps.opportunity_id;
                    spaTimeout(() => {
                        if (oppId && typeof window.openOppViewModal === 'function') {
                            window.openOppViewModal(null, oppId);
                        } else if (oppId) {
                            window.ICY_SPA_GO ? window.ICY_SPA_GO('/modules/crm/opportunity.php?id=' + oppId) : (window.location.href = '/modules/crm/opportunity.php?id=' + oppId);
                        }
                    }, 150);
                }
            });

            calendarInstance.render();

            const areaFilter = document.getElementById('calFilterArea');
            const userFilter = document.getElementById('calFilterUser');
            if (areaFilter) bindSpa(areaFilter, 'change', () => calendarInstance && calendarInstance.refetchEvents());
            if (userFilter) bindSpa(userFilter, 'change', () => calendarInstance && calendarInstance.refetchEvents());
        }

        // CONTROL DE FILTROS 
        const btnToggleFilters = document.getElementById('btnToggleFilters');
        const filtersBar = document.getElementById('calendarFiltersBar');
        
        if (btnToggleFilters && filtersBar) {
            bindSpa(btnToggleFilters, 'click', function(e) {
                e.preventDefault();
                filtersBar.classList.toggle('is-collapsed');
                btnToggleFilters.classList.toggle('is-active');
                if (calendarInstance) {
                    spaTimeout(() => calendarInstance && calendarInstance.updateSize(), 50);
                }
            });
        }

        // LÓGICA DE CONTROL DEL MODAL MANUAL
        window.openManualEventModal = function(prefilledDate) {
            var m = document.getElementById('manualEventModal');
            if (m) {
                document.getElementById('form-create-manual-event').reset();
                window.toggleTimeFields(false);
                
                if (prefilledDate) {
                    document.getElementById('evtStartDate').value = prefilledDate;
                } else {
                    document.getElementById('evtStartDate').value = new Date().toISOString().substring(0, 10);
                }
                
                m.style.display = 'flex';
                spaTimeout(() => m.classList.add('show'), 10);
            }
        };

        window.closeManualEventModal = function() {
            var m = document.getElementById('manualEventModal');
            if (m) { m.classList.remove('show'); spaTimeout(() => m.style.display = 'none', 200); }
        };

        window.toggleTimeFields = function(isAllDay) {
            document.querySelectorAll('.time-control-group').forEach(el => {
                el.style.display = isAllDay ? 'none' : 'block';
            });
        };

        const formManual = document.getElementById('form-create-manual-event');
        if (formManual) {
            bindSpa(formManual, 'submit', function(e) {
                e.preventDefault();
                var btn = document.getElementById('btnSaveManualEvent');
                var originalHtml = btn.innerHTML;
                btn.disabled = true;
                btn.innerHTML = 'Agendando...';

                fetch(this.action, {
                    method: 'POST',
                    body: new FormData(this)
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        window.closeManualEventModal();
                        if (calendarInstance) calendarInstance.refetchEvents();
                    } else {
                        alert(data.error || 'Ocurrió un error inesperado.');
                    }
                })
                .catch(err => alert('Error de red al conectar con el servidor.'))
                .finally(() => {
                    btn.disabled = false;
                    btn.innerHTML = originalHtml;
                });
            });
        }

        bindSpa(document, 'click', function(e) {
            var modal = document.getElementById('manualEventModal');
            if (e.target === modal && typeof window.closeManualEventModal === 'function') window.closeManualEventModal();
        });

        ensureFullCalendarThenInit();
    })();
    </script>
</main>

<?php 
if (!$is_spa) {
    require_once '../../layouts/footer.php'; 
}
?>