<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once '../../services/notifications/NotificationService.php';

require_login();

$page_title = 'Notificaciones';
$service = new NotificationService(db());
$userId = current_user_id();
$isNotificationAdmin = current_user_role() === 'admin';
$notice = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'mark_all_read') {
        $updated = $service->markAllRead($userId);
        $notice = 'Notificaciones marcadas como leídas: ' . (int)$updated . '.';
    }

    if ($action === 'save_preferences') {
        $enabled = $_POST['email_enabled'] ?? [];
        foreach (NotificationService::eventTypes() as $eventType => $definition) {
            if (!empty($definition['critical'])) {
                $service->setEmailPreference($userId, $eventType, true);
                continue;
            }
            $service->setEmailPreference($userId, $eventType, isset($enabled[$eventType]));
        }
        $notice = 'Preferencias de email actualizadas.';
    }


    if ($action === 'save_recipient_groups' && $isNotificationAdmin) {
        $members = $_POST['group_members'] ?? [];
        $service->saveGroupMembers(is_array($members) ? $members : []);
        $notice = 'Responsables y equipos de notificación actualizados.';
    }
}

$unreadOnly = isset($_GET['unread']) && $_GET['unread'] === '1';
$notifications = $service->listForUser($userId, 120, $unreadOnly);
$preferences = $service->preferences($userId);
$recipientGroups = $isNotificationAdmin ? $service->groupsWithMembers() : [];
$activeUsers = $isNotificationAdmin ? $service->activeUsers() : [];
$unreadCount = $service->unreadCount($userId);
$visibleCount = count($notifications);

function notification_priority_label($priority)
{
    $labels = [
        'info' => 'Informativa',
        'success' => 'Éxito',
        'warning' => 'Alerta',
        'critical' => 'Crítica',
    ];
    return $labels[$priority] ?? 'Informativa';
}

function notification_display_date($value)
{
    if (!$value) return '-';
    $ts = strtotime($value);
    return $ts ? date('d-m-Y H:i', $ts) : $value;
}

function notification_icon_name($priority)
{
    if ($priority === 'critical') return 'circle-alert';
    if ($priority === 'warning') return 'triangle-alert';
    if ($priority === 'success') return 'circle-check';
    return 'bell';
}

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main" id="notificationsMain">

    <style>
    /* ==========================================================================
       Modales de notificaciones homologados a Productos / Clientes
       Header y footer fijos; body con scroll interno; footer estable.
       ========================================================================== */
    #notificationsMain .product-modal-backdrop {
        position: fixed !important;
        inset: 0 !important;
        display: none;
        align-items: center !important;
        justify-content: center !important;
        padding: 24px !important;
        overflow: hidden !important;
        background: rgba(0, 0, 0, 0.68) !important;
        backdrop-filter: blur(5px) !important;
        z-index: var(--z-modal, 1050) !important;
        opacity: 0;
        transition: opacity 0.2s ease !important;
    }

    #notificationsMain .product-modal-backdrop.show {
        display: flex !important;
        opacity: 1 !important;
    }

    #notificationsMain .product-modal-box {
        width: min(760px, calc(100vw - 48px)) !important;
        max-width: calc(100vw - 48px) !important;
        height: min(700px, calc(100dvh - 100px)) !important;
        min-height: min(560px, calc(100dvh - 100px)) !important;
        max-height: calc(100dvh - 100px) !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
        background: var(--surface-1) !important;
        border: 1px solid var(--border-default) !important;
        border-radius: var(--radius-xl) !important;
        box-shadow: var(--shadow-lg) !important;
        transform: translateY(20px);
        transition: transform 0.2s ease !important;
    }

    #notificationsMain .product-modal-backdrop.show .product-modal-box {
        transform: translateY(0);
    }

    #notificationsMain #notificationGroupsModal .product-modal-box {
        width: min(980px, calc(100vw - 48px)) !important;
    }

    #notificationsMain .product-modal-header {
        flex: 0 0 auto !important;
        min-height: 78px !important;
        padding: 20px 24px !important;
        display: flex !important;
        align-items: flex-start !important;
        justify-content: space-between !important;
        gap: 14px !important;
        border-bottom: 1px solid var(--border-subtle) !important;
        background: var(--surface-1) !important;
    }

    #notificationsMain .product-modal-header > div {
        flex: 1 1 auto !important;
        min-width: 0 !important;
    }

    #notificationsMain .product-modal-header .h3,
    #notificationsMain .product-modal-header h2 {
        margin-bottom: 2px !important;
        line-height: 1.18 !important;
        word-break: break-word !important;
    }

    #notificationsMain .action-square-btn {
        width: 42px !important;
        min-width: 42px !important;
        max-width: 42px !important;
        height: 42px !important;
        min-height: 42px !important;
        padding: 0 !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        border-radius: var(--radius-lg) !important;
        flex: 0 0 42px !important;
    }

    #notificationsMain .notification-preferences-box > form {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
        margin: 0 !important;
    }

    #notificationsMain .product-modal-body {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        max-height: none !important;
        padding: 20px 24px !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        -webkit-overflow-scrolling: touch !important;
        overscroll-behavior: contain !important;
    }

    #notificationsMain .product-modal-footer {
        flex: 0 0 auto !important;
        min-height: 76px !important;
        height: auto !important;
        padding: 14px 20px !important;
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        flex-wrap: nowrap !important;
        background: var(--surface-0) !important;
        border-top: 1px solid var(--border-subtle) !important;
        border-radius: 0 0 var(--radius-xl) var(--radius-xl) !important;
        overflow: visible !important;
    }

    #notificationsMain .modal-footer-actions-right {
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        flex: 0 1 auto !important;
        min-width: 0 !important;
        overflow: visible !important;
        flex-wrap: nowrap !important;
    }

    #notificationsMain .product-modal-footer .btn {
        width: auto !important;
        min-width: 118px !important;
        max-width: none !important;
        height: 48px !important;
        min-height: 48px !important;
        padding: 0 18px !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 8px !important;
        flex: 0 0 auto !important;
        white-space: nowrap !important;
        text-align: center !important;
        overflow: visible !important;
        text-overflow: clip !important;
        border-radius: var(--radius-lg) !important;
    }

    #notificationsMain .product-modal-footer .btn-primary {
        min-width: 178px !important;
    }

    #notificationsMain .product-modal-footer .btn span {
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        min-width: 0 !important;
        max-width: none !important;
        overflow: visible !important;
        text-overflow: clip !important;
        white-space: nowrap !important;
        text-align: center !important;
    }

    @media (max-width: 760px) {
        #notificationsMain .product-modal-backdrop {
            padding: 12px !important;
        }

        #notificationsMain .product-modal-box,
        #notificationsMain #notificationGroupsModal .product-modal-box {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            height: calc(100dvh - 200px) !important;
            min-height: 0 !important;
            max-height: calc(100dvh - 200px) !important;
            border-radius: 18px !important;
        }

        #notificationsMain .product-modal-header {
            min-height: 64px !important;
            padding: 14px !important;
            gap: 10px !important;
        }

        #notificationsMain .product-modal-header .h3,
        #notificationsMain .product-modal-header h2 {
            font-size: 1.05rem !important;
            line-height: 1.14 !important;
            margin-bottom: 2px !important;
        }

        #notificationsMain .product-modal-header .text-sm {
            font-size: 0.78rem !important;
            line-height: 1.15 !important;
        }

        #notificationsMain .action-square-btn {
            width: 42px !important;
            min-width: 42px !important;
            max-width: 42px !important;
            height: 42px !important;
            min-height: 42px !important;
            flex: 0 0 42px !important;
        }

        #notificationsMain .product-modal-body {
            padding: 14px !important;
        }

        #notificationsMain .product-modal-footer {
            min-height: 68px !important;
            padding: 10px 12px calc(10px + env(safe-area-inset-bottom)) !important;
            gap: 10px !important;
        }

        #notificationsMain .modal-footer-actions-right {
            width: 100% !important;
            flex: 1 1 auto !important;
            justify-content: flex-end !important;
            gap: 10px !important;
        }

        #notificationsMain .product-modal-footer .btn {
            height: 44px !important;
            min-height: 44px !important;
            min-width: 98px !important;
            max-width: none !important;
            padding: 0 12px !important;
            font-size: 0.92rem !important;
            flex: 0 1 auto !important;
        }

        #notificationsMain .product-modal-footer .btn-primary {
            min-width: 124px !important;
        }
    }
    </style>
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content notifications-page">
        <div class="page-header notifications-page-header">
            <div class="page-header-content">
                <span class="label">Sistema</span>
                <h2>Centro de notificaciones</h2>
                <p class="text-secondary">Alertas internas, recordatorios comerciales y estado de emails enviados por ICYLAB OS.</p>
            </div>
            <div class="cluster notifications-actions" aria-label="Acciones de notificaciones">
                <a class="btn btn-sm btn-outline notification-action-btn <?php echo !$unreadOnly ? 'is-active' : ''; ?>" href="/modules/notifications/" title="Todas" aria-label="Mostrar todas las notificaciones">
                    <i data-lucide="inbox"></i>
                    <span class="action-label">Todas</span>
                </a>
                <a class="btn btn-sm btn-outline notification-action-btn <?php echo $unreadOnly ? 'is-active' : ''; ?>" href="/modules/notifications/?unread=1" title="No leídas" aria-label="Mostrar notificaciones no leídas">
                    <i data-lucide="mail-open"></i>
                    <span class="action-label">No leídas</span>
                </a>
                <button class="btn btn-sm btn-outline notification-action-btn" type="button" id="notificationPreferencesOpen" title="Preferencias" aria-label="Abrir preferencias de email">
                    <i data-lucide="settings"></i>
                    <span class="action-label">Preferencias</span>
                </button>
                <?php if ($isNotificationAdmin): ?>
                    <button class="btn btn-sm btn-outline notification-action-btn" type="button" id="notificationGroupsOpen" title="Responsables y equipos" aria-label="Configurar responsables y equipos de notificación">
                        <i data-lucide="users-round"></i>
                        <span class="action-label">Equipos</span>
                    </button>
                <?php endif; ?>
                <form method="post" class="notification-mark-all-form" data-no-spa>
                    <input type="hidden" name="action" value="mark_all_read">
                    <button class="btn btn-sm btn-primary notification-action-btn notification-action-markall" type="submit" title="Marcar todas como leídas" aria-label="Marcar todas las notificaciones como leídas">
                        <i data-lucide="check-check"></i>
                        <span class="action-label">Marcar todas como leídas</span>
                    </button>
                </form>
            </div>
        </div>

        <?php if ($notice !== ''): ?>
            <div class="alert alert-success" style="margin-bottom: var(--space-4);"><?php echo safe_text($notice); ?></div>
        <?php endif; ?>

        <?php if (!$service->isReady()): ?>
            <div class="card">
                <div class="card-body">
                    <strong>Falta ejecutar la migración de notificaciones.</strong>
                    <p class="text-secondary" style="margin-top: 8px;">Ejecuta <code>database/migrations/2026_07_08_notifications_system.sql</code> antes de usar este módulo.</p>
                </div>
            </div>
        <?php else: ?>
            <div class="notifications-layout-grid notifications-layout-single">
                <div class="card notifications-list-card notifications-list-card-wide">
                    <div class="card-header notifications-card-header">
                        <div>
                            <h3>Actividad reciente</h3>
                            <p class="text-secondary text-sm"><?php echo $unreadOnly ? 'Mostrando sólo notificaciones pendientes.' : 'Últimos eventos asignados a tu usuario.'; ?></p>
                        </div>
                        <div class="notification-summary-pills" aria-label="Resumen de notificaciones">
                            <span class="notification-summary-pill"><strong><?php echo (int)$visibleCount; ?></strong> visibles</span>
                            <span class="notification-summary-pill <?php echo $unreadCount > 0 ? 'has-unread' : ''; ?>"><strong><?php echo (int)$unreadCount; ?></strong> no leídas</span>
                        </div>
                    </div>
                    <div class="notifications-full-list">
                        <?php if (empty($notifications)): ?>
                            <div class="empty-state compact notification-empty-state">
                                <i data-lucide="bell-off"></i>
                                <strong>Sin notificaciones</strong>
                                <p class="text-secondary">No hay eventos para mostrar con el filtro actual.</p>
                            </div>
                        <?php endif; ?>

                        <?php foreach ($notifications as $item): ?>
                            <?php
                                $priority = $item['priority'] ?: 'info';
                                $isUnread = empty($item['read_at']);
                                $href = !empty($item['url']) ? $item['url'] : '#';
                            ?>
                            <article class="notification-row notification-priority-<?php echo safe_text($priority); ?> <?php echo $isUnread ? 'is-unread' : 'is-read'; ?>">
                                <div class="notification-row-icon">
                                    <i data-lucide="<?php echo safe_text(notification_icon_name($priority)); ?>"></i>
                                </div>
                                <div class="notification-row-content">
                                    <div class="notification-row-head">
                                        <strong><?php echo safe_text($item['title']); ?></strong>
                                        <span class="notification-priority-badge"><?php echo safe_text(notification_priority_label($priority)); ?></span>
                                    </div>
                                    <?php if (!empty($item['body'])): ?>
                                        <p><?php echo nl2br(safe_text($item['body'])); ?></p>
                                    <?php endif; ?>
                                    <div class="notification-row-meta">
                                        <span><i data-lucide="calendar-clock"></i><?php echo safe_text(notification_display_date($item['created_at'])); ?></span>
                                        <span><i data-lucide="<?php echo $isUnread ? 'circle-dot' : 'check-circle-2'; ?>"></i><?php echo $isUnread ? 'No leída' : 'Leída'; ?></span>
                                        <span><i data-lucide="tag"></i><?php echo safe_text($item['event_type']); ?></span>
                                    </div>
                                </div>
                                <div class="notification-row-actions">
                                    <?php if (!empty($item['url'])): ?>
                                        <a class="btn btn-sm btn-outline notification-row-action" href="<?php echo safe_text($href); ?>" data-notification-link data-notification-id="<?php echo (int)$item['id']; ?>" title="Abrir registro relacionado" aria-label="Abrir registro relacionado">
                                            <i data-lucide="external-link"></i>
                                            <span>Abrir</span>
                                        </a>
                                    <?php endif; ?>
                                    <?php if ($isUnread): ?>
                                        <button class="btn btn-sm btn-ghost notification-row-action" type="button" data-notification-mark-read="<?php echo (int)$item['id']; ?>" title="Marcar como leída" aria-label="Marcar como leída">
                                            <i data-lucide="check"></i>
                                            <span>Leída</span>
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <?php if ($isNotificationAdmin && !empty($recipientGroups)): ?>
                <div id="notificationGroupsModal" class="product-modal-backdrop notification-preferences-modal notification-groups-modal" aria-hidden="true">
                    <div class="product-modal-box notification-preferences-box notification-groups-box" role="dialog" aria-modal="true" aria-labelledby="notificationGroupsTitle">
                        <div class="product-modal-header">
                            <div>
                                <h2 id="notificationGroupsTitle" class="h3">Responsables y equipos</h2>
                                <span class="text-secondary text-sm">Define quién recibe las alertas ejecutivas del MVP. No modifica permisos de acceso ni roles del sistema.</span>
                            </div>
                            <button class="btn btn-outline action-square-btn" type="button" id="notificationGroupsClose" aria-label="Cerrar configuración de equipos" title="Cerrar">
                                <i data-lucide="x"></i>
                            </button>
                        </div>
                        <form method="post" data-no-spa>
                            <input type="hidden" name="action" value="save_recipient_groups">
                            <div class="product-modal-body notification-preferences-body notification-groups-body">
                                <div class="notification-groups-intro">
                                    <strong>MVP activo:</strong>
                                    <span>CEO recibe excepciones estratégicas. CFO recibe caja, cobranza, facturación y descuentos. Comercial y Operaciones reciben alertas accionables según etapa.</span>
                                </div>
                                <div class="notification-groups-list">
                                    <?php foreach ($recipientGroups as $group): ?>
                                        <section class="notification-group-card">
                                            <div class="notification-group-card-head">
                                                <strong><?php echo safe_text($group['name']); ?></strong>
                                                <span><?php echo safe_text($group['group_key']); ?></span>
                                            </div>
                                            <?php if (!empty($group['description'])): ?>
                                                <p><?php echo safe_text($group['description']); ?></p>
                                            <?php endif; ?>
                                            <div class="notification-group-users">
                                                <?php foreach ($activeUsers as $user): ?>
                                                    <?php $checked = in_array((int)$user['id'], $group['member_ids'], true); ?>
                                                    <label class="notification-group-user <?php echo $checked ? 'is-selected' : ''; ?>">
                                                        <input type="checkbox" name="group_members[<?php echo safe_text($group['group_key']); ?>][]" value="<?php echo (int)$user['id']; ?>" <?php echo $checked ? 'checked' : ''; ?>>
                                                        <span>
                                                            <strong><?php echo safe_text($user['name']); ?></strong>
                                                            <em><?php echo safe_text(role_label($user['role'])); ?> · <?php echo safe_text($user['email']); ?></em>
                                                        </span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                        </section>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <div class="product-modal-footer notification-preferences-footer">
                                <div class="modal-footer-actions-right">
                                    <button class="btn btn-outline" type="button" data-notification-groups-close>
                                        <i data-lucide="x"></i>
                                        <span>Cancelar</span>
                                    </button>
                                    <button class="btn btn-primary" type="submit">
                                        <i data-lucide="save"></i>
                                        <span>Guardar&nbsp;<span class="mobile-hidden">equipos</span></span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            <?php endif; ?>

            <div id="notificationPreferencesModal" class="product-modal-backdrop notification-preferences-modal" aria-hidden="true">
                <div class="product-modal-box notification-preferences-box" role="dialog" aria-modal="true" aria-labelledby="notificationPreferencesTitle">
                    <div class="product-modal-header">
                        <div>
                            <h2 id="notificationPreferencesTitle" class="h3">Preferencias de email</h2>
                            <span class="text-secondary text-sm">Las notificaciones internas se mantienen activas. Los eventos críticos siempre envían email.</span>
                        </div>
                        <button class="btn btn-outline action-square-btn" type="button" id="notificationPreferencesClose" aria-label="Cerrar preferencias" title="Cerrar">
                            <i data-lucide="x"></i>
                        </button>
                    </div>
                    <form method="post" data-no-spa>
                        <input type="hidden" name="action" value="save_preferences">
                        <div class="product-modal-body notification-preferences-body">
                            <div class="notification-preferences-list">
                                <?php foreach ($preferences as $eventType => $pref): ?>
                                    <label class="notification-preference-item <?php echo !empty($pref['critical']) ? 'is-critical' : ''; ?>">
                                        <div>
                                            <strong><?php echo safe_text($pref['label']); ?></strong>
                                            <span><?php echo safe_text($pref['description']); ?></span>
                                            <?php if (!empty($pref['critical'])): ?>
                                                <em>Crítica · email obligatorio</em>
                                            <?php endif; ?>
                                        </div>
                                        <input type="checkbox" name="email_enabled[<?php echo safe_text($eventType); ?>]" value="1" <?php echo !empty($pref['email_enabled']) ? 'checked' : ''; ?> <?php echo !empty($pref['critical']) ? 'checked disabled' : ''; ?>>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="product-modal-footer notification-preferences-footer">
                            <div class="modal-footer-actions-right">
                                <button class="btn btn-outline" type="button" data-notification-preferences-close>
                                    <i data-lucide="x"></i>
                                    <span>Cancelar</span>
                                </button>
                                <button class="btn btn-primary" type="submit">
                                    <i data-lucide="save"></i>
                                    <span>Guardar&nbsp;<span class="mobile-hidden">preferencias</span></span>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        <?php endif; ?>
    </section>
</main>

<?php require_once '../../layouts/footer.php'; ?>
