/**
 * Customer Modal Layout Restructurer
 * Converts vertical stacked fields to multi-column layout to avoid scrolling
 */

(function() {
    'use strict';
    
    // Inject CSS if not already loaded
    function injectCSS() {
        if (document.getElementById('customer-modal-layout-css')) {
            return; // Already injected
        }
        
        const link = document.createElement('link');
        link.id = 'customer-modal-layout-css';
        link.rel = 'stylesheet';
        link.href = 'assets/css/customer_modal_layout.css';
        document.head.appendChild(link);
    }
    
    // Restructure modal body into rows and columns
    function restructureModalBody(modalBody, isEditModal) {
        // Check if already restructured
        if (modalBody.classList.contains('customer-modal-restructured')) {
            return;
        }
        
        // For edit modal, verify fields exist by checking for specific IDs
        if (isEditModal) {
            const nameField = document.getElementById('edit_name');
            if (!nameField) {
                console.log('Customer Modal Layout: Edit fields not loaded yet, waiting...');
                return;
            }
        }
        
        console.log('Customer Modal Layout: Restructuring modal', isEditModal ? 'edit' : 'add');
        
        // Store hidden inputs first
        const hiddenInputs = [];
        Array.from(modalBody.querySelectorAll('input[type="hidden"]')).forEach(function(input) {
            hiddenInputs.push(input);
        });
        
        // Direct approach: Find fields by ID and get their parent containers
        function getFieldContainer(fieldId) {
            const field = document.getElementById(fieldId);
            if (!field) return null;
            // Get the parent div with mb-2 class
            let container = field.parentElement;
            while (container && container !== modalBody) {
                if (container.classList && container.classList.contains('mb-2')) {
                    return container;
                }
                container = container.parentElement;
            }
            // If no mb-2 container, create one
            const wrapper = document.createElement('div');
            wrapper.className = 'mb-2';
            const label = field.previousElementSibling && field.previousElementSibling.tagName === 'LABEL' 
                ? field.previousElementSibling 
                : null;
            if (label) {
                wrapper.appendChild(label);
            } else {
                const newLabel = document.createElement('label');
                newLabel.textContent = fieldId.replace('edit_', '').replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                wrapper.appendChild(newLabel);
            }
            wrapper.appendChild(field);
            return wrapper;
        }
        
        function getCheckboxContainer(checkboxId) {
            const checkbox = document.getElementById(checkboxId);
            if (!checkbox) return null;
            // Find the form-check parent
            let container = checkbox.closest('.form-check');
            if (container) return container;
            // If not found, create one
            container = document.createElement('div');
            container.className = 'form-check mb-2';
            const label = checkbox.nextElementSibling && checkbox.nextElementSibling.tagName === 'LABEL'
                ? checkbox.nextElementSibling
                : null;
            container.appendChild(checkbox);
            if (label) container.appendChild(label);
            return container;
        }
        
        const newStructure = document.createElement('div');
        newStructure.className = 'customer-modal-restructured-container';
        
        // Track processed containers to avoid duplicates
        const processedContainers = new Set();
        
        // Group 1: Name and Phone (2 columns)
        const row1 = createRow();
        const nameContainer = getFieldContainer(isEditModal ? 'edit_name' : 'name');
        const phoneContainer = getFieldContainer(isEditModal ? 'edit_phone' : 'phone');
        if (nameContainer) {
            processedContainers.add(nameContainer);
            row1.appendChild(createFieldWrapper(nameContainer, 'customer-modal-field'));
        }
        if (phoneContainer) {
            processedContainers.add(phoneContainer);
            row1.appendChild(createFieldWrapper(phoneContainer, 'customer-modal-field'));
        }
        if (row1.children.length > 0) newStructure.appendChild(row1);
        
        // Group 2: Email and Province (2 columns)
        const row2 = createRow();
        const emailContainer = getFieldContainer(isEditModal ? 'edit_email' : 'email');
        const provinceContainer = getFieldContainer(isEditModal ? 'edit_province' : 'province');
        if (emailContainer) {
            processedContainers.add(emailContainer);
            row2.appendChild(createFieldWrapper(emailContainer, 'customer-modal-field'));
        }
        if (provinceContainer) {
            processedContainers.add(provinceContainer);
            row2.appendChild(createFieldWrapper(provinceContainer, 'customer-modal-field'));
        }
        if (row2.children.length > 0) newStructure.appendChild(row2);
        
        // Group 3: Category and NTN (2 columns)
        const row3 = createRow();
        const categoryContainer = getFieldContainer(isEditModal ? 'edit_category_id' : 'category_id');
        const ntnContainer = getFieldContainer(isEditModal ? 'edit_ntn' : 'ntn');
        if (categoryContainer) {
            processedContainers.add(categoryContainer);
            row3.appendChild(createFieldWrapper(categoryContainer, 'customer-modal-field'));
        }
        if (ntnContainer) {
            processedContainers.add(ntnContainer);
            row3.appendChild(createFieldWrapper(ntnContainer, 'customer-modal-field'));
        }
        if (row3.children.length > 0) newStructure.appendChild(row3);
        
        // Group 4: Address (full width)
        const row4 = createRow();
        const addressContainer = getFieldContainer(isEditModal ? 'edit_address' : 'address');
        if (addressContainer) {
            processedContainers.add(addressContainer);
            row4.appendChild(createFieldWrapper(addressContainer, 'customer-modal-field-full'));
            newStructure.appendChild(row4);
        }
        
        // Group 5: Checkboxes (3 columns)
        const row5 = createRow();
        const walkInContainer = getCheckboxContainer(isEditModal ? 'edit_is_walk_in' : 'is_walk_in');
        const activeContainer = getCheckboxContainer(isEditModal ? 'edit_active' : 'active');
        const discountAppliedContainer = getCheckboxContainer(isEditModal ? 'edit_discount_applied' : 'discount_applied');
        if (walkInContainer) {
            processedContainers.add(walkInContainer);
            row5.appendChild(createFieldWrapper(walkInContainer, 'customer-modal-field-3'));
        }
        if (activeContainer) {
            processedContainers.add(activeContainer);
            row5.appendChild(createFieldWrapper(activeContainer, 'customer-modal-field-3'));
        }
        if (discountAppliedContainer) {
            processedContainers.add(discountAppliedContainer);
            row5.appendChild(createFieldWrapper(discountAppliedContainer, 'customer-modal-field-3'));
        }
        if (row5.children.length > 0) newStructure.appendChild(row5);
        
        // Group 6: Discount Rate and Withholding Rate (2 columns)
        const row6 = createRow();
        const discountRateContainer = getFieldContainer(isEditModal ? 'edit_discount_rate' : 'discount_rate');
        const withholdingRateContainer = getFieldContainer(isEditModal ? 'edit_withholding_rate' : 'withholding_rate');
        if (discountRateContainer) {
            processedContainers.add(discountRateContainer);
            row6.appendChild(createFieldWrapper(discountRateContainer, 'customer-modal-field'));
        }
        if (withholdingRateContainer) {
            processedContainers.add(withholdingRateContainer);
            row6.appendChild(createFieldWrapper(withholdingRateContainer, 'customer-modal-field'));
        }
        if (row6.children.length > 0) newStructure.appendChild(row6);
        
        // Preserve hidden inputs (like customer ID)
        hiddenInputs.forEach(function(input) {
            newStructure.appendChild(input);
        });
        
        // Mark as restructured before replacing content
        modalBody.classList.add('customer-modal-restructured');
        
        // Only replace if we have content in new structure
        if (newStructure.children.length > 0) {
            // Replace modal body content
            modalBody.innerHTML = '';
            modalBody.appendChild(newStructure);
            console.log('Customer Modal Layout: Restructuring complete with', newStructure.children.length, 'rows');
        } else {
            console.warn('Customer Modal Layout: No fields found to restructure, keeping original layout');
            modalBody.classList.remove('customer-modal-restructured');
        }
    }
    
    // Helper: Create a row container
    function createRow() {
        const row = document.createElement('div');
        row.className = 'customer-modal-row';
        return row;
    }
    
    // Helper: Create field wrapper
    function createFieldWrapper(fieldElement, wrapperClass) {
        const wrapper = document.createElement('div');
        wrapper.className = wrapperClass;
        
        // If it's already a div with mb-2, move its content (not clone to preserve event handlers)
        if (fieldElement.tagName === 'DIV' && fieldElement.classList.contains('mb-2')) {
            // Move label and input/select/textarea
            const label = fieldElement.querySelector('label');
            const input = fieldElement.querySelector('input, select, textarea');
            
            if (label) wrapper.appendChild(label);
            if (input) wrapper.appendChild(input);
        } else if (fieldElement.classList && fieldElement.classList.contains('form-check')) {
            // For checkboxes, move the entire structure
            wrapper.appendChild(fieldElement);
        } else {
            // For other elements, move as is
            wrapper.appendChild(fieldElement);
        }
        
        return wrapper;
    }
    
    // Helper: Find field by name/id pattern
    function findField(fields, namePattern, selector) {
        for (let i = 0; i < fields.length; i++) {
            const field = fields[i];
            
            // Skip if already processed
            if (field.classList && (field.classList.contains('customer-modal-field') || 
                field.classList.contains('customer-modal-restructured-container'))) {
                continue;
            }
            
            // For checkboxes, check the field itself
            if (selector === '.form-check') {
                // Check if this is a form-check div
                if (field.classList && field.classList.contains('form-check')) {
                    const checkbox = field.querySelector('input[type="checkbox"]');
                    if (checkbox) {
                        const name = checkbox.name || checkbox.id || '';
                        if (name && name.includes(namePattern)) {
                            return field;
                        }
                    }
                }
                continue;
            }
            
            // Try to find the element with the selector
            let element = null;
            if (field.querySelector) {
                element = field.querySelector(selector);
            }
            
            if (element) {
                const name = element.name || element.id || '';
                if (name && name.includes(namePattern)) {
                    return field;
                }
            }
            
            // Also check if the field itself matches (for direct inputs)
            if (field.tagName && (field.tagName === 'INPUT' || field.tagName === 'SELECT' || field.tagName === 'TEXTAREA')) {
                const name = field.name || field.id || '';
                if (name && name.includes(namePattern)) {
                    // Wrap it in a div
                    const wrapper = document.createElement('div');
                    wrapper.className = 'mb-2';
                    const label = document.createElement('label');
                    label.textContent = namePattern.replace('edit_', '').replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
                    wrapper.appendChild(label);
                    wrapper.appendChild(field);
                    return wrapper;
                }
            }
        }
        return null;
    }
    
    // Process modal when it's shown
    function processModal(modalId, isEditModal) {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        
        const modalBody = modal.querySelector('.modal-body');
        if (!modalBody) return;
        
        // For edit modal, wait a bit longer to ensure AJAX data is loaded
        if (isEditModal) {
            // Check if fields are already populated
            const hasFields = modalBody.querySelector('input[id*="edit_"], select[id*="edit_"], textarea[id*="edit_"]');
            if (!hasFields) {
                // Fields not loaded yet, wait and retry
                setTimeout(function() {
                    processModal(modalId, isEditModal);
                }, 200);
                return;
            }
        }
        
        // Only restructure if we have fields
        const fieldCount = modalBody.querySelectorAll('input, select, textarea').length;
        if (fieldCount > 0) {
            restructureModalBody(modalBody, isEditModal);
        }
    }
    
    // Initialize when DOM is ready
    function init() {
        injectCSS();
        
        // Process modals if they're already in DOM
        processModal('addCustomerModal', false);
        processModal('editCustomerModal', true);
        
        // Listen for modal show events (Bootstrap 5)
        document.addEventListener('shown.bs.modal', function(e) {
            if (e.target.id === 'addCustomerModal') {
                setTimeout(function() {
                    processModal('addCustomerModal', false);
                }, 100);
            } else if (e.target.id === 'editCustomerModal') {
                // For edit modal, wait longer and retry multiple times for AJAX to populate fields
                let retryCount = 0;
                const maxRetries = 10;
                const retryInterval = 200;
                
                function tryRestructure() {
                    const modalBody = e.target.querySelector('.modal-body');
                    const hasFields = modalBody && modalBody.querySelector('input[id*="edit_"], select[id*="edit_"], textarea[id*="edit_"]');
                    
                    if (hasFields && !modalBody.classList.contains('customer-modal-restructured')) {
                        processModal('editCustomerModal', true);
                    } else if (retryCount < maxRetries) {
                        retryCount++;
                        setTimeout(tryRestructure, retryInterval);
                    } else {
                        console.warn('Customer Modal Layout: Edit fields not found after', maxRetries, 'retries');
                    }
                }
                
                setTimeout(tryRestructure, 100);
            }
        });
        
        // Also listen for jQuery/Bootstrap 4 events
        if (typeof $ !== 'undefined') {
            $(document).on('shown.bs.modal', '#addCustomerModal, #editCustomerModal', function() {
                const isEdit = this.id === 'editCustomerModal';
                const delay = isEdit ? 300 : 100;
                setTimeout(function() {
                    processModal(this.id, isEdit);
                }.bind(this), delay);
            });
        }
        
        // Hook into AJAX calls to restructure after data is loaded
        if (typeof $ !== 'undefined') {
            // Intercept AJAX calls to get_customer.php
            const originalAjax = $.ajax;
            $.ajax = function(options) {
                if (options.url && options.url.includes('get_customer.php')) {
                    const originalSuccess = options.success;
                    options.success = function(response) {
                        if (originalSuccess) {
                            originalSuccess.apply(this, arguments);
                        }
                        // Restructure after data is populated
                        setTimeout(function() {
                            processModal('editCustomerModal', true);
                        }, 100);
                    };
                }
                return originalAjax.apply(this, arguments);
            };
            
            // Also monitor the edit modal body for changes
            const editModalBody = document.querySelector('#editCustomerModal .modal-body');
            if (editModalBody) {
                const editObserver = new MutationObserver(function(mutations) {
                    let shouldRestructure = false;
                    mutations.forEach(function(mutation) {
                        if (mutation.addedNodes.length > 0 || mutation.type === 'childList') {
                            // Check if edit fields are now present
                            const hasEditFields = editModalBody.querySelector('input[id*="edit_"], select[id*="edit_"], textarea[id*="edit_"]');
                            if (hasEditFields && !editModalBody.classList.contains('customer-modal-restructured')) {
                                shouldRestructure = true;
                            }
                        }
                    });
                    if (shouldRestructure) {
                        setTimeout(function() {
                            processModal('editCustomerModal', true);
                        }, 150);
                    }
                });
                
                editObserver.observe(editModalBody, {
                    childList: true,
                    subtree: true
                });
            }
        }
        
        // Use MutationObserver to catch dynamically added modals
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        if (node.id === 'addCustomerModal' || node.querySelector && node.querySelector('#addCustomerModal')) {
                            setTimeout(function() {
                                processModal('addCustomerModal', false);
                            }, 100);
                        }
                        if (node.id === 'editCustomerModal' || node.querySelector && node.querySelector('#editCustomerModal')) {
                            setTimeout(function() {
                                processModal('editCustomerModal', true);
                            }, 100);
                        }
                    }
                });
            });
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }
    
    // Start initialization
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();

