<?php
// Contenido del Calendario integrado en el layout del CRM
?>
<link rel="stylesheet" href="<?php echo asset('modules/calendar/calendar_styles.css'); ?>">

<?php
    // Datos del desk para coherencia con el resto del CRM
    try {
        $db = getDB();
        $uid = (int)($_SESSION['user_id'] ?? 0);
        $deskRow = $db->selectOne("SELECT d.id AS desk_id, d.name AS desk_name FROM desks d INNER JOIN desk_users du ON du.desk_id = d.id WHERE du.user_id = ? ORDER BY du.assigned_at DESC LIMIT 1", [$uid]);
        $desk_name = $deskRow['desk_name'] ?? 'Mi Desk';
        $desk_id = $deskRow['desk_id'] ?? null;
    } catch (Exception $e) { $desk_name = 'Mi Desk'; $desk_id = null; }
?>

<div class="content-area edge-to-edge" id="calendar-module">
    <div class="calendar-header">
        <div class="header-left">
            <button class="header-icon-btn" id="calMenuToggle" title="Menú principal">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="3" y1="12" x2="21" y2="12"/>
                    <line x1="3" y1="6" x2="21" y2="6"/>
                    <line x1="3" y1="18" x2="21" y2="18"/>
                </svg>
            </button>
            <div class="logo-section">
                <svg class="calendar-logo" width="40" height="40" viewBox="0 0 40 40" fill="none">
                    <rect x="8" y="10" width="24" height="20" rx="3" stroke="#1a73e8" stroke-width="2"/>
                    <line x1="8" y1="16" x2="32" y2="16" stroke="#1a73e8" stroke-width="2"/>
                    <line x1="16" y1="8" x2="16" y2="10" stroke="#1a73e8" stroke-width="2"/>
                    <line x1="24" y1="8" x2="24" y2="10" stroke="#1a73e8" stroke-width="2"/>
                </svg>
                <span class="calendar-title">Calendario</span>
            </div>
        </div>
        <div class="header-center">
            <div class="date-navigation">
                <button class="nav-btn" id="calToday" title="Ir a hoy">Hoy</button>
                <div class="nav-arrows">
                    <button class="arrow-btn" id="calPrev" title="Mes anterior">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="15 18 9 12 15 6"/>
                        </svg>
                    </button>
                    <button class="arrow-btn" id="calNext" title="Mes siguiente">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="9 18 15 12 9 6"/>
                        </svg>
                    </button>
                </div>
                <div class="current-month" id="calRangeLabel">Octubre 2024</div>
            </div>
        </div>
        <div class="header-right">
            <div class="search-container">
                <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="11" cy="11" r="8"/>
                    <path d="m21 21-4.35-4.35"/>
                </svg>
                <input id="calSearch" type="text" placeholder="Buscar" aria-label="Buscar en calendario" />
            </div>
            <div class="view-controls">
                <button class="view-btn active" id="viewMonth" title="Vista de mes">Mes</button>
            </div>
            <div class="settings-menu">
                <button class="settings-btn" id="calSettings" title="Configuración">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="3"/>
                        <path d="M12 1v6m0 6v6m11-7h-6m-6 0H1"/>
                    </svg>
                </button>
            </div>
            <!-- Campana de notificaciones -->
            <div class="notifications">
                <button class="notify-bell" id="calNotifyBell" title="Recordatorios">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
                        <path d="M12 22a2 2 0 0 0 2-2H10a2 2 0 0 0 2 2Z"/>
                        <path d="M18 8a6 6 0 1 0-12 0c0 7-3 7-3 7h18s-3 0-3-7"/>
                    </svg>
                    <span class="notify-count" id="calNotifyCount" hidden>0</span>
                </button>
                <select id="calNotifyOffset" class="notify-offset" title="Avisar antes">
                    <option value="5">5 min</option>
                    <option value="10">10 min</option>
                    <option value="15" selected>15 min</option>
                    <option value="30">30 min</option>
                </select>
            </div>
            <div class="user-profile">
                <div class="user-avatar"><?php echo htmlspecialchars(substr($_SESSION['user_name'] ?? 'U', 0, 1)); ?></div>
                <span class="user-name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Usuario'); ?></span>
            </div>
        </div>
    </div>

    <div class="calendar-container luxury">
        <div class="calendar-layout">
            <aside class="cal-sidebar" aria-label="Panel lateral de calendario">
                <button type="button" class="btn-primary btn-size-md" id="calAddEventSidebar">＋ Crear</button>
                <div class="mini-month" id="calMiniMonth" aria-label="Mini calendario"></div>
                <div class="calendar-list">
                    <h4>Mis calendarios</h4>
                    <label><input type="checkbox" id="calCalendarDesk" checked> <span class="dot" style="--dot:#2ea6ff"></span> <?php echo htmlspecialchars($desk_name); ?></label>
                    <label><input type="checkbox" id="calCalendarWork" checked> <span class="dot" style="--dot:#0ea5e9"></span> Trabajo</label>
                    <label><input type="checkbox" id="calCalendarTasks" checked> <span class="dot" style="--dot:#6366f1"></span> Tareas</label>
                </div>
                <div class="sidebar-widgets">
                    <h4>Próximos</h4>
                    <div id="calUpcomingList" class="upcoming-list" aria-live="polite"></div>
                    <h4>Recordatorios</h4>
                    <div id="calReminders" class="reminders-list" aria-live="polite"></div>
                </div>
            </aside>
            <div class="cal-main">
                <div class="calendar-toolbar">
                    <div class="toolbar-left">
                        <div class="calendar-info">
                            <span class="calendar-name"><?php echo htmlspecialchars($desk_name); ?></span>
                            <span class="calendar-status">Calendario activo</span>
                        </div>
                    </div>
                    <div class="toolbar-right">
                        <div class="view-indicator">
                            <span class="view-label">Vista de mes</span>
                        </div>
                    </div>
                </div>

                <!-- KPIs profesionales -->
                <div class="kpi-row" id="calKpiRow" aria-label="Indicadores de calendario">
                    <div class="kpi-card" id="kpiToday">
                        <div class="kpi-top"><span class="kpi-chip">Hoy</span></div>
                        <div class="kpi-main">
                            <div class="kpi-value" id="kpiTodayCount">0</div>
                            <span class="kpi-trend" id="kpiTodayTrend">—</span>
                        </div>
                        <div class="kpi-sub" id="kpiTodaySub">Eventos programados</div>
                        <svg class="kpi-spark" id="kpiTodaySpark" viewBox="0 0 100 28" preserveAspectRatio="none" aria-hidden="true"></svg>
                    </div>
                    <div class="kpi-card" id="kpiWeek">
                        <div class="kpi-top"><span class="kpi-chip">Semana</span></div>
                        <div class="kpi-main">
                            <div class="kpi-value" id="kpiWeekCount">0</div>
                        </div>
                        <div class="kpi-sub" id="kpiWeekSub">Total de eventos</div>
                        <svg class="kpi-spark" id="kpiWeekSpark" viewBox="0 0 100 28" preserveAspectRatio="none" aria-hidden="true"></svg>
                    </div>
                    <div class="kpi-card" id="kpiNext">
                        <div class="kpi-top"><span class="kpi-chip">Próximo</span></div>
                        <div class="kpi-main">
                            <div class="kpi-value" id="kpiNextTitle">—</div>
                        </div>
                        <div class="kpi-sub" id="kpiNextTime">—</div>
                    </div>
                    <div class="kpi-card" id="kpiCapacity">
                        <div class="kpi-top"><span class="kpi-chip">Ocupación</span></div>
                        <div class="kpi-main">
                            <div class="kpi-value" id="kpiCapacityPct">0%</div>
                        </div>
                        <div class="kpi-progress"><div class="bar" id="kpiCapacityBar" style="width:0%"></div></div>
                        <div class="kpi-sub" id="kpiCapacitySub">Hoy (08–21)</div>
                    </div>
                </div>

                <div id="calendar" class="calendar" aria-label="Calendario" role="grid"></div>
                <button class="fab-create" id="calFabCreate" title="Crear nuevo evento">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="12" y1="5" x2="12" y2="19"/>
                        <line x1="5" y1="12" x2="19" y2="12"/>
                    </svg>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal profesional de detalles de evento -->
<div id="calModal" class="cal-modal" aria-hidden="true" role="dialog" aria-modal="true">
    <div id="calModalOverlay" style="position:absolute; inset:0;"></div>
    <div class="cal-modal-dialog" role="document">
        <div class="cal-readonly-banner" id="calReadOnlyBanner">
            <span class="lock">🔒</span> Modo lectura. Presiona "Editar" para modificar.
        </div>
        <div class="cal-modal-header">
            <div style="display:flex;align-items:center;gap:8px">
                <span class="ev-color-dot" id="calColorDot" aria-hidden="true"></span>
                <h3 style="margin:0; font-size:18px; font-weight:700; color:#0f172a">Detalles del evento</h3>
            </div>
            <button class="badge" id="calEdit" type="button" title="Editar">Editar</button>
            <button class="badge" id="calModalClose" type="button" title="Cerrar">Cerrar</button>
        </div>
        <!-- Tabs -->
        <div class="cal-tabs">
            <button class="tab-btn active" id="calTabEvent" type="button">Evento</button>
            <button class="tab-btn" id="calTabLead" type="button">Lead</button>
            <button class="tab-btn" id="calTabNotes" type="button">Notas</button>
        </div>
        <div class="cal-modal-body">
            <div class="tab-panel active" id="calTabPanelEvent">
                <div class="cal-section">
                    <h4 class="section-title">Información del evento</h4>
                    <div class="field">
                        <label for="calTitle">Título</label>
                        <input id="calTitle" type="text" placeholder="Título del evento" />
                    </div>
                    <div class="field-row">
                        <div class="field">
                            <label for="calStart">Inicio</label>
                            <input id="calStart" type="datetime-local" />
                        </div>
                        <div class="field">
                            <label for="calEnd">Fin</label>
                            <input id="calEnd" type="datetime-local" />
                        </div>
                    </div>
                    <div class="toggle">
                        <input id="calAllDay" type="checkbox" />
                        <label for="calAllDay">Todo el día</label>
                    </div>
                    <div class="field-row">
                        <div class="field">
                            <label for="calColor">Color</label>
                            <input id="calColor" type="color" />
                        </div>
                        <div class="field">
                            <label for="calCalendar">Calendario</label>
                            <select id="calCalendar">
                                <option value="desk">Mi Desk</option>
                                <option value="work">Trabajo</option>
                                <option value="tasks">Tareas</option>
                            </select>
                        </div>
                    </div>
                    <div class="info-list">
                        <div class="info-item">
                            <span class="info-label">Rango</span>
                            <span class="info-value" id="calRangeMini">—</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Duración</span>
                            <span class="info-value" id="calDuration">—</span>
                        </div>
                    </div>
                    <div class="field">
                        <label for="calDesc">Descripción</label>
                        <textarea id="calDesc" rows="3" placeholder="Descripción o notas"></textarea>
                    </div>
                </div>
            </div>
            <div class="tab-panel" id="calTabPanelLead">
                <div class="cal-section">
                    <h4 class="section-title">Lead asociado</h4>
                    <div class="lead-block">
                        <div class="lead-avatar" id="calLeadAvatar">—</div>
                        <div class="lead-main">
                            <a href="#" id="calLeadNameLink" class="lead-name">Sin lead</a>
                            <span id="calLeadSub" class="lead-sub">—</span>
                        </div>
                    </div>
                    <div class="info-list">
                        <div class="info-item"><span class="info-label">Email</span><span class="info-value" id="calLeadEmail">—</span></div>
                        <div class="info-item"><span class="info-label">Teléfono</span><span class="info-value" id="calLeadPhone">—</span></div>
                        <div class="info-item"><span class="info-label">Desk</span><span class="info-value" id="calLeadDesk">—</span></div>
                        <div class="info-item"><span class="info-label">Asignado</span><span class="info-value" id="calLeadAssigned">—</span></div>
                    </div>
                    <div class="lead-picker-row">
                        <input id="calLeadId" type="number" placeholder="ID del lead" min="1" />
                        <button class="badge" id="calLoadLeadBtn" type="button">Asociar lead</button>
                    </div>
                    <p class="lead-help">Si conoces el ID del lead, ingrésalo para vincularlo a este evento.</p>
                </div>
            </div>
            <div class="tab-panel" id="calTabPanelNotes">
                <div class="cal-section">
                    <h4 class="section-title">Notas adicionales</h4>
                    <div class="field">
                        <label for="calNotes">Notas</label>
                        <textarea id="calNotes" rows="6" placeholder="Notas o comentarios relevantes"></textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="cal-modal-footer">
            <button class="badge" id="calDelete" type="button" style="color:#b91c1c">Eliminar</button>
            <span class="spacer"></span>
            <button class="badge" id="calCancel" type="button">Cancelar</button>
            <button class="badge" id="calSave" type="button">Guardar</button>
        </div>
    </div>
    
    
</div>

<script>
    // Configuración de usuario y desk para el componente
    window.__CALENDAR_USER_ID__ = <?php echo json_encode($_SESSION['user_id'] ?? 1); ?>;
    window.__CURRENT_DESK__ = <?php echo json_encode(['desk_id'=>$desk_id, 'desk_name'=>$desk_name]); ?>;
    // Opcional: URL de datos dinámicos (SSE o polling). Ajustar si existe endpoint.
    window.CALENDAR_SSE_URL = window.CALENDAR_SSE_URL || null; // Ej: '/modules/calendar/events_sse.php'
    window.CALENDAR_DATA_URL = window.CALENDAR_DATA_URL || null; // Ej: '/modules/calendar/events_feed.php'
</script>
<script src="<?php echo asset('modules/calendar/calendar_app.js'); ?>"></script>
