<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="<?php echo base_url('public/admin_assets/css/admin-chat.css'); ?>">
    <style>

    </style>
</head>

<body>
    <section class="analytics-dashboard">
        <div class="title-wrapper">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="title">Send Text Messages</h1>
                <a href="<?php echo base_url('admin/messages'); ?>" class="btn btn-back">
                    <i class="ri-arrow-left-line"></i> Back to Chat
                </a>
            </div>
            <p class="subtitle">Send SMS messages to event participants</p>
        </div>

        <div class="text-message-container">
            <!-- Events Column -->
            <div class="chat-events-column events-column">
                <div class="column-header">
                    <h3 style="padding-bottom: 4px;">Events <span id="eventsCount" class="events-count">0</span></h3>
                    <div class="search-box">
                        <i class="ri-search-line"></i>
                        <input type="text" id="eventSearch" placeholder="Search events..." class="search-input">
                    </div>
                </div>
                <div class="events-list" id="eventsList">
                    <div class="loading-state">
                        <i class="ri-loader-4-line spinning"></i>
                        <p>Loading events...</p>
                    </div>
                </div>
            </div>

            <!-- Users Column -->
            <div class="chat-users-column users-column">
                <div class="column-header">
                    <h3 id="selectedEventTitle">Select an Event</h3>
                    <div class="search-box">
                        <i class="ri-search-line"></i>
                        <input type="text" id="userSearch" placeholder="Search users..." class="search-input">
                    </div>
                    <div class="select-all-container">
                        <input type="checkbox" id="selectAllUsers" class="select-all-checkbox">
                        <label for="selectAllUsers" class="select-all-label">Select All Users</label>
                        <span id="selectedCount" class="selected-count">0</span>
                    </div>
                </div>
                <div class="users-list" id="usersList">
                    <div class="empty-state">
                        <i class="ri-user-3-line"></i>
                        <p>Select an event to view participants</p>
                    </div>
                </div>
            </div>

            <!-- Message Column -->
            <div class="message-column">
                <div class="column-header">
                    <h3>Compose Message</h3>
                    <p>To: <span id="recipientCount">0</span> recipient(s)</p>
                </div>

                <div class="message-area">
                    <textarea
                        id="messageText"
                        class="message-textarea"
                        placeholder="Type your SMS message here... (Max 160 characters)"
                        maxlength="160"></textarea>

                    <div class="char-count" id="charCount">0/160 characters</div>

                    <button id="sendMessageBtn" class="send-btn" disabled>
                        <i class="ri-send-plane-fill"></i> Send Message
                    </button>
                </div>
            </div>
        </div>

        <!-- Status Modal -->
        <div id="statusModal" class="modal-overlay" style="display:none;">
            <div class="modal-content">
                <h3>Sending Messages</h3>
                <div class="progress-container">
                    <div class="progress-bar" id="progressBar"></div>
                    <span id="progressText">0%</span>
                </div>
                <div id="statusDetails" style="margin-top: 20px; max-height: 200px; overflow-y: auto; font-size: 13px; line-height: 1.4;">
                    <!-- Status messages will appear here -->
                </div>
                <div class="modal-buttons" style="margin-top: 20px;">
                    <button id="closeStatusModal" style="display:none; padding: 8px 20px; background: rgba(255,255,255,0.2); color: #333; border: 1px solid rgba(195,162,89,0.3); border-radius: 6px; cursor: pointer;">Close</button>
                </div>
            </div>
        </div>
    </section>

    <script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-firestore-compat.js"></script>

    <script>
        let db;
        let allEvents = [];
        let filteredEvents = [];
        let currentEvent = null;
        let eventUsers = [];
        let selectedUsers = new Set();
        let isSelectAll = false;
        let statusModal;

        // Initialize Firebase
        async function initFirebase() {
            try {
                const response = await fetch('<?php echo base_url("admin/getFirebaseConfig"); ?>');
                const firebaseConfig = await response.json();
                if (!firebase.apps.length) firebase.initializeApp(firebaseConfig);
                db = firebase.firestore();
                loadEvents();
            } catch (error) {
                console.error('Firebase error:', error);
                showError('Failed to initialize Firebase');
            }
        }

        // Load all events
        async function loadEvents() {
            const eventsList = document.getElementById('eventsList');

            try {
                const eventsSnapshot = await db.collection('events').get();
                allEvents = [];

                for (const doc of eventsSnapshot.docs) {
                    const data = doc.data();

                    allEvents.push({
                        id: doc.id,
                        name: data.event_name || 'Untitled Event',
                        status: data.status || 'draft',
                        start_date: data.start_date || 0,
                        member_count: Object.keys(data.event_members || {}).length
                    });
                }

                // Sort by start date (most recent first)
                allEvents.sort((a, b) => b.start_date - a.start_date);
                filteredEvents = [...allEvents];

                displayEvents(filteredEvents);
                updateEventsCount();

            } catch (error) {
                console.error('Error loading events:', error);
                eventsList.innerHTML = '<div class="error-state"><i class="ri-error-warning-line"></i><p>Failed to load events</p></div>';
            }
        }

        // Display events
        function displayEvents(events) {
            const eventsList = document.getElementById('eventsList');

            if (events.length === 0) {
                eventsList.innerHTML = '<div class="empty-state"><i class="ri-calendar-line"></i><p>No events found</p></div>';
                return;
            }

            let html = '';
            events.forEach(event => {
                const dateStr = event.start_date ?
                    new Date(event.start_date).toLocaleDateString('en-US', {
                        month: 'short',
                        day: 'numeric',
                        year: 'numeric'
                    }) : 'No date';

                const isSelected = currentEvent?.id === event.id ? 'selected' : '';

                html += `
                <div class="event-item ${isSelected}" onclick="selectEvent('${event.id}', '${escapeHtml(event.name)}')">
                    <div class="event-info">
                        <h4>${escapeHtml(event.name)}</h4>
                        <span class="event-date">
                            <i class="ri-calendar-line"></i> ${dateStr}
                            <span class="member-count">${event.member_count || 0} users</span>
                        </span>
                    </div>
                </div>
            `;
            });

            eventsList.innerHTML = html;
        }

        // Select an event
        async function selectEvent(eventId, eventName) {
            currentEvent = {
                id: eventId,
                name: eventName
            };

            // Update UI
            document.getElementById('selectedEventTitle').textContent = eventName;
            document.querySelectorAll('.event-item').forEach(item => {
                item.classList.remove('selected');
            });

            const selectedItem = document.querySelector(`.event-item[onclick*="${eventId}"]`);
            if (selectedItem) {
                selectedItem.classList.add('selected');
            }

            // Show users column on mobile
            document.querySelector('.users-column').classList.add('active');
            document.querySelector('.message-column').classList.remove('active');

            // Load users for this event
            await loadEventUsers(eventId);
        }

        // Load users for selected event
        async function loadEventUsers(eventId) {
            const usersList = document.getElementById('usersList');
            usersList.innerHTML = '<div class="loading-state"><i class="ri-loader-4-line spinning"></i><p>Loading participants...</p></div>';

            selectedUsers.clear();
            isSelectAll = false;
            document.getElementById('selectAllUsers').checked = false;
            updateSelectedCount();
            updateSendButton();

            try {
                const eventDoc = await db.collection('events').doc(eventId).get();
                if (!eventDoc.exists) {
                    usersList.innerHTML = '<div class="empty-state"><i class="ri-error-warning-line"></i><p>Event not found</p></div>';
                    return;
                }

                const eventData = eventDoc.data();
                const membersMap = eventData.event_members || {};
                eventUsers = [];

                // Get user details for each member
                for (const userId of Object.keys(membersMap)) {
                    try {
                        const userDoc = await db.collection('Users').doc(userId).get();
                        if (userDoc.exists) {
                            const userData = userDoc.data();
                            if (userData.userRole === 'user' && userData.phoneNumber) {
                                eventUsers.push({
                                    id: userId,
                                    name: userData.fullname || 'Unknown User',
                                    phone: userData.phoneNumber
                                });
                            }
                        }
                    } catch (err) {
                        console.error('Error fetching user:', err);
                    }
                }

                displayUsers(eventUsers);

            } catch (err) {
                console.error('Error loading event users:', err);
                usersList.innerHTML = '<div class="error-state"><i class="ri-error-warning-line"></i><p>Failed to load participants</p></div>';
            }
        }

        // Display users
        function displayUsers(users) {
            const usersList = document.getElementById('usersList');

            if (users.length === 0) {
                usersList.innerHTML = '<div class="empty-state"><i class="ri-user-search-line"></i><p>No participants with phone numbers found</p></div>';
                return;
            }

            let html = '';
            users.forEach(user => {
                const isSelected = selectedUsers.has(user.id);

                html += `
                <div class="user-item ${isSelected ? 'selected' : ''}" onclick="toggleUserSelection('${user.id}')">
                    <div class="user-avatar">
                        <i class="ri-user-3-fill"></i>
                    </div>
                    <div class="user-info">
                        <h4>${escapeHtml(user.name)}</h4>
                        <p class="user-phone">${escapeHtml(user.phone)}</p>
                    </div>
                    <input type="checkbox" ${isSelected ? 'checked' : ''} onclick="event.stopPropagation(); toggleUserSelection('${user.id}')">
                </div>
            `;
            });

            usersList.innerHTML = html;

            // Show message column on mobile when users are loaded
            if (window.innerWidth <= 768) {
                setTimeout(() => {
                    document.querySelector('.message-column').classList.add('active');
                }, 300);
            }
        }

        // Toggle user selection
        function toggleUserSelection(userId) {
            if (selectedUsers.has(userId)) {
                selectedUsers.delete(userId);
            } else {
                selectedUsers.add(userId);
            }

            // Check if "Select All" checkbox should be unchecked
            if (isSelectAll && selectedUsers.size < eventUsers.length) {
                isSelectAll = false;
                document.getElementById('selectAllUsers').checked = false;
            }

            // Check if all users are selected (update "Select All" checkbox)
            if (!isSelectAll && selectedUsers.size === eventUsers.length && eventUsers.length > 0) {
                isSelectAll = true;
                document.getElementById('selectAllUsers').checked = true;
            }

            updateSelectedCount();
            updateSendButton();
            displayUsers(eventUsers);
        }

        // Toggle select all 
        document.getElementById('selectAllUsers').addEventListener('change', function(e) {
            isSelectAll = e.target.checked;

            if (isSelectAll) {
                // Select all users
                eventUsers.forEach(user => selectedUsers.add(user.id));
            } else {
                // Clear all selections
                selectedUsers.clear();
            }

            updateSelectedCount();
            updateSendButton();
            displayUsers(eventUsers);
        });

        // Update selected count 
        function updateSelectedCount() {
            const count = isSelectAll ? eventUsers.length : selectedUsers.size;
            document.getElementById('selectedCount').textContent = count;
            document.getElementById('recipientCount').textContent = count;
        }

        // Update send button state
        function updateSendButton() {
            const messageText = document.getElementById('messageText').value.trim();
            const hasRecipients = isSelectAll ? eventUsers.length > 0 : selectedUsers.size > 0;
            const hasMessage = messageText.length > 0;

            document.getElementById('sendMessageBtn').disabled = !(hasRecipients && hasMessage);
        }

        // Update events count
        function updateEventsCount() {
            document.getElementById('eventsCount').textContent = filteredEvents.length;
        }

        // Character counter
        document.getElementById('messageText').addEventListener('input', function(e) {
            const length = e.target.value.length;
            document.getElementById('charCount').textContent = `${length}/160 characters`;
            updateSendButton();
        });

        // Send message 
        document.getElementById('sendMessageBtn').addEventListener('click', async function() {
            const messageText = document.getElementById('messageText').value.trim();

            // Calculate actual recipients based on current state
            const actualRecipients = isSelectAll ? eventUsers.length : selectedUsers.size;

            if (!currentEvent || actualRecipients === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Select Recipients',
                    text: 'Please select recipients first'
                });
                return;
            }

            if (!messageText) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Enter Message',
                    text: 'Please enter a message'
                });
                return;
            }

            // Get phone numbers - FIXED to use actual selections
            let phoneNumbers = [];

            if (isSelectAll) {
                // All users in the event
                phoneNumbers = eventUsers.map(user => user.phone).filter(phone => phone);
            } else {
                // Only selected users
                eventUsers.forEach(user => {
                    if (selectedUsers.has(user.id) && user.phone) {
                        phoneNumbers.push(user.phone);
                    }
                });
            }

            if (phoneNumbers.length === 0) {
                Swal.fire({
                    icon: 'error',
                    title: 'No Phone Numbers',
                    text: 'No valid phone numbers found'
                });
                return;
            }

            // Show confirmation with ACTUAL count
            const confirmResult = await Swal.fire({
                title: 'Send Messages?',
                html: `Send SMS to <strong>${phoneNumbers.length}</strong> recipient(s)?<br><br>
                  <strong>Event:</strong> ${currentEvent.name}<br>
                  <strong>Message:</strong> "${messageText.substring(0, 50)}${messageText.length > 50 ? '...' : ''}"`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Send Now',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#c3a259',
                cancelButtonColor: '#666'
            });

            if (!confirmResult.isConfirmed) return;

            // Show progress modal with ACTUAL count
            showStatusModal(phoneNumbers.length, messageText);

            // Send messages
            try {
                const response = await fetch('<?php echo base_url("admin/send_twillio_message"); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        to: phoneNumbers,
                        msg: messageText,
                        eventId: currentEvent.id,
                        eventName: currentEvent.name
                    })
                });

                const result = await response.json();

                // Update status modal with results
                updateStatusModal(result, phoneNumbers.length);

                // Clear message if successful
                if (result.status === 'success' || result.status === 'partial') {
                    document.getElementById('messageText').value = '';
                    updateSendButton();
                    document.getElementById('charCount').textContent = '0/160 characters';
                }

            } catch (err) {
                console.error('Error sending messages:', err);
                updateStatusModalWithError(err.message);
            }
        });

        // Show status modal
        function showStatusModal(totalRecipients, message) {
            statusModal = document.getElementById('statusModal');
            statusModal.style.display = 'flex';

            document.getElementById('progressBar').style.width = '0%';
            document.getElementById('progressText').textContent = '0%';

            const details = document.getElementById('statusDetails');
            details.innerHTML = `
            <p><strong>Event:</strong> ${currentEvent.name}</p>
            <p><strong>Total Recipients:</strong> ${totalRecipients}</p>
            <p><strong>Message:</strong> ${message}</p>
            <hr>
            <p><i class="ri-loader-4-line spinning"></i> Sending messages...</p>
         `;

            document.getElementById('closeStatusModal').style.display = 'none';
        }

        // Update status modal
        function updateStatusModal(result, totalRecipients) {
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');
            const details = document.getElementById('statusDetails');
            const closeBtn = document.getElementById('closeStatusModal');

            const successCount = result.success_numbers?.length || 0;
            const failedCount = result.failed_numbers?.length || 0;
            const progress = totalRecipients > 0 ? Math.round((successCount + failedCount) / totalRecipients * 100) : 100;

            progressBar.style.width = `${progress}%`;
            progressText.textContent = `${progress}%`;

            let detailsHtml = `
            <p><strong>✓ Sent:</strong> ${successCount}</p>
            <p><strong>✗ Failed:</strong> ${failedCount}</p>
            `;

            if (result.failed_numbers && result.failed_numbers.length > 0) {
                detailsHtml += `<p><strong>Failed Numbers:</strong><br>${result.failed_numbers.join('<br>')}</p>`;
            }

            details.innerHTML = detailsHtml;

            // Show close button when done
            closeBtn.style.display = 'block';
            closeBtn.onclick = function() {
                statusModal.style.display = 'none';


            };
        }

        // Update status modal with error
        function updateStatusModalWithError(error) {
            const details = document.getElementById('statusDetails');
            const closeBtn = document.getElementById('closeStatusModal');

            details.innerHTML = `<p style="color: #dc3545;"><strong>Error:</strong> ${error}</p>`;
            closeBtn.style.display = 'block';
            closeBtn.onclick = function() {
                statusModal.style.display = 'none';
                Swal.fire({
                    icon: 'error',
                    title: 'Sending Failed',
                    text: 'Failed to send messages. Please try again.'
                });
            };
        }

        // Search events
        document.getElementById('eventSearch').addEventListener('input', function(e) {
            const query = e.target.value.toLowerCase();
            filteredEvents = allEvents.filter(event =>
                event.name.toLowerCase().includes(query)
            );
            displayEvents(filteredEvents);
            updateEventsCount();
        });

        // Search users
        document.getElementById('userSearch').addEventListener('input', function(e) {
            const query = e.target.value.toLowerCase();
            const userItems = document.querySelectorAll('.users-column .user-item');

            userItems.forEach(item => {
                const name = item.querySelector('h4').textContent.toLowerCase();
                const phone = item.querySelector('.user-phone').textContent.toLowerCase();
                item.style.display = (name.includes(query) || phone.includes(query)) ? 'flex' : 'none';
            });
        });

        // Helper function to escape HTML
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Helper function to show error
        function showError(message) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }

        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function() {
            statusModal = document.getElementById('statusModal');
            initFirebase();

            // Close modal when clicking outside
            statusModal.addEventListener('click', function(e) {
                if (e.target === statusModal) {
                    statusModal.style.display = 'none';
                }
            });

            // Mobile navigation
            window.backToEvents = function() {
                document.querySelector('.users-column').classList.remove('active');
                document.querySelector('.message-column').classList.remove('active');
                currentEvent = null;
            };

            window.backToUsers = function() {
                document.querySelector('.message-column').classList.remove('active');
            };
        });

        // Enter key to send message
        document.getElementById('messageText').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (!document.getElementById('sendMessageBtn').disabled) {
                    document.getElementById('sendMessageBtn').click();
                }
            }
        });
    </script>
</body>

</html>