/**
 * Pexally Email Campaign - Master Admin Script
 * Handles UI interactions, SMTP auto-fill, and the High-Performance CSV Chunking Engine.
 */
jQuery(document).ready(function($) {

    // ---------------------------------------------------------
    // 1. SETTINGS PAGE: SMTP PROVIDER AUTO-FILL
    // ---------------------------------------------------------
    if ($('input[name="smtp_provider"]').length) {
        const providerConfig = {
            'google': { host: 'smtp.gmail.com', port: 587, userLabel: 'Google Workspace Email', passLabel: 'Google App Password', userAuto: '', passHint: 'Google Workspace users: Do NOT use your regular login password. You must generate a 16-character "App Password" in Google Security settings.' },
            'sendgrid': { host: 'smtp.sendgrid.net', port: 587, userLabel: 'API Key Username', passLabel: 'SendGrid API Key', userAuto: 'apikey', passHint: 'Your SendGrid API Key starts with "SG."' },
            'ses': { host: 'email-smtp.us-east-1.amazonaws.com', port: 587, userLabel: 'SMTP Username', passLabel: 'SMTP Password', userAuto: '', passHint: 'Generate your SMTP credentials inside the Amazon SES Console.' },
            'mailgun': { host: 'smtp.mailgun.org', port: 587, userLabel: 'Postmaster Email', passLabel: 'SMTP Password', userAuto: 'postmaster@yourdomain.com', passHint: 'Your postmaster login from the Mailgun Domain settings.' },
            'other': { host: '', port: 587, userLabel: 'SMTP Username', passLabel: 'SMTP Password', userAuto: '', passHint: 'Enter the password provided by your email host.' }
        };

        $('input[name="smtp_provider"]').on('change', function() {
            let val = $(this).val();
            
            if (val === 'wp_mail') {
                $('#pex-smtp-settings-wrapper').slideUp();
                $('#smtp_enabled_val').val('no');
            } else {
                $('#pex-smtp-settings-wrapper').slideDown();
                $('#smtp_enabled_val').val('yes');
                $('#smtp-section-title').text($('input[name="smtp_provider"]:checked').siblings('.pex-mailer-box').find('strong').text() + ' Settings');

                if(providerConfig[val]) {
                    let currentHost = $('#smtp_host').val();
                    let knownHosts = Object.values(providerConfig).map(c => c.host).filter(h => h !== '');
                    
                    if (currentHost === '' || knownHosts.includes(currentHost)) {
                        $('#smtp_host').val(providerConfig[val].host);
                        $('#smtp_port').val(providerConfig[val].port);
                    }
                    
                    $('#lbl_smtp_username').text(providerConfig[val].userLabel);
                    $('#lbl_smtp_password').text(providerConfig[val].passLabel);
                    $('#hint_smtp_password').text(providerConfig[val].passHint);
                    
                    let currentUser = $('#smtp_username').val();
                    let knownUsers = ['apikey', 'postmaster@yourdomain.com'];
                    if (currentUser === '' || knownUsers.includes(currentUser)) {
                        $('#smtp_username').val(providerConfig[val].userAuto);
                    }
                }
            }
        });

        if ($('input[name="smtp_provider"]:checked').val() !== 'wp_mail') {
            let val = $('input[name="smtp_provider"]:checked').val();
            if(providerConfig[val]) {
                $('#lbl_smtp_username').text(providerConfig[val].userLabel);
                $('#lbl_smtp_password').text(providerConfig[val].passLabel);
                $('#hint_smtp_password').text(providerConfig[val].passHint);
            }
        }
    }

    // ---------------------------------------------------------
    // 2. CONTACTS & LISTS MANAGER
    // ---------------------------------------------------------
    
    // Ensure we are on a Pexally Admin page by checking if global variables are loaded
    if (typeof pexEmailGlobal !== 'undefined') {
        
        // UI: Tab Switching for Import types
        $('.pex-tab').on('click', function() {
            $('.pex-tab').removeClass('active');
            $('.pex-tab-content').removeClass('active');
            $(this).addClass('active');
            $('#' + $(this).data('target')).addClass('active');
        });

        // AJAX: Create List
        $('#btn_create_list').on('click', function(e) {
            e.preventDefault();
            let listName = $('#new_list_name').val().trim();
            if (!listName) return alert('Please enter a list name.');
            
            let btn = $(this);
            let originalText = btn.text();
            btn.text('Creating...').prop('disabled', true);

            $.post(pexEmailGlobal.ajax_url, {
                action: 'pexemail_create_list',
                list_name: listName,
                _ajax_nonce: pexEmailGlobal.nonce_contacts
            }, function(res) {
                if(res.success) {
                    location.reload();
                } else { 
                    alert('Error creating list.'); 
                    btn.text(originalText).prop('disabled', false); 
                }
            }).fail(function() {
                alert('Network error. Please try again.');
                btn.text(originalText).prop('disabled', false); 
            });
        });

        // AJAX: Delete List
        $('.pex-delete-list').on('click', function(e) {
            e.preventDefault();
            if(!confirm('Are you sure? This will delete the list and all contacts inside it!')) return;
            
            let btn = $(this);
            let originalText = btn.text();
            let listId = btn.data('id');
            btn.text('...').prop('disabled', true);

            $.post(pexEmailGlobal.ajax_url, {
                action: 'pexemail_delete_list',
                list_id: listId,
                _ajax_nonce: pexEmailGlobal.nonce_contacts
            }, function(res) {
                if(res.success) {
                    location.reload();
                } else {
                    alert('Error deleting list.');
                    btn.text(originalText).prop('disabled', false);
                }
            });
        });

        // AJAX: Rename List
        $('.pex-edit-list').on('click', function(e) {
            e.preventDefault();
            let listId = $(this).data('id');
            let currentName = $('#list-name-' + listId).text();
            let newName = prompt("Enter new name for this list:", currentName);
            
            if(newName && newName.trim() !== currentName) {
                $.post(pexEmailGlobal.ajax_url, {
                    action: 'pexemail_edit_list',
                    list_id: listId,
                    list_name: newName.trim(),
                    _ajax_nonce: pexEmailGlobal.nonce_contacts
                }, function(res) {
                    if(res.success) {
                        $('#list-name-' + listId).text(newName.trim());
                    } else {
                        alert('Error renaming list.');
                    }
                });
            }
        });

        // Modals for Contacts
        $('.pex-edit-contact').on('click', function(e) {
            e.preventDefault();
            $('#edit_c_id').val($(this).data('id'));
            $('#edit_c_email').val($(this).data('email'));
            $('#edit_c_fname').val($(this).data('fname'));
            $('#edit_c_lname').val($(this).data('lname'));
            $('#pex-edit-contact-modal').css('display', 'flex');
        });

        // AJAX: Save Edited Contact
        $('#btn_save_contact').on('click', function(e) {
            e.preventDefault();
            let btn = $(this);
            let originalText = btn.text();
            btn.text('Saving...').prop('disabled', true);

            $.post(pexEmailGlobal.ajax_url, {
                action: 'pexemail_edit_contact',
                contact_id: $('#edit_c_id').val(),
                email: $('#edit_c_email').val(),
                first_name: $('#edit_c_fname').val(),
                last_name: $('#edit_c_lname').val(),
                _ajax_nonce: pexEmailGlobal.nonce_contacts
            }, function(res) {
                if(res.success) {
                    location.reload();
                } else { 
                    alert(res.data || 'Error saving contact.'); 
                    btn.text(originalText).prop('disabled', false); 
                }
            });
        });

        // AJAX: Delete Contact
        $('.pex-delete-contact').on('click', function(e) {
            e.preventDefault();
            if(!confirm('Delete this contact?')) return;
            
            let btn = $(this);
            btn.text('...').prop('disabled', true);
            
            $.post(pexEmailGlobal.ajax_url, {
                action: 'pexemail_delete_contact',
                contact_id: btn.data('id'),
                _ajax_nonce: pexEmailGlobal.nonce_contacts
            }, function(res) {
                if(res.success) location.reload();
                else alert('Error deleting contact.');
            });
        });

        // =========================================================
        // THE BROWSER-SIDE JAVASCRIPT CHUNKING ENGINE
        // =========================================================
        let rawContactsToProcess = [];
        let currentChunkIndex = 0;
        const CHUNK_SIZE = 500; 

        $('#btn_import_contacts').on('click', function(e) {
            e.preventDefault();
            let listId = $('#target_list_id').val();
            let activeTab = $('.pex-tab.active').data('target');

            rawContactsToProcess = [];
            currentChunkIndex = 0;

            if (activeTab === 'tab-single') {
                let sEmail = $('#single_email').val().trim();
                if(!sEmail) return alert('Email address is required.');
                
                let btn = $(this);
                let originalText = btn.text();
                btn.text('Adding...').prop('disabled', true);
                
                $.post(pexEmailGlobal.ajax_url, {
                    action: 'pexemail_add_single_contact',
                    list_id: listId,
                    email: sEmail,
                    first_name: $('#single_fname').val().trim(),
                    last_name: $('#single_lname').val().trim(),
                    _ajax_nonce: pexEmailGlobal.nonce_contacts
                }, function(res) {
                    if(res.success) {
                        location.reload();
                    } else {
                        alert('Failed: ' + res.data);
                        btn.html('<svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"></path></svg> Import Contacts').prop('disabled', false);
                    }
                });
                return; 
            }

            if (activeTab === 'tab-paste') {
                let emails = $('#paste_emails').val().split('\n');
                emails.forEach(function(email) {
                    email = email.trim();
                    if (email) rawContactsToProcess.push({ email: email, first_name: '', last_name: '' });
                });
                if(rawContactsToProcess.length === 0) return alert('Please paste some emails.');
                startChunkImport(listId);
                
            } else if (activeTab === 'tab-csv') {
                let fileInput = document.getElementById('csv_file');
                if (fileInput.files.length === 0) return alert('Please select a CSV file.');

                let file = fileInput.files[0];
                let reader = new FileReader();

                reader.onload = function(e) {
                    let text = e.target.result;
                    let lines = text.split('\n');
                    
                    lines.forEach(function(line, index) {
                        if(index === 0 || !line.trim()) return; 
                        
                        // Handle standard CSV parsing safely
                        let cols = line.split(',');
                        if(cols.length > 0) {
                            let email = cols[0] ? cols[0].trim().replace(/"/g, '') : '';
                            let fName = cols[1] ? cols[1].trim().replace(/"/g, '') : '';
                            let lName = cols[2] ? cols[2].trim().replace(/"/g, '') : '';
                            
                            if(email && email.includes('@')) {
                                rawContactsToProcess.push({ email: email, first_name: fName, last_name: lName });
                            }
                        }
                    });

                    if(rawContactsToProcess.length === 0) return alert('No valid emails found in the CSV.');
                    startChunkImport(listId);
                };
                reader.readAsText(file);
            }
        });

        function startChunkImport(listId) {
            $('#btn_import_contacts').hide();
            $('#import_progress_wrap').show();
            $('#import_progress_bar').css('width', '0%');
            processNextChunk(listId);
        }

        function processNextChunk(listId) {
            let chunk = rawContactsToProcess.slice(currentChunkIndex, currentChunkIndex + CHUNK_SIZE);
            
            if (chunk.length === 0) {
                $('#import_progress_bar').css('width', '100%');
                $('#import_progress_text').text('Processing Complete! Refreshing...');
                setTimeout(function() { location.reload(); }, 1500);
                return;
            }

            let progress = Math.round((currentChunkIndex / rawContactsToProcess.length) * 100);
            $('#import_progress_bar').css('width', progress + '%');
            $('#import_progress_text').text('Saving to database... (' + currentChunkIndex + ' of ' + rawContactsToProcess.length + ')');

            $.ajax({
                url: pexEmailGlobal.ajax_url,
                type: 'POST',
                data: {
                    action: 'pexemail_import_contacts',
                    list_id: listId,
                    contacts: JSON.stringify(chunk),
                    _ajax_nonce: pexEmailGlobal.nonce_contacts
                },
                success: function(res) {
                    if(res.success) {
                        currentChunkIndex += CHUNK_SIZE;
                        processNextChunk(listId);
                    } else {
                        alert('Save failed. Server might be timing out.');
                        $('#btn_import_contacts').show();
                        $('#import_progress_wrap').hide();
                    }
                },
                error: function() {
                    alert('Server blocked the request. Try a smaller file.');
                    $('#btn_import_contacts').show();
                    $('#import_progress_wrap').hide();
                }
            });
        }
    }
});