/**
 * Special Access Links - Admin Interface JavaScript
 * Handles CRUD operations, modal interactions, and UI updates
 */

// State management
let currentEditId = null;

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    initializeSearchFilter();
    initializeFormValidation();
    initializeLinkCodePreview();
});

/**
 * Search/Filter functionality for links table
 */
function initializeSearchFilter() {
    const searchInput = document.getElementById('searchLinks');
    if (!searchInput) return;
    
    // Add clear button
    addClearButton(searchInput);
    
    searchInput.addEventListener('input', function(e) {
        performSearch(e.target.value);
    });
    
    // Add keyboard shortcuts
    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            clearSearch();
        }
    });
}

/**
 * Perform search functionality
 */
function performSearch(searchTerm) {
    const searchTermLower = searchTerm.toLowerCase().trim();
    const table = document.querySelector('table');
    if (!table) return;
    
    const rows = table.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        const shouldShow = searchTermLower === '' || text.includes(searchTermLower);
        row.style.display = shouldShow ? '' : 'none';
    });
    
    // Show/hide the "no results" message if needed
    updateNoResultsMessage(searchTermLower, rows);
}

/**
 * Clear search
 */
function clearSearch() {
    const searchInput = document.getElementById('searchLinks');
    if (searchInput) {
        searchInput.value = '';
        performSearch('');
    }
}

/**
 * Add clear button to search input
 */
function addClearButton(searchInput) {
    const searchContainer = searchInput.parentElement;
    
    const clearButton = document.createElement('button');
    clearButton.type = 'button';
    clearButton.className = 'search-clear-btn';
    clearButton.innerHTML = '<i class="fas fa-times"></i>';
    clearButton.title = 'Clear search';
    clearButton.style.cssText = `
        background: none;
        border: none;
        color: #6b7280;
        cursor: pointer;
        padding: 0.25rem;
        border-radius: 4px;
        transition: all 0.2s;
        display: none;
    `;
    
    clearButton.addEventListener('click', clearSearch);
    
    searchContainer.appendChild(clearButton);
    
    // Show/hide clear button based on input
    searchInput.addEventListener('input', function() {
        clearButton.style.display = this.value ? 'block' : 'none';
    });
}

/**
 * Update no results message visibility
 */
function updateNoResultsMessage(searchTerm, rows) {
    const visibleRows = Array.from(rows).filter(row => row.style.display !== 'none');
    const noResultsMsg = document.getElementById('noResultsMessage');
    
    if (searchTerm && visibleRows.length === 0) {
        if (!noResultsMsg) {
            createNoResultsMessage();
        } else {
            noResultsMsg.style.display = 'block';
        }
    } else {
        if (noResultsMsg) {
            noResultsMsg.style.display = 'none';
        }
    }
}

/**
 * Create no results message
 */
function createNoResultsMessage() {
    const table = document.querySelector('table');
    if (!table) return;
    
    const tbody = table.querySelector('tbody');
    if (!tbody) return;
    
    const noResultsRow = document.createElement('tr');
    noResultsRow.id = 'noResultsMessage';
    noResultsRow.innerHTML = `
        <td colspan="9" style="text-align: center; padding: 3rem 1rem; color: #6b7280; font-style: italic;">
            <i class="fas fa-search" style="font-size: 2rem; color: #d1d5db; margin-bottom: 1rem; display: block;"></i>
            No links found matching your search
        </td>
    `;
    
    tbody.appendChild(noResultsRow);
}

/**
 * Form validation
 */
function initializeFormValidation() {
    const form = document.getElementById('linkForm');
    if (!form) return;
    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Validate at least one product is selected
        const selectedProducts = form.querySelectorAll('input[name="product_ids[]"]:checked');
        if (selectedProducts.length === 0) {
            showToast('Please select at least one product', 'error');
            return;
        }
        
        // Validate link code format
        const linkCode = document.getElementById('linkCode').value;
        if (!/^[A-Za-z0-9_-]+$/.test(linkCode)) {
            showToast('Link code can only contain letters, numbers, dashes, and underscores', 'error');
            return;
        }
        
        saveLink();
    });
}

/**
 * Link code preview updater
 */
function initializeLinkCodePreview() {
    const linkCodeInput = document.getElementById('linkCode');
    if (!linkCodeInput) return;
    
    linkCodeInput.addEventListener('input', function(e) {
        const code = e.target.value || 'CODE';
        document.getElementById('previewCode').textContent = code;
        document.getElementById('urlCode').textContent = code;
    });
}

/**
 * Open create modal
 */
function openCreateModal() {
    currentEditId = null;
    document.getElementById('modalTitle').textContent = 'Create Special Access Link';
    document.getElementById('submitBtnText').textContent = 'Create Link';
    document.getElementById('linkForm').reset();
    document.getElementById('linkId').value = '';
    
    // Set defaults
    document.getElementById('isActive').checked = true;
    document.getElementById('includeVisible').checked = true;
    document.getElementById('customMessage').value = 'You have exclusive access to additional registration options';
    
    // Clear product selections
    document.querySelectorAll('input[name="product_ids[]"]').forEach(cb => cb.checked = false);
    
    // Reset preview
    document.getElementById('previewCode').textContent = 'CODE';
    document.getElementById('urlCode').textContent = 'CODE';
    
    openModal();
}

/**
 * Edit existing link
 */
async function editLink(linkId) {
    try {
        const response = await fetch(`special_access_links_api.php?action=get&id=${linkId}`);
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || 'Failed to load link');
        }
        
        const link = result.data;
        currentEditId = linkId;
        
        // Populate form
        document.getElementById('modalTitle').textContent = 'Edit Special Access Link';
        document.getElementById('submitBtnText').textContent = 'Update Link';
        document.getElementById('linkId').value = link.id;
        document.getElementById('linkName').value = link.link_name;
        document.getElementById('linkCode').value = link.link_code;
        document.getElementById('description').value = link.description || '';
        document.getElementById('customMessage').value = link.custom_message || 'You have exclusive access to additional registration options';
        document.getElementById('isActive').checked = link.is_active == 1;
        document.getElementById('includeVisible').checked = link.include_visible_products == 1;
        document.getElementById('expiresAt').value = link.expires_at ? formatDateTimeLocal(link.expires_at) : '';
        
        // Update preview
        document.getElementById('previewCode').textContent = link.link_code;
        document.getElementById('urlCode').textContent = link.link_code;
        
        // Set product selections
        document.querySelectorAll('input[name="product_ids[]"]').forEach(cb => cb.checked = false);
        const productIds = JSON.parse(link.product_ids || '[]');
        productIds.forEach(productId => {
            const checkbox = document.getElementById(`product_${productId}`);
            if (checkbox) checkbox.checked = true;
        });
        
        openModal();
    } catch (error) {
        console.error('Error loading link:', error);
        showToast(error.message, 'error');
    }
}

/**
 * View link details
 */
async function viewLink(linkId) {
    try {
        const response = await fetch(`special_access_links_api.php?action=get&id=${linkId}`);
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || 'Failed to load link');
        }
        
        const link = result.data;
        const productIds = JSON.parse(link.product_ids || '[]');
        
        // Get product names
        const products = ALL_PRODUCTS.filter(p => productIds.includes(p.id.toString()) || productIds.includes(p.id));
        
        const fullUrl = `${BASE_URL}?access=${link.link_code}`;
        const isExpired = link.expires_at && new Date(link.expires_at) < new Date();
        
        let html = `
            <div class="view-details">
                <div class="detail-section">
                    <h3>Basic Information</h3>
                    <dl class="detail-list">
                        <dt>Link Name:</dt>
                        <dd>${escapeHtml(link.link_name)}</dd>
                        
                        <dt>Link Code:</dt>
                        <dd><code>${escapeHtml(link.link_code)}</code></dd>
                        
                        ${link.description ? `
                        <dt>Description:</dt>
                        <dd>${escapeHtml(link.description)}</dd>
                        ` : ''}
                        
                        <dt>Full URL:</dt>
                        <dd>
                            <div class="url-copy-box">
                                <code>${escapeHtml(fullUrl)}</code>
                                <button class="btn-icon" onclick="copyLinkUrl('${escapeHtml(link.link_code)}')">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                        </dd>
                    </dl>
                </div>
                
                <div class="detail-section">
                    <h3>Status & Access</h3>
                    <dl class="detail-list">
                        <dt>Status:</dt>
                        <dd>
                            <span class="status-badge status-${link.is_active && !isExpired ? 'active' : 'inactive'}">
                                ${isExpired ? 'Expired' : (link.is_active ? 'Active' : 'Inactive')}
                            </span>
                        </dd>
                        
                        <dt>Expires:</dt>
                        <dd>${link.expires_at ? formatDateTime(link.expires_at) : 'Never'}</dd>
                        
                        <dt>Access Count:</dt>
                        <dd>${Number(link.access_count).toLocaleString()} times</dd>
                        
                        <dt>Last Accessed:</dt>
                        <dd>${link.last_accessed_at ? formatDateTime(link.last_accessed_at) : 'Never'}</dd>
                        
                        <dt>Conversions:</dt>
                        <dd>${Number(link.conversion_count || 0).toLocaleString()}</dd>
                        
                        <dt>Conversion Rate:</dt>
                        <dd>${link.access_count > 0 ? ((link.conversion_count || 0) / link.access_count * 100).toFixed(1) : '0'}%</dd>
                    </dl>
                </div>
                
                <div class="detail-section">
                    <h3>Products (${products.length})</h3>
                    <div class="product-list">
                        ${products.map(p => `
                            <div class="product-item">
                                <span class="product-name">${escapeHtml(p.name)}</span>
                                <span class="product-code">${escapeHtml(p.product_code)}</span>
                                ${!p.show_in_frontend ? '<span class="badge badge-warning">Hidden</span>' : ''}
                            </div>
                        `).join('')}
                    </div>
                    ${link.include_visible_products ? 
                        '<p class="text-muted" style="margin-top: 1rem;"><i class="fas fa-info-circle"></i> Also shows all normally visible products</p>' 
                        : ''}
                </div>
                
                <div class="detail-section">
                    <h3>Audit Information</h3>
                    <dl class="detail-list">
                        <dt>Created:</dt>
                        <dd>${formatDateTime(link.created_at)}${link.creator_name ? ` by ${escapeHtml(link.creator_name)}` : ''}</dd>
                        
                        <dt>Last Updated:</dt>
                        <dd>${formatDateTime(link.updated_at)}</dd>
                    </dl>
                </div>
            </div>
        `;
        
        document.getElementById('viewModalContent').innerHTML = html;
        openViewModal();
    } catch (error) {
        console.error('Error viewing link:', error);
        showToast(error.message, 'error');
    }
}

/**
 * Save link (create or update)
 */
async function saveLink() {
    const form = document.getElementById('linkForm');
    const formData = new FormData(form);
    
    // Convert form data to JSON
    const data = {
        link_id: formData.get('link_id'),
        link_name: formData.get('link_name'),
        link_code: formData.get('link_code'),
        description: formData.get('description'),
        custom_message: formData.get('custom_message'),
        product_ids: Array.from(formData.getAll('product_ids[]')),
        include_visible_products: formData.get('include_visible_products') ? 1 : 0,
        is_active: formData.get('is_active') ? 1 : 0,
        expires_at: formData.get('expires_at') || null
    };
    
    try {
        const action = data.link_id ? 'update' : 'create';
        const response = await fetch('special_access_links_api.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'same-origin',
            body: JSON.stringify({ action, data })
        });
        
        // Debug: Log response status and text
        console.log('Response status:', response.status);
        const responseText = await response.text();
        console.log('Response text:', responseText);
        
        // Try to parse JSON
        let result;
        try {
            result = JSON.parse(responseText);
        } catch (jsonError) {
            console.error('JSON parse error:', jsonError);
            console.error('Response text that failed to parse:', responseText);
            // Show a friendlier error in the UI
            const snippet = responseText ? responseText.slice(0, 200) : 'No response body';
            throw new Error('Invalid response from server: ' + snippet);
        }
        
        if (!result.success) {
            throw new Error(result.error || 'Failed to save link');
        }
        
        showToast(action === 'create' ? 'Link created successfully!' : 'Link updated successfully!', 'success');
        closeModal();
        
        // Reload page to show updated data
        setTimeout(() => window.location.reload(), 1000);
    } catch (error) {
        console.error('Error saving link:', error);
        showToast(error.message, 'error');
    }
}

/**
 * Toggle link active status
 */
async function toggleLinkStatus(linkId, newStatus) {
    if (!confirm(`Are you sure you want to ${newStatus ? 'activate' : 'deactivate'} this link?`)) {
        return;
    }
    
    try {
        const response = await fetch('special_access_links_api.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'toggle_status',
                data: { link_id: linkId, is_active: newStatus }
            })
        });
        
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || 'Failed to update status');
        }
        
        showToast('Link status updated successfully!', 'success');
        setTimeout(() => window.location.reload(), 1000);
    } catch (error) {
        console.error('Error toggling status:', error);
        showToast(error.message, 'error');
    }
}

/**
 * Delete link
 */
async function deleteLink(linkId) {
    if (!confirm('Are you sure you want to delete this link? This action cannot be undone.')) {
        return;
    }
    
    try {
        const response = await fetch('special_access_links_api.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'delete',
                data: { link_id: linkId }
            })
        });
        
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || 'Failed to delete link');
        }
        
        showToast('Link deleted successfully!', 'success');
        setTimeout(() => window.location.reload(), 1000);
    } catch (error) {
        console.error('Error deleting link:', error);
        showToast(error.message, 'error');
    }
}

/**
 * Generate random link code
 */
function generateLinkCode() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let code = 'SAL-'; // Special Access Link prefix
    for (let i = 0; i < 8; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    document.getElementById('linkCode').value = code;
    document.getElementById('linkCode').dispatchEvent(new Event('input'));
}

/**
 * Copy link URL to clipboard
 */
function copyLinkUrl(linkCode) {
    const fullUrl = `${BASE_URL}?access=${linkCode}`;
    copyToClipboard(fullUrl);
    showToast('Link URL copied to clipboard!', 'success');
}

/**
 * Copy preview URL
 */
function copyPreviewUrl() {
    const code = document.getElementById('linkCode').value || 'CODE';
    const fullUrl = `${BASE_URL}?access=${code}`;
    copyToClipboard(fullUrl);
    showToast('URL copied to clipboard!', 'success');
}

/**
 * Copy text to clipboard
 */
function copyToClipboard(text) {
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text);
    } else {
        // Fallback for older browsers
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
    }
}

/**
 * Toggle category products selection
 */
function toggleCategoryProducts(category, select) {
    const checkboxes = document.querySelectorAll(`input[data-category="${category}"]`);
    checkboxes.forEach(cb => cb.checked = select);
}

/**
 * Modal controls
 */
function openModal() {
    document.getElementById('linkModal').classList.add('active');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('linkModal').classList.remove('active');
    document.body.style.overflow = '';
}

function openViewModal() {
    document.getElementById('viewModal').classList.add('active');
    document.body.style.overflow = 'hidden';
}

function closeViewModal() {
    document.getElementById('viewModal').classList.remove('active');
    document.body.style.overflow = '';
}

// Close modal on backdrop click
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal')) {
        if (e.target.id === 'linkModal') closeModal();
        if (e.target.id === 'viewModal') closeViewModal();
    }
});

// Close modal on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal();
        closeViewModal();
    }
});

/**
 * Show toast notification
 */
function showToast(message, type = 'success') {
    // Remove existing toasts
    document.querySelectorAll('.toast').forEach(t => t.remove());
    
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
        <span>${escapeHtml(message)}</span>
    `;
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

/**
 * Utility: Escape HTML
 */
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * Utility: Format datetime for display
 */
function formatDateTime(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

/**
 * Utility: Format datetime for input field
 */
function formatDateTimeLocal(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const offset = date.getTimezoneOffset();
    const localDate = new Date(date.getTime() - (offset * 60 * 1000));
    return localDate.toISOString().slice(0, 16);
}


