<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Manage Sessions</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"/>
    <link rel="stylesheet" href="css/main/main.css?ver=<?php echo time(); ?>"/>
    <script src="js/main/main.js?ver=<?php echo time(); ?>" defer></script>
    <style>
        .session-cards {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .session-card {
            flex: 1;
            min-width: 220px;
            background: #f9f9f9;
            border-left: 5px solid #4CAF50;
            padding: 15px;
            border-radius: 6px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .session-card h4 {
            margin: 0 0 5px;
            font-size: 16px;
            color: #333;
        }
        .session-card p {
            margin: 0;
            font-weight: bold;
            font-size: 18px;
            color: #555;
        }
        .session-card i {
            margin-right: 8px;
            color: #4CAF50;
        }

        .session-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        .session-table th,
        .session-table td {
            padding: 10px;
            border: 1px solid #ccc;
            text-align: left;
        }
        .session-table th {
            background-color: #f0f0f0;
        }
        .table-container {
            overflow-x: auto;
        }

        /* Highlighted row for the current user */
        .highlight-row {
            background-color: #e6f7ff; /* Light blue background */
            font-weight: bold;
        }

        
        .chat-btn {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 25px;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
    
        .chat-btn:hover {
            background-color: #218838;
            transform: scale(1.05);
        }
    </style>
</head>
<body>

    <div class="left-panel left-panel-show" id="left-panel"></div>

    <div class="main-content main-content-normal" id="main-content">
        <div id="content">
        </div>
    </div>

    <div id="chatModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h3>Send Message to <span id="chat-user-name"></span></h3>
            <textarea id="chat-message" placeholder="Type your message..."></textarea>
            <button id="send-message-btn">Send</button>
        </div>
    </div>
    
    
<script src="https://unpkg.com/peerjs@1.5.2/dist/peerjs.min.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        let peer = null;
        const connections = {};
        let currentUserPeerId = localStorage.getItem('peerId');

        // Initialize PeerJS with the current user's peer ID
        if (currentUserPeerId) {
            peer = new Peer(currentUserPeerId);

            peer.on('open', function(id) {
                console.log('My peer ID is: ' + id);
            });

            // Listen for incoming data connections from other peers
            peer.on('connection', function(conn) {
                console.log('Incoming connection from:', conn.peer);
                connections[conn.peer] = conn;

                // Listen for data on this new connection
                conn.on('data', function(data) {
                    console.log('Received data from ' + conn.peer + ':', data);
                    showMessagePopup(conn.peer, data.senderName, data.message); // Show popup when a message is received
                });

                conn.on('close', function() {
                    console.log('Connection closed with:', conn.peer);
                    delete connections[conn.peer];
                });
            });

            peer.on('error', function(err) {
                // console.error('PeerJS error:', err);
            });
        } else {
            // console.error('No peer ID found. Cannot initialize PeerJS.');
        }

        fetch("php/login/fetch_session_data.php")
            .then(res => res.json())
            .then(data => {
                const contentDiv = document.getElementById("content");

                if (!data || data.status !== "success" || !Array.isArray(data.data)) {
                    contentDiv.innerHTML = "<p>⚠️ Failed to load session data.</p>";
                    return;
                }

                let sessions = data.data;
                sessions.sort((a, b) => (a.peerId === currentUserPeerId ? -1 : 1));

                const count = sessions.length;
                const latestSession = sessions.reduce((latest, current) => {
                    return new Date(current.loggedAt) > new Date(latest.loggedAt) ? current : latest;
                }, sessions[0]);

                const cardsHTML = `
                    <div class="session-cards">
                        <div class="session-card">
                            <h4><i class="fas fa-users"></i>Total Sessions</h4>
                            <p>${count}</p>
                        </div>
                        <div class="session-card">
                            <h4><i class="fas fa-clock"></i>Last Login</h4>
                            <p>${new Date(latestSession.loggedAt).toLocaleString()}</p>
                        </div>
                        <div class="session-card">
                            <h4><i class="fas fa-user-circle"></i>Last User</h4>
                            <p>${latestSession.sessionName || "N/A"}</p>
                        </div>
                        <div class="session-card">
                            <h4><i class="fas fa-user-shield"></i>Last Role</h4>
                            <p>${latestSession.sessionRole || "N/A"}</p>
                        </div>
                    </div>
                `;

                let tableHTML = `
                    <div class="table-container">
                        <table class="session-table">
                            <thead>
                                <tr>
                                    <th>Peer ID</th>
                                    <th>Email</th>
                                    <th>Name</th>
                                    <th>Role</th>
                                    <th>Session Key</th>
                                    <th>Session Time</th>
                                    <th>Logged At</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                `;

                for (const s of sessions) {
                    const isCurrentUser = s.peerId === currentUserPeerId;
                    const sessionDurationInSeconds = (new Date() - new Date(s.sessionTime)) / 1000;
                    const canChat = sessionDurationInSeconds < 60;
                    const rowClass = isCurrentUser ? 'class="highlight-row"' : '';
                    tableHTML += `
                        <tr ${rowClass}>
                            <td>${s.peerId}</td>
                            <td>${s.sessionEmail}</td>
                            <td>${s.sessionName}</td>
                            <td>${s.sessionRole}</td>
                            <td>${s.sessionKey}</td>
                            <td>${new Date(s.sessionTime).toLocaleString()}</td>
                            <td>${s.loggedAt}</td>
                            <td>
                                ${isCurrentUser ? 'You' : (canChat ? `<button class="chat-btn" data-peer="${s.peerId}" data-name="${s.sessionName}"><i class="fas fa-comment-dots"></i></button>` : '')}
                            </td>
                        </tr>
                    `;
                }

                tableHTML += `
                            </tbody>
                        </table>
                    </div>
                `;

                contentDiv.innerHTML = cardsHTML + tableHTML;

                // Chat modal logic
                const modal = document.getElementById("chatModal");
                const closeBtn = modal.querySelector(".close");
                const chatUserName = document.getElementById("chat-user-name");
                const chatMessage = document.getElementById("chat-message");
                const sendMessageBtn = document.getElementById("send-message-btn");
                let targetPeerId = null;
                
                document.querySelectorAll(".chat-btn").forEach(btn => {
                    btn.addEventListener("click", () => {
                        const recipientPeerId = btn.dataset.peer;
                        if (recipientPeerId === currentUserPeerId) {
                            alert("You can't chat with yourself.");
                            return;
                        }
                        targetPeerId = recipientPeerId;
                        chatUserName.textContent = btn.dataset.name;
                        chatMessage.value = "";
                        modal.style.display = "block";
                        chatMessage.focus(); // Focus the input field when the modal opens
                    });
                });

                closeBtn.onclick = () => modal.style.display = "none";
                window.onclick = (e) => {
                    if (e.target === modal) modal.style.display = "none";
                };

                sendMessageBtn.onclick = () => {
                    const message = chatMessage.value.trim();
                    const senderName = localStorage.getItem('sessionName') || "Unknown User";

                    if (!message) {
                        alert("Message cannot be empty.");
                        return;
                    }
                    
                    showProcessingPopup(); // Show the new processing message
                    modal.style.display = "none"; // Hide the chat modal

                    const sendDataAndHandleResponse = (conn) => {
                        conn.send({
                            message: message,
                            senderName: senderName
                        });
                        console.log(`Message sent to ${targetPeerId}`);
                        hideProcessingPopup(); // Hide processing on success
                        showSentMessagePopup(targetPeerId); // Show confirmation popup
                    };

                    const handleError = (err) => {
                        console.error('Connection error:', err);
                        hideProcessingPopup(); // Hide processing on error
                        alert("Error connecting to peer. Please try again.");
                    };

                    if (connections[targetPeerId] && connections[targetPeerId].open) {
                        sendDataAndHandleResponse(connections[targetPeerId]);
                    } else {
                        const conn = peer.connect(targetPeerId);
                        conn.on('open', () => {
                            sendDataAndHandleResponse(conn);
                            connections[targetPeerId] = conn; // Cache the new connection
                        });
                        
                        conn.on('data', function(data) {
                            console.log('Received data from ' + conn.peer + ':', data);
                            showMessagePopup(conn.peer, data.senderName, data.message);
                        });

                        conn.on('error', handleError);
                    }
                };
            })
            .catch(err => {
                // console.error("Error fetching session data:", err);
                document.getElementById("content").innerHTML = "<p>❌ Error loading session data.</p>";
            });
            
        // Function to show a professional message received popup
        function showMessagePopup(senderPeerId, senderName, message) {
            senderName = senderName || "Unknown User";
            const popup = document.createElement('div');
            popup.classList.add('message-popup');
            popup.innerHTML = `
                <div class="popup-content">
                    <h3>📬 New Message from ${senderName}</h3>
                    <textarea class="message-display" readonly>${message}</textarea>
                    <div class="reply-section">
                        <textarea id="replyMessage" placeholder="Type your reply..."></textarea>
                        <button id="sendReplyBtn">Send Reply</button>
                    </div>
                    <button class="close-popup">Close</button>
                </div>
            `;
            document.body.appendChild(popup);
            
            popup.querySelector('#sendReplyBtn').addEventListener('click', () => {
                const replyMessage = document.getElementById('replyMessage').value.trim();
                const senderName = localStorage.getItem('sessionName') || "Unknown User";

                if (replyMessage) {
                    showProcessingPopup(); // Show processing message for reply
                    document.body.removeChild(popup); // Close the original message popup

                    const sendReplyAndHandleResponse = (conn) => {
                        conn.send({
                            message: replyMessage,
                            senderName: senderName
                        });
                        console.log(`Reply sent to ${senderPeerId}`);
                        hideProcessingPopup();
                        showSentMessagePopup(senderPeerId);
                    };

                    const handleError = (err) => {
                        console.error('Connection error:', err);
                        hideProcessingPopup();
                        alert("Error connecting to peer. Please try again.");
                    };

                    if (connections[senderPeerId] && connections[senderPeerId].open) {
                        sendReplyAndHandleResponse(connections[senderPeerId]);
                    } else {
                        const conn = peer.connect(senderPeerId);
                        conn.on('open', () => {
                            sendReplyAndHandleResponse(conn);
                            connections[senderPeerId] = conn;
                        });
                        conn.on('data', (data) => {
                            showMessagePopup(conn.peer, data.senderName, data.message);
                        });
                        conn.on('error', handleError);
                    }
                }
            });

            popup.querySelector('.close-popup').addEventListener('click', () => {
                document.body.removeChild(popup);
            });
        }

        // Function to show a professional message sent popup
        function showSentMessagePopup(targetPeerId) {
            const popup = document.createElement('div');
            popup.classList.add('sent-message-popup');
            popup.innerHTML = `
                <div class="popup-content">
                    <h3>✅ Message Sent!</h3>
                    <p>Your message was delivered.</p>
                </div>
            `;
            document.body.appendChild(popup);

            setTimeout(() => {
                if (document.body.contains(popup)) {
                    document.body.removeChild(popup);
                }
            }, 3000);
        }
        
        // NEW: Function to show a processing popup
        function showProcessingPopup() {
            const popup = document.createElement('div');
            popup.id = 'processing-popup';
            popup.classList.add('processing-popup');
            popup.innerHTML = `
                <div class="popup-content">
                    <h3>Sending Message...</h3>
                    <p>Please wait while we connect.</p>
                </div>
            `;
            document.body.appendChild(popup);
        }

        // NEW: Function to hide the processing popup
        function hideProcessingPopup() {
            const popup = document.getElementById('processing-popup');
            if (popup) {
                document.body.removeChild(popup);
            }
        }
    });
</script>

<style>
    /* Modal Styling */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        padding-top: 100px;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.4);
    }
    .modal-content {
        background-color: #fff;
        margin: auto;
        padding: 20px;
        border-radius: 6px;
        width: 90%;
        max-width: 400px;
        position: relative;
    }
    .close {
        color: #aaa;
        position: absolute;
        top: 10px;
        right: 15px;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
    }
    .modal textarea {
        width: 100%;
        height: 100px;
        margin-top: 10px;
    }
    .modal button {
        margin-top: 10px;
        background-color: #4CAF50;
        color: white;
        padding: 8px 12px;
        border: none;
        cursor: pointer;
        width: 100%;
    }

    /* Modal Styles */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0, 0, 0, 0.6);
        padding-top: 60px;
        backdrop-filter: blur(5px);
    }

    .modal-content {
        background: linear-gradient(145deg, #f0f4f8, #e0e8f0);
        margin: 5% auto;
        padding: 30px;
        border: none;
        border-radius: 20px;
        width: 80%;
        max-width: 500px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
        animation: modalOpen 0.5s ease-out;
    }

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

    .modal-header h2 {
        margin: 0;
        color: #007bff;
    }

    .close {
        color: #aaa;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        transition: color 0.3s;
    }

    .close:hover,
    .close:focus {
        color: #000;
    }

    .modal-body input {
        width: 100%;
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid #ddd;
        border-radius: 10px;
        font-size: 16px;
        transition: border-color 0.3s;
    }

    .modal-body input:focus {
        outline: none;
        border-color: #007bff;
        box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
    }

    .modal-footer {
        text-align: right;
    }

    .send-btn {
        background-color: #007bff;
        color: white;
        border: none;
        padding: 12px 25px;
        border-radius: 10px;
        cursor: pointer;
        transition: background-color 0.3s, transform 0.2s;
    }

    .send-btn:hover {
        background-color: #0056b3;
        transform: translateY(-2px);
    }

    /* Message Received Popup */
    .message-popup {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 320px;
        background: linear-gradient(135deg, #ffffff, #f0f8ff);
        border: 1px solid #e0eaf6;
        padding: 20px;
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        z-index: 9999;
        border-radius: 15px;
        font-family: 'Segoe UI', Arial, sans-serif;
        animation: slideIn 0.5s ease-out;
        transition: transform 0.3s ease, opacity 0.3s ease;
    }
    
    .message-popup h3 {
        margin: 0 0 10px;
        font-size: 1.2em;
        color: #007bff;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
    }

    .message-popup h3 i {
        margin-right: 10px;
    }
    
    .message-popup .message-display {
        width: 100%;
        max-width: 300px;
        min-height: 80px;
        border: 1px solid #ddd;
        border-radius: 8px;
        margin: 10px 0;
        background-color: #fff;
        padding: 10px;
        box-sizing: border-box;
        resize: vertical;
    }

    .message-popup .reply-section {
        margin-top: 15px;
        display: flex;
        flex-direction: column;
        align-items: stretch;
    }

    .message-popup textarea {
        width: 100%;
        padding: 10px;
        border-radius: 8px;
        border: 1px solid #ccc;
        resize: vertical;
        font-family: inherit;
        min-height: 50px;
    }

    .message-popup #sendReplyBtn {
        background-color: #007bff;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 8px;
        cursor: pointer;
        font-weight: bold;
        transition: background-color 0.3s;
        margin-top: 10px;
    }
    
    .message-popup #sendReplyBtn:hover {
        background-color: #0056b3;
    }
    
    .message-popup .close-popup {
        width: 100%;
        background-color: #dc3545;
        color: #fff;
        border: none;
        padding: 10px;
        border-radius: 8px;
        cursor: pointer;
        margin-top: 15px;
        font-weight: bold;
        transition: background-color 0.3s;
    }
    
    .message-popup .close-popup:hover {
        background-color: #c82333;
    }
    
    /* Sent Message Confirmation Popup */
    .sent-message-popup {
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        background-color: #28a745;
        color: #fff;
        padding: 15px 30px;
        border-radius: 10px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        z-index: 9998;
        text-align: center;
        animation: fadeInOut 3s forwards;
    }

    .sent-message-popup h3 {
        margin: 0;
        font-size: 1.1em;
    }
    
    .sent-message-popup p {
        margin: 5px 0 0;
        font-size: 0.9em;
    }

    /* NEW: Processing Message Popup */
    .processing-popup {
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        background-color: #ffc107;
        color: #333;
        padding: 15px 30px;
        border-radius: 10px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        z-index: 9999;
        text-align: center;
        opacity: 0;
        animation: fadeIn 0.5s forwards;
    }
    
    .processing-popup h3 {
        margin: 0;
        font-size: 1.1em;
    }
    
    .processing-popup p {
        margin: 5px 0 0;
        font-size: 0.9em;
    }

    /* Animations */
    @keyframes slideIn {
        from { transform: translate(-50%, -60%) scale(0.9); opacity: 0; }
        to { transform: translate(-50%, -50%) scale(1); opacity: 1; }
    }
    
    @keyframes modalOpen {
        from { transform: translateY(-50px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
    }
    
    @keyframes fadeInOut {
        0% { opacity: 0; transform: translateX(-50%) translateY(20px); }
        10% { opacity: 1; transform: translateX(-50%) translateY(0); }
        90% { opacity: 1; transform: translateX(-50%) translateY(0); }
        100% { opacity: 0; transform: translateX(-50%) translateY(20px); }
    }
    
    /* NEW: fadeIn animation for the processing popup */
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
</style>

</body>
</html>