<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webinar Manage - FastOpp</title>
    <link rel="icon" type="image/x-icon" href="{{ url_for('static', path='/favicon.ico') }}">
    <script src="https://unpkg.com/htmx.org@2.0.6"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'ai-blue': '#3B82F6',
                        'ai-purple': '#8B5CF6'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="min-h-screen flex flex-col">
        {% include 'partials/header.html' %}

        <!-- Webinar Manage Header -->
        <div class="bg-gradient-to-r from-ai-blue to-ai-purple text-white py-8">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="text-3xl font-bold mb-2">Webinar Manage</h1>
                        <p class="text-blue-100">Manage webinar attendees and their photos</p>
                    </div>
                    
                    <!-- Refresh Button -->
                    <button onclick="loadRegistrants()" 
                            class="bg-white bg-opacity-20 hover:bg-opacity-30 text-white px-6 py-2 rounded-lg font-semibold transition-all duration-200 flex items-center space-x-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                        </svg>
                        <span>Refresh</span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <main class="flex-grow">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                <!-- Registrants List -->
                <div class="bg-white rounded-xl shadow-lg p-8">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-2xl font-semibold text-gray-900">All Registrants</h3>
                        <div class="flex items-center space-x-4">
                            <div class="text-sm text-gray-500" id="registrantsCount">0 registrants</div>
                        </div>
                    </div>
                    
                    <!-- Search Bar -->
                    <div class="mb-6">
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                </svg>
                            </div>
                            <input type="text" 
                                   id="searchInput" 
                                   placeholder="Search registrants..." 
                                   class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-ai-blue focus:border-transparent text-gray-700 placeholder-gray-400 transition-colors duration-200">
                        </div>
                    </div>
                    
                    <div id="registrantsContainer">
                        <!-- Loading state -->
                        <div class="flex items-center justify-center py-12">
                            <svg class="animate-spin h-8 w-8 text-ai-blue" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            <span class="ml-3 text-gray-600">Loading registrants...</span>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        
        {% include 'partials/footer.html' %}
    </div>

    <!-- Modal for Photo Upload -->
    <div id="uploadModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl p-8 max-w-md w-full mx-4">
            <h3 class="text-xl font-semibold text-gray-900 mb-4">Upload Photo</h3>
            <form id="uploadForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Registrant</label>
                    <div class="text-gray-900 font-medium" id="uploadRegistrantName"></div>
                </div>
                <div>
                    <label for="photo" class="block text-sm font-medium text-gray-700 mb-2">Photo</label>
                    <input type="file" id="photo" name="photo" accept="image/*" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-ai-blue focus:border-transparent">
                </div>
                <div>
                    <label for="description" class="block text-sm font-medium text-gray-700 mb-2">Description (optional)</label>
                    <input type="text" id="description" name="description"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-ai-blue focus:border-transparent">
                </div>
                <div class="flex space-x-3 pt-4">
                    <button type="submit" 
                            class="flex-1 bg-ai-blue hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition duration-200">
                        Upload Photo
                    </button>
                    <button type="button" onclick="closeUploadModal()"
                            class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-700 font-medium py-2 px-4 rounded-lg transition duration-200">
                        Cancel
                    </button>
                </div>
            </form>
            <div id="uploadResult" class="mt-4"></div>
        </div>
    </div>

    <!-- Modal for Edit Notes -->
    <div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl p-8 max-w-md w-full mx-4">
            <h3 class="text-xl font-semibold text-gray-900 mb-4">Edit Notes</h3>
            <form id="editForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Registrant</label>
                    <div class="text-gray-900 font-medium" id="editRegistrantName"></div>
                </div>
                <div>
                    <label for="notes" class="block text-sm font-medium text-gray-700 mb-2">Notes</label>
                    <textarea id="notes" name="notes" rows="4"
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-ai-blue focus:border-transparent"></textarea>
                </div>
                <div class="flex space-x-3 pt-4">
                    <button type="submit" 
                            class="flex-1 bg-ai-blue hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition duration-200">
                        Update Notes
                    </button>
                    <button type="button" onclick="closeEditModal()"
                            class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-700 font-medium py-2 px-4 rounded-lg transition duration-200">
                        Cancel
                    </button>
                </div>
            </form>
            <div id="editResult" class="mt-4"></div>
        </div>
    </div>

    <script>
        // Global variables
        let currentRegistrantId = null;
        let currentRegistrantName = null;
        let allRegistrants = []; // Store all registrants for search functionality

        // Load registrants on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadRegistrants();
        });

        // Load registrants function
        function loadRegistrants() {
            fetch('/api/registrants')
                .then(response => response.json())
                .then(data => {
                    allRegistrants = data.registrants; // Store all registrants
                    displayRegistrants(data.registrants);
                })
                .catch(error => {
                    console.error('Error loading registrants:', error);
                    document.getElementById('registrantsContainer').innerHTML = 
                        '<div class="text-center py-12"><p class="text-red-600">Error loading registrants</p></div>';
                });
        }

        // Display registrants
        function displayRegistrants(registrants) {
            const container = document.getElementById('registrantsContainer');
            
            if (!registrants || registrants.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-12">
                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                        </svg>
                        <h3 class="mt-2 text-sm font-medium text-gray-900">No registrants</h3>
                        <p class="mt-1 text-sm text-gray-500">No webinar registrants found.</p>
                    </div>
                `;
                return;
            }

            const registrantsHtml = registrants.map(registrant => {
                const photoHtml = registrant.photo_url 
                    ? `<img src="${registrant.photo_url}" alt="Photo" class="w-20 h-20 object-cover rounded-full border-4 border-ai-blue shadow-lg">`
                    : `<div class="w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center text-gray-500 text-xl shadow-lg">👤</div>`;
                
                return `
                    <div class="bg-white border border-gray-200 rounded-xl p-6 shadow-sm hover:shadow-md transition-shadow">
                        <div class="flex items-start space-x-4">
                            <div class="flex-shrink-0">
                                ${photoHtml}
                            </div>
                            <div class="flex-1 min-w-0">
                                <h4 class="text-lg font-semibold text-gray-900 mb-2">${registrant.name}</h4>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm text-gray-600 mb-4">
                                    <p><span class="font-medium">Email:</span> ${registrant.email}</p>
                                    <p><span class="font-medium">Company:</span> ${registrant.company || 'N/A'}</p>
                                    <p><span class="font-medium">Webinar:</span> ${registrant.webinar_title}</p>
                                    <p><span class="font-medium">Status:</span> 
                                        <span class="px-2 py-1 text-xs rounded-full ${registrant.status === 'confirmed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                                            ${registrant.status}
                                        </span>
                                    </p>
                                </div>
                                <div class="mb-4">
                                    <p class="text-sm text-gray-600">
                                        <span class="font-medium">Notes:</span> 
                                        <span class="text-gray-700">${registrant.notes || 'No notes'}</span>
                                    </p>
                                </div>
                                
                                <!-- Management Icons -->
                                <div class="flex items-center space-x-2">
                                    <!-- Add Photo Button -->
                                    <button onclick="openUploadModal('${registrant.id}', '${registrant.name.replace(/'/g, "\\'")}')"
                                            class="p-2 text-gray-600 hover:text-ai-blue hover:bg-blue-50 rounded-lg transition-colors duration-200"
                                            title="Add Photo">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                                        </svg>
                                    </button>
                                    
                                    <!-- Edit Notes Button -->
                                    <button onclick="openEditModal('${registrant.id}', '${registrant.name.replace(/'/g, "\\'")}', '${(registrant.notes || '').replace(/'/g, "\\'")}')"
                                            class="p-2 text-gray-600 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors duration-200"
                                            title="Edit Notes">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                        </svg>
                                    </button>
                                    
                                    ${registrant.photo_url ? `
                                    <!-- Delete Photo Button -->
                                    <button onclick="deletePhoto('${registrant.id}')"
                                            class="p-2 text-gray-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors duration-200"
                                            title="Delete Photo">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                        </svg>
                                    </button>
                                    ` : ''}
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
            
            container.innerHTML = registrantsHtml;
            document.getElementById('registrantsCount').textContent = `${registrants.length} registrants`;
        }

        // Modal functions
        function openUploadModal(registrantId, registrantName) {
            currentRegistrantId = registrantId;
            currentRegistrantName = registrantName;
            document.getElementById('uploadRegistrantName').textContent = registrantName;
            document.getElementById('uploadModal').classList.remove('hidden');
        }

        function closeUploadModal() {
            document.getElementById('uploadModal').classList.add('hidden');
            document.getElementById('uploadForm').reset();
            document.getElementById('uploadResult').innerHTML = '';
        }

        function openEditModal(registrantId, registrantName, notes) {
            currentRegistrantId = registrantId;
            currentRegistrantName = registrantName;
            document.getElementById('editRegistrantName').textContent = registrantName;
            document.getElementById('notes').value = notes;
            document.getElementById('editModal').classList.remove('hidden');
        }

        function closeEditModal() {
            document.getElementById('editModal').classList.add('hidden');
            document.getElementById('editForm').reset();
            document.getElementById('editResult').innerHTML = '';
        }

        // Delete photo function
        function deletePhoto(registrantId) {
            if (!confirm('Are you sure you want to delete this photo?')) {
                return;
            }
            
            fetch(`/delete-photo/${registrantId}`, {
                method: 'DELETE'
            })
            .then(response => response.text())
            .then(() => {
                loadRegistrants();
            })
            .catch(error => {
                console.error('Error deleting photo:', error);
                alert('Error deleting photo');
            });
        }

        // Form submissions
        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData();
            formData.append('photo', document.getElementById('photo').files[0]);
            formData.append('description', document.getElementById('description').value);
            
            fetch(`/upload-photo/${currentRegistrantId}`, {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(result => {
                document.getElementById('uploadResult').innerHTML = result;
                if (result.includes('successfully')) {
                    setTimeout(() => {
                        closeUploadModal();
                        loadRegistrants();
                    }, 1000);
                }
            })
            .catch(error => {
                console.error('Error uploading photo:', error);
                document.getElementById('uploadResult').innerHTML = '<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">Error uploading photo</div>';
            });
        });

        document.getElementById('editForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData();
            formData.append('notes', document.getElementById('notes').value);
            
            fetch(`/update-notes/${currentRegistrantId}`, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.text();
            })
            .then(result => {
                document.getElementById('editResult').innerHTML = result;
                if (result.includes('successfully')) {
                    setTimeout(() => {
                        closeEditModal();
                        loadRegistrants();
                    }, 1000);
                }
            })
            .catch(error => {
                console.error('Error updating notes:', error);
                document.getElementById('editResult').innerHTML = `<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">Error updating notes: ${error.message}</div>`;
            });
        });

        // Close modals when clicking outside
        document.getElementById('uploadModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeUploadModal();
            }
        });

        document.getElementById('editModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeEditModal();
            }
        });

        // Close modals with Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeUploadModal();
                closeEditModal();
            }
        });

        // Search functionality
        document.getElementById('searchInput').addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase().trim();
            
            if (searchTerm === '') {
                // If search is empty, show all registrants
                displayRegistrants(allRegistrants);
                return;
            }
            
            // Filter registrants based on search term
            const filteredRegistrants = allRegistrants.filter(registrant => {
                const searchableFields = [
                    registrant.name || '',
                    registrant.email || '',
                    registrant.company || '',
                    registrant.webinar_title || '',
                    registrant.notes || '',
                    registrant.status || ''
                ].map(field => field.toLowerCase());
                
                return searchableFields.some(field => field.includes(searchTerm));
            });
            
            displayRegistrants(filteredRegistrants);
        });
    </script>
</body>
</html> 