/**
 * Admin Email Page JavaScript
 *
 * @package Karate_Club_Manager
 * @since 1.0.57
 */

jQuery(document).ready(function($) {
    'use strict';

    // Get form elements
    var $form = $('#kcm-bulk-email-form');
    var $sendToAll = $('#macm_send_to_all');
    var $userIds = $('#macm_user_ids');
    var $selectedCount = $('#kcm-selected-count');
    var $previewBtn = $('#kcm-preview-email');

    // Handle form submission
    $form.on('submit', function(e) {
        e.preventDefault(); // Always prevent default - we'll use AJAX

        // Validate the form
        if (!validateForm()) {
            return false;
        }

        // Show recipients confirmation modal
        showRecipientsConfirmation(function(confirmed) {
            if (confirmed) {
                // Send email via AJAX
                sendEmailAjax();
            }
        });

        return false;
    });

    // Toggle user selection visibility
    $sendToAll.on('change', function() {
        if ($(this).is(':checked')) {
            $('#kcm-user-selection').hide();
            $userIds.prop('disabled', true);
        } else {
            $('#kcm-user-selection').show();
            $userIds.prop('disabled', false);
        }
    });

    // Update selected count
    $userIds.on('change', function() {
        var count = $(this).val() ? $(this).val().length : 0;

        if (count === 0) {
            $selectedCount.text('No users selected').css('color', '#d63638');
        } else if (count === 1) {
            $selectedCount.text('1 user selected').css('color', '#B11226');
        } else {
            $selectedCount.text(count + ' users selected').css('color', '#B11226');
        }
    });

    // Initialize count on load
    $userIds.trigger('change');

    // Show recipients confirmation modal
    function showRecipientsConfirmation(callback) {
        var sendToAllChecked = $sendToAll.is(':checked');
        var selectedUsers = $userIds.val();
        var membershipType = $('#macm_membership_type').val();
        var group = $('#macm_group').val();
        var memberStatus = $('#macm_member_status').val();

        // Get recipients via AJAX
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'macm_get_email_recipients',
                nonce: $('#macm_email_nonce').val(),
                send_to_all: sendToAllChecked ? '1' : '0',
                user_ids: selectedUsers,
                membership_type: membershipType,
                group: group,
                member_status: memberStatus
            },
            success: function(response) {
                if (response.success && response.data.emails) {
                    var emails = response.data.emails;
                    var count = emails.length;

                    // Create modal content
                    var modalHtml = '<div id="kcm-recipients-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 100000; display: flex; align-items: center; justify-content: center;">';
                    modalHtml += '<div style="background: white; padding: 30px; border-radius: 8px; max-width: 600px; max-height: 80vh; overflow-y: auto; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">';
                    modalHtml += '<h2 style="margin-top: 0; color: #B11226;">Confirm Email Recipients</h2>';
                    modalHtml += '<p style="font-size: 16px; margin-bottom: 20px;">This email will be sent to <strong>' + count + ' recipient(s)</strong>:</p>';
                    modalHtml += '<div style="max-height: 300px; overflow-y: auto; background: #F4F4F2; padding: 15px; border-radius: 4px; margin-bottom: 20px;">';
                    modalHtml += '<ul style="list-style: none; padding: 0; margin: 0;">';
                    emails.forEach(function(email) {
                        modalHtml += '<li style="padding: 8px; border-bottom: 1px solid #D1D5DB; font-family: monospace;">' + email + '</li>';
                    });
                    modalHtml += '</ul></div>';
                    modalHtml += '<div style="text-align: right;">';
                    modalHtml += '<button id="kcm-recipients-cancel" style="padding: 10px 20px; margin-right: 10px; background: #2F343A; color: white; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>';
                    modalHtml += '<button id="kcm-recipients-confirm" style="padding: 10px 20px; background: linear-gradient(135deg, #B11226 0%, #8F0E1E 100%); color: white; border: none; border-radius: 4px; cursor: pointer;">Send Email</button>';
                    modalHtml += '</div></div></div>';

                    $('body').append(modalHtml);

                    // Handle buttons
                    $('#kcm-recipients-confirm').on('click', function() {
                        $('#kcm-recipients-modal').remove();
                        callback(true);
                    });

                    $('#kcm-recipients-cancel').on('click', function() {
                        $('#kcm-recipients-modal').remove();
                        callback(false);
                    });

                    // Close on overlay click
                    $('#kcm-recipients-modal').on('click', function(e) {
                        if (e.target.id === 'kcm-recipients-modal') {
                            $(this).remove();
                            callback(false);
                        }
                    });
                } else {
                    alert('Error loading recipients. Please try again.');
                    callback(false);
                }
            },
            error: function() {
                alert('Error loading recipients. Please try again.');
                callback(false);
            }
        });
    }

    // Validate form
    function validateForm() {
        var sendToAllChecked = $sendToAll.is(':checked');
        var selectedUsers = $userIds.val();
        var subject = $('#macm_email_subject').val().trim();
        var body = '';

        // Get editor content
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('macm_email_body')) {
            body = tinyMCE.get('macm_email_body').getContent();
        } else {
            body = $('#macm_email_body').val();
        }

        // Validate recipients
        if (!sendToAllChecked && (!selectedUsers || selectedUsers.length === 0)) {
            alert('Please select at least one user or check "Send to All Users"');
            return false;
        }

        // Validate subject
        if (!subject) {
            alert('Please enter an email subject');
            $('#macm_email_subject').focus();
            return false;
        }

        // Validate body
        var bodyText = body.replace(/<[^>]*>/g, '').trim();
        if (!bodyText) {
            alert('Please enter an email message');
            return false;
        }

        // All validations passed
        return true;
    }

    // Send email via AJAX
    function sendEmailAjax() {
        var $submitBtn = $('#kcm-send-email-btn');
        var originalBtnText = $submitBtn.text();

        // Disable button and show loading state
        $submitBtn.prop('disabled', true).text('Sending...');

        // Get form data
        var formData = $form.serializeArray();

        // Get editor content (in case it's not in the serialized data)
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('macm_email_body')) {
            var editorContent = tinyMCE.get('macm_email_body').getContent();
            // Update the body field in formData
            formData = formData.filter(function(item) {
                return item.name !== 'macm_email_body';
            });
            formData.push({name: 'macm_email_body', value: editorContent});
        }

        // Add the submit button field (required by PHP handler)
        formData.push({name: 'macm_send_email', value: '1'});

        // Add action for AJAX
        formData.push({name: 'action', value: 'macm_send_bulk_email'});

        // Debug: Log the form data being sent

        // Send AJAX request
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: $.param(formData),
            success: function(response) {
                $submitBtn.prop('disabled', false).text(originalBtnText);

                if (response.success) {
                    // Show success message
                    showNotice('success', response.data.message);

                    // Clear form
                    $('#macm_email_subject').val('');
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('macm_email_body')) {
                        tinyMCE.get('macm_email_body').setContent('');
                    } else {
                        $('#macm_email_body').val('');
                    }
                    $sendToAll.prop('checked', false).trigger('change');
                    $userIds.val(null).trigger('change');
                } else {
                    // Show error message
                    console.error('Email send failed:', response);
                    showNotice('error', response.data ? response.data.message : 'An error occurred while sending emails.');
                }
            },
            error: function(xhr, status, error) {
                $submitBtn.prop('disabled', false).text(originalBtnText);
                console.error('AJAX error:', xhr.status, xhr.statusText, xhr.responseText);

                // Try to get more specific error from response
                var errorMsg = 'An error occurred while sending emails. Please try again.';
                if (xhr.responseText) {
                    try {
                        var errorData = JSON.parse(xhr.responseText);
                        if (errorData.data && errorData.data.message) {
                            errorMsg = errorData.data.message;
                        }
                    } catch(e) {
                        // Response is not JSON, show generic error
                    }
                }

                showNotice('error', errorMsg);
            }
        });
    }

    // Show admin notice
    function showNotice(type, message) {
        // Remove any existing notices
        $('.kcm-ajax-notice').remove();

        // Create notice HTML
        var noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
        var noticeHtml = '<div class="notice ' + noticeClass + ' is-dismissible kcm-ajax-notice" style="margin: 20px 0;">';
        noticeHtml += '<p>' + message + '</p>';
        noticeHtml += '<button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>';
        noticeHtml += '</div>';

        // Insert notice at the top of the form
        $('.kcm-email-form-wrapper').prepend(noticeHtml);

        // Scroll to notice
        $('html, body').animate({
            scrollTop: $('.kcm-ajax-notice').offset().top - 100
        }, 500);

        // Handle dismiss button
        $('.kcm-ajax-notice .notice-dismiss').on('click', function() {
            $(this).parent().fadeOut(300, function() {
                $(this).remove();
            });
        });
    }

    // Preview button handler
    $previewBtn.on('click', function(e) {
        e.preventDefault();
        handlePreviewClick();
    });

    // Handle preview click
    function handlePreviewClick() {
        var sendToAllChecked = $sendToAll.is(':checked');
        var selectedUsers = $userIds.val();
        var subject = $('#macm_email_subject').val().trim();
        var body = '';

        // Get editor content
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('macm_email_body')) {
            body = tinyMCE.get('macm_email_body').getContent();
        } else {
            body = $('#macm_email_body').val();
        }

        // Validate recipients
        if (!sendToAllChecked && (!selectedUsers || selectedUsers.length === 0)) {
            alert('Please select at least one user or check "Send to All Users"');
            return;
        }

        // Validate body
        var bodyText = body.replace(/<[^>]*>/g, '').trim();
        if (!bodyText) {
            alert('Please enter an email message');
            return;
        }

        // Show preview
        showPreview(subject, body);
    }

    // Show preview modal
    function showPreview(subject, body) {

        var siteName = 'Your Dojo';
        var gradientStart = '#B11226';
        var gradientEnd = '#8F0E1E';

        if (typeof macmEmail !== 'undefined' && macmEmail.settings) {
            if (macmEmail.settings.siteName) {
                siteName = macmEmail.settings.siteName;
            }
            if (macmEmail.settings.gradientStart) {
                gradientStart = macmEmail.settings.gradientStart;
            }
            if (macmEmail.settings.gradientEnd) {
                gradientEnd = macmEmail.settings.gradientEnd;
            }
        }

        var gradientStyle = 'background: linear-gradient(135deg, ' + gradientStart + ' 0%, ' + gradientEnd + ' 100%)';

        var html = '<div style="font-family: Arial, sans-serif; background: #F4F4F2; padding: 20px;">';
        html += '<div style="max-width: 600px; margin: 0 auto; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">';
        html += '<div style="' + gradientStyle + '; padding: 40px 30px; text-align: center;">';
        html += '<div style="font-size: 32px; font-weight: 700; color: #fff;">' + siteName + '</div>';
        html += '</div>';
        html += '<div style="padding: 40px 30px;">';
        html += '<p style="font-size: 16px; color: #111827;"><strong>Dear John (Sample),</strong></p>';
        html += '<div style="font-size: 16px; color: #111827; line-height: 1.6;">' + body + '</div>';
        html += '<p style="font-size: 15px; color: #111827; margin-top: 25px;">Best regards,<br><strong>' + siteName + '</strong></p>';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        $('#kcm-preview-content').html(html);
        $('#kcm-email-preview-modal').fadeIn(200);
    }

    // Close preview modal
    $('#kcm-close-preview').on('click', function() {
        $('#kcm-email-preview-modal').fadeOut(200);
    });

    // Close on background click
    $('#kcm-email-preview-modal').on('click', function(e) {
        if ($(e.target).is('#kcm-email-preview-modal')) {
            $(this).fadeOut(200);
        }
    });

    // Close on Escape key
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $('#kcm-email-preview-modal').is(':visible')) {
            $('#kcm-email-preview-modal').fadeOut(200);
        }
    });
});
