// TrustBeam Credit Admin Panel JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // Initialize admin panel functionality
    initAdminPanel();
});

function initAdminPanel() {
    // Sidebar toggle functionality
    initSidebarToggle();
    
    // Submenu functionality
    initSubmenus();
    
    // Search functionality
    initSearch();
    
    // Responsive behavior
    initResponsive();
    
    // Form enhancements
    initFormEnhancements();
}

// Sidebar toggle functionality
function initSidebarToggle() {
    const menuToggle = document.getElementById('menuToggle');
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.querySelector('.admin-main');
    
    if (menuToggle && sidebar) {
        menuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('active');
            
            // Update main content margin on mobile
            if (window.innerWidth <= 1024) {
                if (sidebar.classList.contains('active')) {
                    mainContent.style.marginLeft = '0';
                } else {
                    mainContent.style.marginLeft = '0';
                }
            }
        });
    }
    
    // Close sidebar when clicking outside on mobile
    document.addEventListener('click', function(e) {
        if (window.innerWidth <= 1024) {
            if (sidebar && !sidebar.contains(e.target) && !menuToggle.contains(e.target)) {
                sidebar.classList.remove('active');
            }
        }
    });
}

// Submenu functionality
function initSubmenus() {
    const submenuToggles = document.querySelectorAll('.submenu-toggle');
    
    submenuToggles.forEach(toggle => {
        toggle.addEventListener('click', function(e) {
            e.preventDefault();
            
            const parentLi = this.closest('li');
            const submenu = parentLi.querySelector('.submenu');
            
            // Close other open submenus
            document.querySelectorAll('.has-submenu.active').forEach(activeItem => {
                if (activeItem !== parentLi) {
                    activeItem.classList.remove('active');
                }
            });
            
            // Toggle current submenu
            parentLi.classList.toggle('active');
            
            // Animate submenu
            if (submenu) {
                if (parentLi.classList.contains('active')) {
                    submenu.style.display = 'block';
                    submenu.style.opacity = '0';
                    submenu.style.transform = 'translateY(-10px)';
                    
                    setTimeout(() => {
                        submenu.style.opacity = '1';
                        submenu.style.transform = 'translateY(0)';
                    }, 10);
                } else {
                    submenu.style.opacity = '0';
                    submenu.style.transform = 'translateY(-10px)';
                    
                    setTimeout(() => {
                        submenu.style.display = 'none';
                    }, 200);
                }
            }
        });
    });
}

// Search functionality
function initSearch() {
    const searchInput = document.querySelector('.search-bar input');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            
            if (searchTerm.length > 0) {
                // Implement search functionality here
                console.log('Searching for:', searchTerm);
                
                // Example: Highlight matching sidebar items
                highlightSearchResults(searchTerm);
            } else {
                // Clear search highlights
                clearSearchHighlights();
            }
        });
        
        // Search on Enter key
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch(this.value);
            }
        });
    }
}

// Highlight search results in sidebar
function highlightSearchResults(searchTerm) {
    const sidebarItems = document.querySelectorAll('.sidebar-nav li a');
    
    sidebarItems.forEach(item => {
        const text = item.textContent.toLowerCase();
        const parentLi = item.closest('li');
        
        if (text.includes(searchTerm)) {
            parentLi.style.backgroundColor = '#f0f2ff';
            item.style.color = '#667eea';
        } else {
            parentLi.style.backgroundColor = '';
            if (!parentLi.classList.contains('active')) {
                item.style.color = '';
            }
        }
    });
}

// Clear search highlights
function clearSearchHighlights() {
    const sidebarItems = document.querySelectorAll('.sidebar-nav li a');
    
    sidebarItems.forEach(item => {
        const parentLi = item.closest('li');
        parentLi.style.backgroundColor = '';
        
        if (!parentLi.classList.contains('active')) {
            item.style.color = '';
        }
    });
}

// Perform search action
function performSearch(searchTerm) {
    // Implement actual search functionality here
    console.log('Performing search for:', searchTerm);
    
    // Example: Redirect to search results page
    // window.location.href = `search.php?q=${encodeURIComponent(searchTerm)}`;
}

// Responsive behavior
function initResponsive() {
    // Handle window resize
    window.addEventListener('resize', function() {
        handleResize();
    });
    
    // Initial resize check
    handleResize();
}

function handleResize() {
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.querySelector('.admin-main');
    
    if (window.innerWidth <= 1024) {
        // Mobile/tablet view
        if (sidebar) {
            sidebar.style.transform = 'translateX(-100%)';
        }
        if (mainContent) {
            mainContent.style.marginLeft = '0';
        }
    } else {
        // Desktop view
        if (sidebar) {
            sidebar.style.transform = 'translateX(0)';
        }
        if (mainContent) {
            mainContent.style.marginLeft = '280px';
        }
    }
}

// Form enhancements
function initFormEnhancements() {
    // Auto-save form data
    initAutoSave();
    
    // Form validation
    initFormValidation();
    
    // File upload previews
    initFileUploads();
}

// Auto-save form data
function initAutoSave() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        const formId = form.id || 'form_' + Math.random().toString(36).substr(2, 9);
        form.id = formId;
        
        // Save form data on input change
        const inputs = form.querySelectorAll('input, select, textarea');
        inputs.forEach(input => {
            input.addEventListener('input', function() {
                saveFormData(formId, form);
            });
            
            input.addEventListener('change', function() {
                saveFormData(formId, form);
            });
        });
        
        // Restore form data on page load
        restoreFormData(formId, form);
    });
}

// Save form data to localStorage
function saveFormData(formId, form) {
    const formData = new FormData(form);
    const data = {};
    
    for (let [key, value] of formData.entries()) {
        data[key] = value;
    }
    
    localStorage.setItem(`form_${formId}`, JSON.stringify(data));
}

// Restore form data from localStorage
function restoreFormData(formId, form) {
    const savedData = localStorage.getItem(`form_${formId}`);
    
    if (savedData) {
        try {
            const data = JSON.parse(savedData);
            
            Object.keys(data).forEach(key => {
                const input = form.querySelector(`[name="${key}"]`);
                if (input && !input.value) {
                    input.value = data[key];
                }
            });
        } catch (e) {
            console.error('Error restoring form data:', e);
        }
    }
}

// Form validation
function initFormValidation() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!validateForm(this)) {
                e.preventDefault();
                showValidationErrors(this);
            }
        });
    });
}

// Validate form
function validateForm(form) {
    let isValid = true;
    const requiredFields = form.querySelectorAll('[required]');
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            field.classList.add('error');
        } else {
            field.classList.remove('error');
        }
        
        // Email validation
        if (field.type === 'email' && field.value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(field.value)) {
                isValid = false;
                field.classList.add('error');
            }
        }
        
        // Phone validation
        if (field.name === 'phone' && field.value) {
            const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/;
            if (!phoneRegex.test(field.value.replace(/\s/g, ''))) {
                isValid = false;
                field.classList.add('error');
            }
        }
    });
    
    return isValid;
}

// Show validation errors
function showValidationErrors(form) {
    const errorFields = form.querySelectorAll('.error');
    
    errorFields.forEach(field => {
        const errorMessage = document.createElement('div');
        errorMessage.className = 'field-error';
        errorMessage.textContent = getErrorMessage(field);
        
        // Remove existing error message
        const existingError = field.parentNode.querySelector('.field-error');
        if (existingError) {
            existingError.remove();
        }
        
        // Add new error message
        field.parentNode.appendChild(errorMessage);
    });
}

// Get error message for field
function getErrorMessage(field) {
    if (field.type === 'email') {
        return 'Please enter a valid email address';
    } else if (field.name === 'phone') {
        return 'Please enter a valid phone number';
    } else {
        return 'This field is required';
    }
}

// File upload functionality
function initFileUploads() {
    const fileInputs = document.querySelectorAll('input[type="file"]');
    
    fileInputs.forEach(input => {
        input.addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                // Show file info
                showFileInfo(this, file);
                
                // Preview image if it's an image file
                if (file.type.startsWith('image/')) {
                    showImagePreview(this, file);
                }
            }
        });
    });
}

// Show file information
function showFileInfo(input, file) {
    const fileNameElement = input.parentNode.querySelector('.file-name');
    if (fileNameElement) {
        fileNameElement.textContent = file.name;
        fileNameElement.style.color = '#28a745';
    }
}

// Show image preview
function showImagePreview(input, file) {
    const reader = new FileReader();
    
    reader.onload = function(e) {
        // Create preview container if it doesn't exist
        let previewContainer = input.parentNode.querySelector('.image-preview');
        if (!previewContainer) {
            previewContainer = document.createElement('div');
            previewContainer.className = 'image-preview';
            previewContainer.style.cssText = 'margin-top: 10px; text-align: center;';
            input.parentNode.appendChild(previewContainer);
        }
        
        // Show preview
        previewContainer.innerHTML = `
            <img src="${e.target.result}" alt="Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
        `;
    };
    
    reader.readAsDataURL(file);
}

// Utility functions
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // Style the notification
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        animation: slideIn 0.3s ease;
    `;
    
    // Set background color based on type
    switch (type) {
        case 'success':
            notification.style.backgroundColor = '#28a745';
            break;
        case 'error':
            notification.style.backgroundColor = '#dc3545';
            break;
        case 'warning':
            notification.style.backgroundColor = '#ffc107';
            notification.style.color = '#333';
            break;
        default:
            notification.style.backgroundColor = '#17a2b8';
    }
    
    // Add to page
    document.body.appendChild(notification);
    
    // Remove after 5 seconds
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 5000);
}

// Add CSS animations
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    .field-error {
        color: #dc3545;
        font-size: 0.8rem;
        margin-top: 5px;
        animation: fadeIn 0.3s ease;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    .error {
        border-color: #dc3545 !important;
    }
    
    .image-preview img {
        transition: transform 0.3s ease;
    }
    
    .image-preview img:hover {
        transform: scale(1.05);
    }
`;
document.head.appendChild(style);

// Export functions for global use
window.AdminPanel = {
    showNotification,
    validateForm,
    saveFormData,
    restoreFormData
};
