<section class="analytics-dashboard">
    <div class="notification-content">
        <div class="title-wrapper">
            <h1 class="title">Notifications</h1>
        </div>

        <div class="user-page">
            <div class="form-wrapper">
                <div class="form-row">
                    <div class="form-group custom-select">
                        <label class="label-title">Recipient Type</label>
                        <select id="recipientType">
                            <option value="all" selected>All Users</option>
                            <!-- <option value="active">Active</option> -->
                        </select>
                    </div>
                    <div class="form-group custom-select">
                        <label class="label-title">Event</label>
                        <select id="eventSelect">
                            <option value="">Select an event</option>
                            <?php if (!empty($events)): ?>
                                <?php foreach ($events as $event): ?>
                                    <option value="<?= htmlspecialchars($event['id']) ?>">
                                        <?= htmlspecialchars($event['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="label-title">Subject</label>
                        <input type="text" id="notificationSubject" placeholder="Enter notification subject" />
                    </div>
                </div>
            </div>
            <div class="form-wrapper">
                <div class="form-row">
                    <div class="form-group">
                        <label class="label-title">Message</label>
                        <textarea id="notificationMessage" placeholder="Enter your message here..." rows="11"></textarea>
                    </div>
                </div>
            </div>
        </div>

        <div class="d-flex justify-content-end">
            <div class="btn btn-notification-wrapper">
                <a class="btn-notification" href="javascript:void(0)" id="sendNotificationBtn">Send Notification</a>
            </div>
        </div>

        <div class="recent-notification" id="recentNotification">
            <div class="events-header">
                <h2 class="title">Recent Notifications</h2>
            </div>

            <div class="table-responsive table-wrapper">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>Subject</th>
                            <th>Content</th>
                            <th>Type</th>
                            <th>Time</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="recentNotificationBody">
                        <!-- JS will render notifications here -->
                    </tbody>
                </table>
                <!-- Pagination Container -->

            </div>

        </div>
        <div class="pagination-wrapper" id="notificationsPagination" style="margin-top:10px; text-align:center;"></div>
    </div>
</section>

<!-- Notification Modal -->
<div id="notificationModal" class="custom-modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalSubject" class="title">Notification Details</h3>
            <span class="close-modal" onclick="closeModal()">&times;</span>
        </div>
        <div class="modal-body">
            <div class="detail-group">
                <label>Recipient Type:</label>
                <p id="modalType"></p>
            </div>
            <div class="detail-group">
                <label>Date & Time:</label>
                <p id="modalTime"></p>
            </div>
            <hr>
            <div class="detail-group">
                <label>Message Content:</label>
                <div class="scrollable-message" id="modalMessage"></div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // ---------------- SEND NOTIFICATION ----------------
        document.getElementById("sendNotificationBtn").addEventListener("click", function() {
            const recipientType = document.getElementById("recipientType").value;
            const eventId = document.getElementById("eventSelect").value;
            const subject = document.getElementById("notificationSubject").value.trim();
            const message = document.getElementById("notificationMessage").value.trim();

            if (!subject || !message) {
                Swal.fire('Missing!', 'Subject and message required', 'warning');
                return;
            }

            Swal.fire({
                title: 'Sending...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            fetch("<?= base_url('send/notification') ?>", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify({
                        recipientType,
                        subject,
                        eventId,
                        message
                    })
                })
                .then(res => res.json())
                .then(res => {
                    Swal.close();
                    if (res.status === 'success') {
                        Swal.fire({
                                icon: 'success',
                                title: 'Notification Sent',
                                timer: 1500,
                                showConfirmButton: false
                            })
                            .then(() => location.reload());
                    } else {
                        Swal.fire('Error', res.message || 'Something went wrong', 'error');
                    }
                })
                .catch(err => {
                    Swal.close();
                    Swal.fire('Error', 'Server error: ' + err.message, 'error');
                });
        });

        // ---------------- VIEW & CLOSE MODAL ----------------
        window.viewNotification = function(data) {
            document.getElementById("modalSubject").innerText = data.title;
            document.getElementById("modalType").innerText = data.type.toUpperCase();
            const date = new Date(parseInt(data.timestamp));
            document.getElementById("modalTime").innerText = date.toLocaleString();
            document.getElementById("modalMessage").innerText = data.message;
            document.getElementById("notificationModal").style.display = "block";
        }

        window.closeModal = function() {
            document.getElementById("notificationModal").style.display = "none";
        }

        window.onclick = function(event) {
            const modal = document.getElementById("notificationModal");
            if (event.target == modal) modal.style.display = "none";
        }

        // ---------------- DELETE NOTIFICATION ----------------
        window.deleteNotification = async function(id) {
            const result = await Swal.fire({
                title: 'Delete?',
                text: "Remove this log?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete'
            });

            if (result.isConfirmed) {
                fetch(`<?= base_url('admin/NotificationController/deleteNotification/') ?>${id}`)
                    .then(res => res.json())
                    .then(res => {
                        if (res.status === 'success') location.reload();
                    });
            }
        }

        // ---------------- CLIENT-SIDE PAGINATION ----------------
        let notificationsData = <?php echo json_encode($notifications ?? []); ?>;
        let currentNotificationPage = 1;
        const notificationsPerPage = 10;

        function renderNotifications() {
            const body = document.getElementById("recentNotificationBody");
            const pagination = document.getElementById("notificationsPagination");
            body.innerHTML = "";
            pagination.innerHTML = "";

            if (!notificationsData.length) {
                body.innerHTML = '<tr><td colspan="5" class="text-center">No notifications found</td></tr>';
                return;
            }

            const totalPages = Math.ceil(notificationsData.length / notificationsPerPage);
            if (currentNotificationPage > totalPages) currentNotificationPage = 1;

            const start = (currentNotificationPage - 1) * notificationsPerPage;
            const paginatedNotifications = notificationsData.slice(start, start + notificationsPerPage);

            paginatedNotifications.forEach(n => {
                const dateStr = new Date(parseInt(n.timestamp)).toLocaleString();
                body.innerHTML += `
            <tr class="table-data">
                <td><span class="title truncate-subject" title="${n.title}">${n.title}</span></td>
                <td><span class="title truncate-text" title="${n.message}">${n.message}</span></td>
                <td class="to">${n.type.charAt(0).toUpperCase() + n.type.slice(1)}</td>
                <td class="time">${dateStr}</td>
                <td>
                    <button class="btn-secondary" onclick='viewNotification(${JSON.stringify(n)})'>👁️</button>
                    <button class="btn-secondary btn-delete" onclick="deleteNotification('${n.id}')">
                        <img src="<?= base_url('public/admin_assets/images/delete.png'); ?>" style="width:16px;" />
                    </button>
                </td>
            </tr>`;
            });

            // -------- PAGINATION UI --------
            pagination.innerHTML += `
            <button class="btn-primary" style="background-color: #000000"
                ${currentNotificationPage === 1 ? 'disabled' : ''}
                onclick="goToNotificationPage(${currentNotificationPage - 1})"
                style="margin:0 4px;">
                Previous
            </button>
            <button class="btn-primary active" style="background-color: #000000" disabled style="margin:0 4px;">
                ${currentNotificationPage}
            </button>
            <button class="btn-primary" style="background-color: #000000"
                ${currentNotificationPage === totalPages ? 'disabled' : ''}
                onclick="goToNotificationPage(${currentNotificationPage + 1})"
                style="margin:0 4px;">
                Next
            </button>
        `;
        }

        window.goToNotificationPage = function(page) {
            currentNotificationPage = page;
            renderNotifications();
        }

        // INITIAL RENDER
        renderNotifications();
    });
</script>



<style>
    .pagination-wrapper button:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    /* Truncate long text in the table */
    .truncate-text {
        max-width: 200px;
        /* Adjust this width as needed */
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
        vertical-align: middle;
    }

    /* Optional: Make the subject slightly bolder but still limited */
    .truncate-subject {
        max-width: 300px;
        font-weight: 500;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
    }

    /* Modal Styling */
    .custom-modal {
        display: none;
        position: fixed;
        z-index: 9999;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(5px);
    }

    .modal-content {
        background: rgba(246, 246, 246, 0.95);
        /* Slightly more solid for readability */
        margin: 5% auto;
        padding: 20px;
        border-radius: 20px;
        width: 60%;
        max-width: 600px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        animation: slideIn 0.3s ease-out;
    }

    @keyframes slideIn {
        from {
            transform: translateY(-50px);
            opacity: 0;
        }

        to {
            transform: translateY(0);
            opacity: 1;
        }
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ddd;
        padding-bottom: 15px;
        margin-bottom: 20px;
    }

    .close-modal {
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        color: #5d5d5d;
    }

    .detail-group label {
        display: block;
        font-weight: 600;
        color: #D2B767;
        font-size: 14px;
        margin-bottom: 5px;
    }

    .detail-group p {
        font-size: 16px;
        color: #333;
    }

    .scrollable-message {
        background: rgba(0, 0, 0, 0.05);
        padding: 20px;
        border-radius: 12px;
        max-height: 300px;
        overflow-y: auto;
        font-size: 16px;
        line-height: 1.6;
        white-space: pre-wrap;
        /* Maintains line breaks from textarea */
        color: #000;
    }

    /* Custom Scrollbar for the message */
    .scrollable-message::-webkit-scrollbar {
        width: 6px;
    }

    .scrollable-message::-webkit-scrollbar-thumb {
        background: #D2B767;
        border-radius: 10px;
    }

    /* Search bar */
    .search-bar-wrapper input[type="text"] {
        width: 100%;
        padding: 12px 15px;
        font-size: 16px;
        border-radius: 12px;
        border: none;
        background: rgba(255, 255, 255, 0.3);
        outline: none;
        color: #000;
    }

    .notification-content h1 {
        font-size: 20px;
        font-weight: 500;
        color: #5D5D5D;
        margin-bottom: 10px;
    }

    /* Forms */
    .user-page {
        width: 100%;
        display: flex;
        gap: 20px;
    }

    @media (max-width: 767.98px) {
        .user-page {
            flex-direction: column;
        }
    }

    .user-page .form-wrapper {
        width: 50%;
    }

    @media (max-width: 767.98px) {
        .user-page .form-wrapper {
            width: 100%;
        }
    }

    .form-group {
        margin-top: 15px;
        overflow: clip;
    }

    .form-group .label-title {
        font-size: 14px;
        font-weight: 500;
        color: #5D5D5D;
    }

    .ringside .analytics-dashboard .title-wrapper .title {
        padding: 0;
        margin: 0;
    }


    /* Inputs */
    .form-group input,
    .form-group select {
        width: 100%;
        padding: 15px 20px;
        font-size: 18px;
        border: none;
        border-radius: 12px;
        background: rgba(255, 255, 255, 0.3);
        outline: none;
        margin-top: 10px;
        font-weight: 300;
    }

    /* Placeholder */
    input::placeholder {
        opacity: 0.8;
        color: #000;
    }


    /* Custom select */
    .custom-select {
        position: relative;
    }

    .custom-select select {
        appearance: none;
    }

    .custom-select::after {
        content: "";
        position: absolute;
        bottom: 20%;
        right: 25px;
        width: 12px;
        height: 8px;
        background-image: url("./assets/images/icon-down.png");
        background-size: contain;
        background-repeat: no-repeat;
        transform: translateY(-50%);
        pointer-events: none;
    }

    textarea {
        width: 100%;
        padding: 13px 15px;
        font-size: 15px;
        border: none;
        border-radius: 12px;
        background: rgba(255, 255, 255, 0.3);
        outline: none;
        margin-top: 10px;
        min-height: 232px;
        vertical-align: middle;
    }

    /* NOTIFICATION PAGE (same styling as schedule/events) */
    .ringside .analytics-dashboard .recent-notification {
        background: rgba(255, 255, 255, 0.3);
        border-radius: 20px;
        padding: 20px;
        display: block;
    }

    .ringside .analytics-dashboard .btn-notification-wrapper {
        margin-top: 5px;
        margin-bottom: 35px;
        padding: 17px 37px;
        border-radius: 30px;
        border: none;
        max-width: 190px;
        width: 100%;
        font-size: 15px;
        line-height: 21px;
    }

    .ringside .analytics-dashboard .btn-notification {
        text-decoration: none;
        color: #ffffff;
        border: none;
    }

    /* Header */
    .ringside .analytics-dashboard .recent-notification .events-header .title {
        letter-spacing: 0px;
        font-weight: 400;
        font-size: 20px;
        line-height: 22px;
        color: #000000;
        opacity: 1;
    }

    /* Table text styles */
    .ringside .analytics-dashboard .recent-notification .table-wrapper .notification,
    .ringside .analytics-dashboard .recent-notification .table-wrapper .to,
    .ringside .analytics-dashboard .recent-notification .table-wrapper .time,
    .ringside .analytics-dashboard .recent-notification .table-wrapper .status {
        font-weight: 300;
        font-size: 12px;
        line-height: 14px;
    }

    /* Buttons (same as events/schedule) */
    .ringside .analytics-dashboard .recent-notification .btn-secondary {
        background: #D2B767;
        font-size: 9px;
        font-weight: 300;
        line-height: 10px;
        border: none;
        padding: 7px 13px;
        border-radius: 8px;
        cursor: pointer;
        margin-right: 6px;
    }

    .ringside .analytics-dashboard .recent-notification .btn-delete {
        padding: 7px;
        height: 24px;
    }
</style>