/**
 * VMO Manager Admin JavaScript
 */

jQuery(document).ready(function($) {
    
    // Initialize admin functionality
    vmoInitializeAdmin();
    
    function vmoInitializeAdmin() {
        // Handle gift tokens form
        $('#vmo-gift-tokens-form').on('submit', function(e) {
            e.preventDefault();
            vmoSubmitGiftTokens();
        });
        
        // Handle affiliate forms
        $('.vmo-affiliate-form').on('submit', function(e) {
            // Add loading state
            $(this).addClass('vmo-loading');
        });
        
        // Initialize tooltips
        $('[data-tooltip]').each(function() {
            $(this).attr('title', $(this).data('tooltip'));
        });
        
        // Auto-refresh dashboard stats every 5 minutes
        if ($('.vmo-dashboard-widgets').length) {
            setInterval(vmoRefreshDashboardStats, 300000); // 5 minutes
        }
    }
    
    // Gift tokens functionality
    window.vmoOpenGiftTokensModal = function() {
        $('#vmo-gift-tokens-modal').show();
    };
    
    window.vmoCloseModal = function(modalId) {
        $('#' + modalId).hide();
    };
    
    function vmoSubmitGiftTokens() {
        const formData = {
            action: 'vmo_manager_admin_action',
            admin_action: 'gift_tokens',
            nonce: vmoManagerAdmin.nonce,
            installation_id: $('#gift-installation-id').val(),
            token_amount: $('#gift-token-amount').val(),
            reason: $('#gift-reason').val(),
            send_email: $('#gift-send-email').is(':checked')
        };
        
        $('#vmo-gift-tokens-form').addClass('vmo-loading');
        
        $.post(vmoManagerAdmin.ajaxurl, formData)
            .done(function(response) {
                if (response.success) {
                    vmoShowNotice('Balance updated successfully!', 'success');
                    vmoCloseModal('vmo-gift-tokens-modal');
                    $('#vmo-gift-tokens-form')[0].reset();
                } else {
                    vmoShowNotice('Error: ' + response.data, 'error');
                }
            })
            .fail(function() {
                vmoShowNotice('Server error occurred', 'error');
            })
            .always(function() {
                $('#vmo-gift-tokens-form').removeClass('vmo-loading');
            });
    }
    
    // User management functions
    window.vmoEditUser = function(installationId) {
        // Open user edit modal (implementation depends on your needs)
        console.log('Edit user:', installationId);
    };
    
    window.vmoGiftTokens = function(installationId) {
        $('#gift-installation-id').val(installationId);
        vmoOpenGiftTokensModal();
    };
    
    // Affiliate management functions
    window.vmoEditAffiliate = function(affiliateId) {
        // Open affiliate edit modal
        console.log('Edit affiliate:', affiliateId);
    };
    
    window.vmoViewAffiliateDetails = function(affiliateId) {
        // Show affiliate details modal with stats
        vmoLoadAffiliateDetails(affiliateId);
    };
    
    window.vmoProcessPayout = function(affiliateId) {
        if (confirm('Are you sure you want to process the payout for this affiliate?')) {
            vmoExecutePayout(affiliateId);
        }
    };
    
    function vmoLoadAffiliateDetails(affiliateId) {
        $.post(vmoManagerAdmin.ajaxurl, {
            action: 'vmo_manager_admin_action',
            admin_action: 'get_affiliate_details',
            nonce: vmoManagerAdmin.nonce,
            affiliate_id: affiliateId
        })
        .done(function(response) {
            if (response.success) {
                vmoShowAffiliateDetailsModal(response.data);
            }
        });
    }
    
    function vmoExecutePayout(affiliateId) {
        $.post(vmoManagerAdmin.ajaxurl, {
            action: 'vmo_manager_admin_action',
            admin_action: 'process_payout',
            nonce: vmoManagerAdmin.nonce,
            affiliate_id: affiliateId
        })
        .done(function(response) {
            if (response.success) {
                vmoShowNotice('Payout processed successfully!', 'success');
                location.reload();
            } else {
                vmoShowNotice('Error: ' + response.data, 'error');
            }
        });
    }
    
    // Export functions
    window.vmoExportUsers = function() {
        const exportData = {
            action: 'vmo_manager_admin_action',
            admin_action: 'export_users',
            nonce: vmoManagerAdmin.nonce,
            format: 'csv'
        };
        
        // Create download link
        const params = new URLSearchParams(exportData);
        const downloadUrl = vmoManagerAdmin.ajaxurl + '?' + params.toString();
        
        // Trigger download
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = 'vmo-users-export.csv';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };
    
    // Bulk email functions
    window.vmoSendBulkEmail = function() {
        vmoOpenBulkEmailModal();
    };
    
    function vmoOpenBulkEmailModal() {
        // Create and show bulk email modal
        const modalHtml = `
            <div id="vmo-bulk-email-modal" class="vmo-modal">
                <div class="vmo-modal-content">
                    <h3>📧 Send Bulk Email</h3>
                    <form id="vmo-bulk-email-form">
                        <table class="form-table">
                            <tr>
                                <th><label for="bulk-email-subject">Subject</label></th>
                                <td><input type="text" id="bulk-email-subject" name="subject" class="regular-text" required></td>
                            </tr>
                            <tr>
                                <th><label for="bulk-email-target">Target Users</label></th>
                                <td>
                                    <select id="bulk-email-target" name="target">
                                        <option value="all">All Users</option>
                                        <option value="free">Unpaid Users Only</option>
                                        <option value="subscribers">Subscribers Only</option>
                                        <option value="low_tokens">Low Balance Users</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="bulk-email-message">Message</label></th>
                                <td><textarea id="bulk-email-message" name="message" rows="8" class="large-text" required></textarea></td>
                            </tr>
                        </table>
                        <p class="submit">
                            <button type="submit" class="button button-primary">Send Email</button>
                            <button type="button" class="button" onclick="vmoCloseModal('vmo-bulk-email-modal')">Cancel</button>
                        </p>
                    </form>
                </div>
            </div>
        `;
        
        $('body').append(modalHtml);
        
        $('#vmo-bulk-email-form').on('submit', function(e) {
            e.preventDefault();
            vmoSubmitBulkEmail();
        });
    }
    
    function vmoSubmitBulkEmail() {
        const formData = {
            action: 'vmo_manager_admin_action',
            admin_action: 'send_bulk_email',
            nonce: vmoManagerAdmin.nonce,
            subject: $('#bulk-email-subject').val(),
            target: $('#bulk-email-target').val(),
            message: $('#bulk-email-message').val()
        };
        
        $('#vmo-bulk-email-form').addClass('vmo-loading');
        
        $.post(vmoManagerAdmin.ajaxurl, formData)
            .done(function(response) {
                if (response.success) {
                    vmoShowNotice('Bulk email queued successfully!', 'success');
                    vmoCloseModal('vmo-bulk-email-modal');
                    $('#vmo-bulk-email-modal').remove();
                } else {
                    vmoShowNotice('Error: ' + response.data, 'error');
                }
            })
            .always(function() {
                $('#vmo-bulk-email-form').removeClass('vmo-loading');
            });
    }
    
    // Dashboard refresh
    function vmoRefreshDashboardStats() {
        $.post(vmoManagerAdmin.ajaxurl, {
            action: 'vmo_manager_admin_action',
            admin_action: 'refresh_dashboard',
            nonce: vmoManagerAdmin.nonce
        })
        .done(function(response) {
            if (response.success) {
                // Update stats without full page reload
                $('.vmo-stat-number').each(function() {
                    const statType = $(this).closest('.vmo-stat').find('.vmo-stat-label').text().toLowerCase().replace(/\s+/g, '_');
                    if (response.data[statType] !== undefined) {
                        $(this).text(response.data[statType]);
                    }
                });
            }
        });
    }
    
    // Utility functions
    function vmoShowNotice(message, type = 'info') {
        const noticeClass = type === 'error' ? 'notice-error' : 
                           type === 'success' ? 'notice-success' : 'notice-info';
        
        const notice = $(`
            <div class="notice ${noticeClass} is-dismissible">
                <p>${message}</p>
                <button type="button" class="notice-dismiss">
                    <span class="screen-reader-text">Dismiss this notice.</span>
                </button>
            </div>
        `);
        
        $('.wrap > h1').after(notice);
        
        // Auto-dismiss after 5 seconds
        setTimeout(function() {
            notice.fadeOut(function() {
                $(this).remove();
            });
        }, 5000);
        
        // Handle manual dismiss
        notice.find('.notice-dismiss').on('click', function() {
            notice.fadeOut(function() {
                $(this).remove();
            });
        });
    }
    
    function vmoShowAffiliateDetailsModal(affiliateData) {
        const modalHtml = `
            <div id="vmo-affiliate-details-modal" class="vmo-modal">
                <div class="vmo-modal-content">
                    <h3>👤 ${affiliateData.name} - Affiliate Details</h3>
                    <div class="vmo-affiliate-stats">
                        <div class="vmo-stats-grid">
                            <div class="vmo-stat">
                                <span class="vmo-stat-number">${affiliateData.total_referrals}</span>
                                <span class="vmo-stat-label">Total Referrals</span>
                            </div>
                            <div class="vmo-stat">
                                <span class="vmo-stat-number">$${affiliateData.total_commission}</span>
                                <span class="vmo-stat-label">Total Commission</span>
                            </div>
                            <div class="vmo-stat">
                                <span class="vmo-stat-number">$${affiliateData.pending_commission}</span>
                                <span class="vmo-stat-label">Pending</span>
                            </div>
                            <div class="vmo-stat">
                                <span class="vmo-stat-number">${affiliateData.commission_rate}%</span>
                                <span class="vmo-stat-label">Commission Rate</span>
                            </div>
                        </div>
                    </div>
                    <div class="vmo-affiliate-links">
                        <h4>Tracking Links</h4>
                        <p><strong>Main:</strong> <code>${affiliateData.tracking_links.main}</code></p>
                        <p><strong>Download:</strong> <code>${affiliateData.tracking_links.download}</code></p>
                    </div>
                    <p class="submit">
                        <button type="button" class="button button-primary" onclick="vmoCloseModal('vmo-affiliate-details-modal')">Close</button>
                    </p>
                </div>
            </div>
        `;
        
        $('body').append(modalHtml);
    }
    
    // Real-time notifications (if you want to implement)
    function vmoInitializeRealTimeNotifications() {
        // This could connect to a WebSocket or use long polling
        // for real-time updates of new users, support tickets, etc.
    }
    
    // Enhanced table interactions
    $('.wp-list-table tbody tr').hover(
        function() {
            $(this).addClass('hover');
        },
        function() {
            $(this).removeClass('hover');
        }
    );
    
    // Settings form validation
    $('form').on('submit', function() {
        const $form = $(this);
        const requiredFields = $form.find('[required]');
        let hasErrors = false;
        
        requiredFields.each(function() {
            if (!$(this).val().trim()) {
                $(this).addClass('error');
                hasErrors = true;
            } else {
                $(this).removeClass('error');
            }
        });
        
        if (hasErrors) {
            vmoShowNotice('Please fill in all required fields', 'error');
            return false;
        }
    });
    
    // Auto-save settings (draft mode)
    let settingsTimer;
    $('.vmo-settings-section input, .vmo-settings-section textarea, .vmo-settings-section select').on('input change', function() {
        clearTimeout(settingsTimer);
        settingsTimer = setTimeout(function() {
            vmoAutoSaveSettings();
        }, 2000);
    });
    
    function vmoAutoSaveSettings() {
        // Auto-save draft settings
        const settingsData = {};
        $('.vmo-settings-section input, .vmo-settings-section textarea, .vmo-settings-section select').each(function() {
            settingsData[$(this).attr('name')] = $(this).val();
        });
        
        localStorage.setItem('vmo_manager_settings_draft', JSON.stringify(settingsData));
    }
    
    // Load draft settings on page load
    const draftSettings = localStorage.getItem('vmo_manager_settings_draft');
    if (draftSettings) {
        const settings = JSON.parse(draftSettings);
        Object.keys(settings).forEach(function(key) {
            const $field = $(`[name="${key}"]`);
            if ($field.length && !$field.val()) {
                $field.val(settings[key]);
            }
        });
    }
});
