/**
 * Admin JavaScript for SPAI Contact Form
 */

(function($) {
    'use strict';

    // Tab switching
    $(document).on('click', '.spai-tab', function() {
        var target = $(this).data('tab');
        
        $('.spai-tab').removeClass('active');
        $(this).addClass('active');
        
        $('.spai-tab-content').removeClass('active');
        $('#' + target).addClass('active');
    });

    // Save form
    $(document).on('click', '#save-form', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        
        // Validate form name
        var formName = $('#form_name').val();
        if (!formName) {
            alert('Please enter a form name');
            return;
        }
        
        // Collect form data
        var formData = {
            form_name: formName,
            form_fields: [],
            form_settings: {},
            active: 1
        };
        
        // Get form fields from form builder
        if (window.SPAIFormBuilder && window.SPAIFormBuilder.getFormData) {
            var builderData = window.SPAIFormBuilder.getFormData();
            formData.form_fields = builderData.form_fields;
            formData.form_settings = builderData.form_settings;
            
            // Debug logging
            console.log('Form fields to save:', formData.form_fields);
            console.log('Fields count:', formData.form_fields.length);
        } else {
            // Fallback to existing fields
            formData.form_fields = window.spaiFormFields || [];
            formData.form_settings = {
                submit_text: $('#submit_text').val() || 'Submit',
                redirect_url: $('#redirect_url').val() || '',
                enable_honeypot: $('input[name="enable_honeypot"]').is(':checked')
            };
        }
        
        // Add form ID if editing
        if (window.spaiFormId) {
            formData.form_id = window.spaiFormId;
        }
        
        console.log('Saving form data:', formData);
        
        $button.prop('disabled', true).text('Saving...');
        
        $.post(spai_admin.ajax_url, {
            action: 'spai_save_form',
            nonce: spai_admin.nonce,
            form_id: formData.form_id,
            form_data: formData
        }, function(response) {
            console.log('Save response:', response);
            
            if (response.success) {
                $button.text('Saved!');
                
                // Update URL if new form
                if (!window.spaiFormId && response.data && response.data.form_id) {
                    window.spaiFormId = response.data.form_id;
                    var newUrl = window.location.href + '&form_id=' + response.data.form_id;
                    window.history.replaceState({}, '', newUrl);
                    
                    // Add shortcode display
                    if (!$('code').length) {
                        $button.after('<span style="margin-left: 20px;">Shortcode: <code>[spai_form id="' + response.data.form_id + '"]</code></span>');
                    }
                }
                
                setTimeout(function() {
                    $button.prop('disabled', false).text('Save Form');
                }, 2000);
            } else {
                alert(response.data || spai_admin.strings.error);
                $button.prop('disabled', false).text('Save Form');
            }
        }).fail(function(xhr) {
            console.error('Save failed:', xhr);
            alert('Failed to save form. Please check the console for errors.');
            $button.prop('disabled', false).text('Save Form');
        });
    });

    // Test integration
    $(document).on('click', '.test-integration', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var integration = $button.data('integration');
        var settings = collectIntegrationSettings(integration);
        
        $button.prop('disabled', true).text('Testing...');
        
        $.post(spai_admin.ajax_url, {
            action: 'spai_test_integration',
            nonce: spai_admin.nonce,
            integration: integration,
            settings: settings
        }, function(response) {
            if (response.success) {
                alert(response.data.message || 'Connection successful!');
            } else {
                alert(response.data || 'Connection failed!');
            }
            $button.prop('disabled', false).text('Test Connection');
        });
    });

    // Get Monday boards
    $(document).on('click', '#get-monday-boards', function(e) {
        e.preventDefault();
        
        var apiKey = $('#monday_api_key').val();
        if (!apiKey) {
            alert('Please enter your Monday.com API key first.');
            return;
        }
        
        var $button = $(this);
        $button.prop('disabled', true).text('Loading...');
        
        $.post(spai_admin.ajax_url, {
            action: 'spai_get_monday_boards',
            nonce: spai_admin.nonce,
            api_key: apiKey
        }, function(response) {
            if (response.success) {
                var $select = $('#monday_board_id');
                $select.empty().append('<option value="">Select a board</option>');
                
                $.each(response.data, function(i, board) {
                    $select.append('<option value="' + board.id + '">' + board.name + '</option>');
                });
                
                $button.text('Boards loaded!');
            } else {
                alert(response.data || 'Failed to load boards');
            }
            
            setTimeout(function() {
                $button.prop('disabled', false).text('Get Boards');
            }, 2000);
        });
    });

    // Helper function to collect integration settings
    function collectIntegrationSettings(integration) {
        var settings = {};
        $('#' + integration + '-settings').find('input, select, textarea').each(function() {
            var $field = $(this);
            settings[$field.attr('name')] = $field.val();
        });
        return settings;
    }
    
    // Export submissions
    $(document).on('click', '#export-submissions-json, #export-submissions-csv', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var format = $button.attr('id').includes('csv') ? 'csv' : 'json';
        
        $button.prop('disabled', true).text('Exporting...');
        
        $.post(spai_admin.ajax_url, {
            action: 'spai_export_submissions',
            nonce: spai_admin.nonce,
            format: format
        }, function(response) {
            if (response.success) {
                var data = response.data;
                var content;
                var mimeType;
                
                if (format === 'csv') {
                    // Convert array to CSV string
                    content = data.data.map(function(row) {
                        return row.map(function(cell) {
                            // Escape quotes and wrap in quotes if contains comma, newline, or quotes
                            cell = String(cell || '');
                            if (cell.includes(',') || cell.includes('\n') || cell.includes('"')) {
                                cell = '"' + cell.replace(/"/g, '""') + '"';
                            }
                            return cell;
                        }).join(',');
                    }).join('\n');
                    mimeType = 'text/csv';
                } else {
                    // JSON format
                    content = JSON.stringify(data.data, null, 2);
                    mimeType = 'application/json';
                }
                
                // Create download
                var blob = new Blob([content], { type: mimeType });
                var url = window.URL.createObjectURL(blob);
                var a = document.createElement('a');
                a.href = url;
                a.download = data.filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                $button.text('Exported!');
                setTimeout(function() {
                    $button.prop('disabled', false).html('<span class="dashicons dashicons-download" style="margin-top: 3px;"></span> Export as ' + format.toUpperCase());
                }, 2000);
            } else {
                alert(response.data || 'Export failed');
                $button.prop('disabled', false).html('<span class="dashicons dashicons-download" style="margin-top: 3px;"></span> Export as ' + format.toUpperCase());
            }
        }).fail(function() {
            alert('Export failed. Please try again.');
            $button.prop('disabled', false).html('<span class="dashicons dashicons-download" style="margin-top: 3px;"></span> Export as ' + format.toUpperCase());
        });
    });

    // ==========================================
    // Email Confirmation Settings
    // ==========================================

    /**
     * Initialize email confirmation settings when tab is shown
     */
    function initEmailConfirmationSettings() {
        var $attachmentField = $('#attachment_field');
        var $mappingContainer = $('#attachment-mapping-container');
        var $mappingTable = $('#attachment-mapping-table tbody');

        // Skip if elements don't exist (not on form editor page)
        if (!$attachmentField.length) {
            return;
        }

        // Get form fields that are select/radio type
        var selectFields = [];
        if (window.spaiFormFields && Array.isArray(window.spaiFormFields)) {
            window.spaiFormFields.forEach(function(field) {
                if (field.type === 'select' || field.type === 'radio' || field.type === 'multichoice') {
                    selectFields.push(field);
                }
            });
        }

        // Populate the attachment field dropdown
        $attachmentField.empty().append('<option value="">-- No attachment --</option>');
        selectFields.forEach(function(field) {
            var selected = (window.spaiEmailSettings && window.spaiEmailSettings.attachment_field === field.name) ? ' selected' : '';
            $attachmentField.append('<option value="' + field.name + '"' + selected + '>' + field.label + ' (' + field.name + ')</option>');
        });

        // Handle field selection change
        $attachmentField.off('change').on('change', function() {
            var selectedFieldName = $(this).val();

            if (!selectedFieldName) {
                $mappingContainer.hide();
                return;
            }

            // Find the selected field
            var selectedField = null;
            selectFields.forEach(function(field) {
                if (field.name === selectedFieldName) {
                    selectedField = field;
                }
            });

            if (!selectedField || !selectedField.options || !selectedField.options.length) {
                $mappingContainer.hide();
                return;
            }

            // Build mapping rows
            $mappingTable.empty();
            var existingMapping = (window.spaiEmailSettings && window.spaiEmailSettings.attachment_mapping) || {};

            selectedField.options.forEach(function(option) {
                var optionValue = typeof option === 'object' ? option.value || option.label : option;
                var existingUrl = existingMapping[optionValue] || '';

                var row = '<tr>' +
                    '<td><strong>' + escapeHtml(optionValue) + '</strong></td>' +
                    '<td><input type="url" class="large-text attachment-url" ' +
                    'data-option="' + escapeHtml(optionValue) + '" ' +
                    'value="' + escapeHtml(existingUrl) + '" ' +
                    'placeholder="https://example.com/file.pdf"></td>' +
                    '</tr>';
                $mappingTable.append(row);
            });

            $mappingContainer.show();
        });

        // Trigger change to load initial state
        $attachmentField.trigger('change');
    }

    /**
     * Collect email confirmation settings
     */
    function collectEmailSettings() {
        var settings = {
            enabled: $('#email_enabled').is(':checked'),
            subject: $('#email_subject').val(),
            from_name: $('#email_from_name').val(),
            from_email: $('#email_from_email').val(),
            reply_to: $('#email_reply_to').val(),
            logo_url: $('#email_logo_url').val(),
            phone_number: $('#email_phone_number').val(),
            body_text: $('#email_body_text').val(),
            footer_text: $('#email_footer_text').val(),
            attachment_field: $('#attachment_field').val(),
            attachment_mapping: {}
        };

        // Collect attachment mapping
        $('#attachment-mapping-table .attachment-url').each(function() {
            var $input = $(this);
            var optionValue = $input.data('option');
            var url = $input.val().trim();
            if (url) {
                settings.attachment_mapping[optionValue] = url;
            }
        });

        return settings;
    }

    /**
     * HTML escape helper
     */
    function escapeHtml(text) {
        if (!text) return '';
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(text));
        return div.innerHTML;
    }

    // Initialize email settings when tab is clicked
    $(document).on('click', '.spai-tab[data-tab="email-confirmation"]', function() {
        setTimeout(initEmailConfirmationSettings, 100);
    });

    // Also initialize on page load if we're on form editor
    $(document).ready(function() {
        // Delay to ensure form builder has loaded
        setTimeout(function() {
            initEmailConfirmationSettings();
        }, 500);
    });

    // Populate test attachment dropdown when attachment mapping changes
    function updateTestAttachmentDropdown() {
        var $dropdown = $('#test_attachment_option');
        if (!$dropdown.length) return;

        $dropdown.empty().append('<option value="">-- No attachment --</option>');

        // Get options from attachment mapping table
        $('#attachment-mapping-table .attachment-url').each(function() {
            var optionValue = $(this).data('option');
            var pdfUrl = $(this).val();
            if (optionValue && pdfUrl) {
                $dropdown.append('<option value="' + escapeHtml(optionValue) + '">' + escapeHtml(optionValue) + '</option>');
            }
        });
    }

    // Update dropdown when mapping URLs change
    $(document).on('change', '.attachment-url', updateTestAttachmentDropdown);
    $(document).on('change', '#attachment_field', function() {
        setTimeout(updateTestAttachmentDropdown, 200);
    });

    // Test email button - sends REAL email with configured template
    $(document).on('click', '#test-email-btn', function(e) {
        e.preventDefault();

        var $button = $(this);
        var $result = $('#test-email-result');

        // Validate email
        var testEmail = $('#test_email_address').val().trim();
        if (!testEmail) {
            $result.html('<span style="color: red;">Please enter an email address</span>');
            return;
        }

        // Collect all settings
        var emailSettings = collectEmailSettings();

        // Add test-specific data
        var testData = {
            to_email: testEmail,
            first_name: $('#test_first_name').val() || 'Test',
            test_attachment_option: $('#test_attachment_option').val()
        };

        $button.prop('disabled', true).text('Sending...');
        $result.text('');

        $.post(spai_admin.ajax_url, {
            action: 'spai_send_real_test_email',
            nonce: spai_admin.nonce,
            settings: emailSettings,
            test_data: testData
        }, function(response) {
            if (response.success) {
                var msg = response.data.message || 'Test email sent!';
                if (response.data.has_attachment) {
                    msg += ' (with PDF attached)';
                }
                $result.html('<span style="color: green;">✓ ' + msg + '</span>');
            } else {
                $result.html('<span style="color: red;">✗ ' + (response.data || 'Failed to send test email') + '</span>');
            }
            $button.prop('disabled', false).html('<span class="dashicons dashicons-email" style="vertical-align: middle;"></span> Send Test Email Now');
        }).fail(function() {
            $result.html('<span style="color: red;">Request failed. Please try again.</span>');
            $button.prop('disabled', false).html('<span class="dashicons dashicons-email" style="vertical-align: middle;"></span> Send Test Email Now');
        });
    });

    // Expose collectEmailSettings globally so form-builder can use it
    window.SPAIAdmin = window.SPAIAdmin || {};
    window.SPAIAdmin.collectEmailSettings = collectEmailSettings;

    // ============================================
    // NEWSLETTER SETTINGS
    // ============================================

    /**
     * Initialize newsletter settings
     */
    function initNewsletterSettings() {
        var $fieldSelect = $('#newsletter_field');
        var $mappingContainer = $('#newsletter-mapping-container');
        var $mappingTable = $('#newsletter-mapping-table tbody');

        if (!$fieldSelect.length) return;

        // Get form fields (same as email confirmation)
        var selectableFields = [];
        if (window.spaiFormFields && Array.isArray(window.spaiFormFields)) {
            window.spaiFormFields.forEach(function(field) {
                if (field.type === 'select' || field.type === 'radio' || field.type === 'multichoice') {
                    selectableFields.push(field);
                }
            });
        }

        // Populate field dropdown
        var currentValue = $fieldSelect.data('saved-value') || $fieldSelect.val();
        $fieldSelect.empty().append('<option value="">-- Select field --</option>');

        selectableFields.forEach(function(field) {
            var selected = field.name === currentValue ? 'selected' : '';
            $fieldSelect.append('<option value="' + escapeHtml(field.name) + '" ' + selected + '>' + escapeHtml(field.label || field.name) + '</option>');
        });

        // Restore saved value
        if (currentValue) {
            $fieldSelect.val(currentValue);
            updateNewsletterMapping();
        }
    }

    /**
     * Update newsletter mapping table when field selection changes
     */
    function updateNewsletterMapping() {
        var $fieldSelect = $('#newsletter_field');
        var $mappingContainer = $('#newsletter-mapping-container');
        var $mappingTable = $('#newsletter-mapping-table tbody');

        var selectedField = $fieldSelect.val();

        if (!selectedField) {
            $mappingContainer.hide();
            return;
        }

        // Get form fields (same as email confirmation)
        var formFields = [];
        if (window.spaiFormFields && Array.isArray(window.spaiFormFields)) {
            formFields = window.spaiFormFields;
        }

        // Find the selected field
        var field = null;
        for (var i = 0; i < formFields.length; i++) {
            if (formFields[i].name === selectedField) {
                field = formFields[i];
                break;
            }
        }

        if (!field || !field.options || !field.options.length) {
            $mappingContainer.hide();
            return;
        }

        // Get MyEmma group IDs
        var residentialGroup = $('#myemma_residential_group').val() || '';
        var commercialGroup = $('#myemma_commercial_group').val() || '';

        // Build mapping rows
        $mappingTable.empty();

        field.options.forEach(function(option) {
            var optionValue = typeof option === 'object' ? (option.value || option.label) : option;
            var optionLabel = typeof option === 'object' ? (option.label || option.value) : option;

            var row = '<tr>' +
                '<td><strong>' + escapeHtml(optionLabel) + '</strong></td>' +
                '<td>' +
                '<select class="newsletter-group-select regular-text" data-option="' + escapeHtml(optionValue) + '">' +
                '<option value="">-- Skip --</option>' +
                '<option value="residential" data-group-id="' + escapeHtml(residentialGroup) + '">Residential (' + escapeHtml(residentialGroup) + ')</option>' +
                '<option value="commercial" data-group-id="' + escapeHtml(commercialGroup) + '">Commercial (' + escapeHtml(commercialGroup) + ')</option>' +
                '</select>' +
                '</td>' +
                '</tr>';

            $mappingTable.append(row);
        });

        $mappingContainer.show();

        // Restore saved mappings
        restoreNewsletterMappings();
    }

    /**
     * Restore saved newsletter mappings
     */
    function restoreNewsletterMappings() {
        // Get saved mapping from hidden field
        var savedMapping = {};
        try {
            var mappingData = $('#newsletter_mapping_data').val();
            if (mappingData) {
                savedMapping = JSON.parse(mappingData);
            }
        } catch (e) {
            console.log('Newsletter mapping parse error:', e);
        }

        // Apply saved values - mapping has structure {type: 'residential', group_id: '123'}
        $('.newsletter-group-select').each(function() {
            var optionValue = $(this).data('option');
            if (savedMapping[optionValue]) {
                var config = savedMapping[optionValue];
                // Get the type (residential or commercial)
                var groupType = typeof config === 'object' ? config.type : config;
                if (groupType) {
                    $(this).val(groupType);
                }
            }
        });
    }

    /**
     * Collect newsletter settings
     */
    function collectNewsletterSettings() {
        var settings = {
            enabled: $('#newsletter_enabled').is(':checked'),
            field: $('#newsletter_field').val(),
            mapping: {}
        };

        // Collect group mapping with group IDs
        $('.newsletter-group-select').each(function() {
            var optionValue = $(this).data('option');
            var groupType = $(this).val();
            if (groupType) {
                var groupId = $(this).find('option:selected').data('group-id');
                settings.mapping[optionValue] = {
                    type: groupType,
                    group_id: groupId
                };
            }
        });

        return settings;
    }

    // Initialize newsletter settings when tab is clicked
    $(document).on('click', '.spai-tab[data-tab="newsletter"]', function() {
        setTimeout(initNewsletterSettings, 100);
    });

    // Update mapping when field selection changes
    $(document).on('change', '#newsletter_field', updateNewsletterMapping);

    // Initialize on page load
    $(document).ready(function() {
        setTimeout(initNewsletterSettings, 600);
    });

    // Expose collectNewsletterSettings globally
    window.SPAIAdmin.collectNewsletterSettings = collectNewsletterSettings;

})(jQuery);
