<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS Messages</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', sans-serif;
        }

        .container {
            display: grid;
            grid-template-columns: 300px 1fr;
            height: 100vh;
            background: #f5f5f5;
        }

        .senders-list {
            background: white;
            border-right: 1px solid #ddd;
            overflow-y: auto;
        }

        .sender-item {
            padding: 1rem;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background 0.3s;
        }

        .sender-item:hover {
            background: #f8f9fa;
        }

        .sender-unread {
            background: #e3f2fd;
        }

        .messages-container {
            padding: 1rem;
            overflow-y: auto;
        }

        .message-card {
            background: white;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }

        .message-card.unread {
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
            color: #666;
        }

        .message-body {
            color: #333;
            line-height: 1.5;
        }

        .unread-badge {
            background: #4caf50;
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 0.8rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="senders-list" id="sendersList"></div>
        <div class="messages-container" id="messagesContainer"></div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', async () => {
            const companyId = sessionStorage.getItem('companyId');
            const branchId = sessionStorage.getItem('branchId');

            if (!companyId || !branchId) {
                alert('Company or Branch not set in session.');
                return;
            }

            await RequestNewMessages(companyId, branchId);

            // Fetch and display senders
            await loadSenders();
        });

        async function RequestNewMessages(companyId, branchId) {
            try {
                const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
                const data = await response.json();
                const defaultSmsUserId = data.defaultSmsUserId; // defaults
                const response2 = await fetch(`/api/sms/sendRequest/${defaultSmsUserId}`);
                if (response2.ok) {
                    console.log("request sent successfully");
                }
            } catch (error) {
                console.error('Error requesting new messages:', error);
            }
        }

        async function loadSenders() {
            try {
                const response = await fetch('/api/sms/senders');
                const senders = await response.json();
                
                const sendersList = document.getElementById('sendersList');
                sendersList.innerHTML = senders.map(sender => `
                    <div class="sender-item ${sender.unreadCount > 0 ? 'sender-unread' : ''}" 
                         onclick="loadMessages('${sender._id}')">
                        <div style="font-weight: 500;">${sender._id}</div>
                        <div style="font-size: 0.9em; color: #666;">${sender.address}</div>
                        ${sender.unreadCount > 0 ? `
                        <div style="margin-top: 0.5rem;">
                            <span class="unread-badge">${sender.unreadCount} unread</span>
                        </div>` : ''}
                    </div>
                `).join('');
            } catch (error) {
                console.error('Error loading senders:', error);
            }
        }

        async function loadMessages(senderName) {
            try {
                const response = await fetch(`/api/sms/sender/${encodeURIComponent(senderName)}`);
                const messages = await response.json();
                
                const messagesContainer = document.getElementById('messagesContainer');
                messagesContainer.innerHTML = messages.map(message => `
                    <div class="message-card ${!message.view ? 'unread' : ''}" 
                         onclick="markAsViewed('${message._id}', this)">
                        <div class="message-header">
                            <div>${new Date(message.date).toLocaleString()}</div>
                            ${!message.view ? '<div class="unread-badge">New</div>' : ''}
                        </div>
                       <div class="message-body">${message.amount.toLocaleString()}</div>
                    </div>
                `).join('');
            } catch (error) {
                console.error('Error loading messages:', error);
            }
        }

        async function markAsViewed(messageId, element) {
            try {
                await fetch(`/api/sms/message/${messageId}/view`, {
                    method: 'PUT'
                });
                element.classList.remove('unread');
                element.querySelector('.unread-badge')?.remove();
                loadSenders(); // Refresh sender list
            } catch (error) {
                console.error('Error marking message as viewed:', error);
            }
        }
    </script>
</body>
</html>
