/**
 * CargoHub Admin JavaScript
 * Handles admin interface interactions
 */

(function($) {
    'use strict';

    /**
     * CargoHub Admin Object
     */
    const CargoHubAdmin = {
        /**
         * Feature flag to disable unused AJAX flows and global $.ajax override
         */
        ENABLE_CARGOHUB_AJAX: false,
        
        /**
         * Initialize the admin functionality
         */
        init: function() {
            this.bindEvents();
            this.initializeComponents();
        },
        
        /**
         * Bind event handlers
         */
        bindEvents: function() {
            // Form submission
            if (this.ENABLE_CARGOHUB_AJAX) {
                $(document).on('submit', '.cargohub-form', this.handleFormSubmit);
            }
            
            // Edit tracking button
            $(document).on('click', '.cargohub-edit-tracking', this.toggleEditForm);
            
            // Cancel edit button
            $(document).on('click', '.cargohub-cancel-edit', this.cancelEdit);
            
            // Delete tracking button
            if (this.ENABLE_CARGOHUB_AJAX) {
                $(document).on('click', '.cargohub-delete-tracking', this.deleteTracking);
            }
            
            // Carrier selection change
            $(document).on('change', 'select[name="cargohub_carrier"], #cargohub_carrier', this.onCarrierChange);
            
            // Real-time tracking number validation
            $(document).on('input', 'input[name="cargohub_tracking_number"], #cargohub_tracking_number', this.validateTrackingNumber);
            
            // WooCommerce order status change monitoring
            $(document).on('change', '#order_status', this.handleOrderStatusChange);
            
            // WooCommerce order form submission validation (always enforce)
            $(document).on('submit', '#post', this.validateWooCommerceOrderForm);
            
            // Also catch publish/update button clicks
            $(document).on('click', '#publish, #save-post', this.validateWooCommerceOrderBeforeSubmit);
            
            // Manual email sending button
            if (this.ENABLE_CARGOHUB_AJAX) {
                $(document).on('click', '.cargohub-send-email-btn', this.handleManualEmailSend);
            }
        },
        
        /**
         * Initialize components
         */
        initializeComponents: function() {
            // Add fade-in animation to tracking boxes
            $('.cargohub-tracking-box').addClass('cargohub-fade-in');
            
            // Initialize tooltips if available
            if ($.fn.tooltip) {
                $('[data-tooltip]').tooltip();
            }
            
            // Auto-focus first input in forms
            $('.cargohub-tracking-form:visible').find('select, input').first().focus();
            
            // Initialize order status validation on WooCommerce order pages
            this.initOrderStatusValidation();
            
            // Override WooCommerce AJAX for order save
            if (this.ENABLE_CARGOHUB_AJAX) {
                this.overrideWooCommerceAjax();
            }
        },
        
        /**
         * Handle form submission
         */
        handleFormSubmit: function(e) {
            e.preventDefault();
            
            const $form = $(this);
            const $submitBtn = $form.find('.cargohub-save-tracking');
            const orderId = $form.data('order-id');
            
            // Validate form
            if (!CargoHubAdmin.validateForm($form)) {
                return;
            }
            
            // Show loading state
            CargoHubAdmin.setLoadingState($form, true);
            $submitBtn.prop('disabled', true).text('Saving...');
            
            // Prepare data
            const formData = {
                action: 'cargohub_save_tracking',
                nonce: cargohub_ajax.nonce,
                order_id: orderId,
                carrier: $form.find('select[name="carrier"]').val(),
                tracking_number: $form.find('input[name="tracking_number"]').val().trim()
            };
            
            // Send AJAX request
            $.ajax({
                url: cargohub_ajax.ajax_url,
                type: 'POST',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        CargoHubAdmin.showMessage('success', response.data.message || cargohub_ajax.messages.saved);
                        CargoHubAdmin.refreshTrackingBox(orderId);
                        // Reload page after short delay to show updated state
                        setTimeout(function() {
                            window.location.reload();
                        }, 1500);
                    } else {
                        CargoHubAdmin.showMessage('error', response.data.message || cargohub_ajax.messages.error);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('CargoHub AJAX Error:', error);
                    CargoHubAdmin.showMessage('error', cargohub_ajax.messages.error);
                },
                complete: function() {
                    CargoHubAdmin.setLoadingState($form, false);
                    $submitBtn.prop('disabled', false).text('Save Tracking Info');
                }
            });
        },
        
        /**
         * Toggle edit form visibility
         */
        toggleEditForm: function(e) {
            e.preventDefault();
            
            const orderId = $(this).data('order-id');
            const $trackingBox = $('#cargohub-tracking-' + orderId);
            const $existingDiv = $trackingBox.find('.cargohub-existing-tracking');
            const $formDiv = $trackingBox.find('.cargohub-tracking-form');
            
            $existingDiv.slideUp(300);
            $formDiv.slideDown(300, function() {
                $formDiv.find('select, input').first().focus();
            });
        },
        
        /**
         * Cancel edit operation
         */
        cancelEdit: function(e) {
            e.preventDefault();
            
            const $form = $(this).closest('.cargohub-tracking-form');
            const $trackingBox = $form.closest('.cargohub-tracking-box');
            const $existingDiv = $trackingBox.find('.cargohub-existing-tracking');
            
            $form.slideUp(300);
            $existingDiv.slideDown(300);
            
            // Reset form
            $form.find('form')[0].reset();
        },
        
        /**
         * Delete tracking information
         */
        deleteTracking: function(e) {
            e.preventDefault();
            
            if (!confirm(cargohub_ajax.messages.confirm_delete)) {
                return;
            }
            
            const orderId = $(this).data('order-id');
            const $button = $(this);
            
            // Show loading state
            $button.prop('disabled', true).text('Deleting...');
            
            // Prepare data
            const data = {
                action: 'cargohub_delete_tracking',
                nonce: cargohub_ajax.nonce,
                order_id: orderId
            };
            
            // Send AJAX request
            $.ajax({
                url: cargohub_ajax.ajax_url,
                type: 'POST',
                data: data,
                success: function(response) {
                    if (response.success) {
                        CargoHubAdmin.showMessage('success', response.data.message || cargohub_ajax.messages.deleted);
                        // Reload page after short delay
                        setTimeout(function() {
                            window.location.reload();
                        }, 1500);
                    } else {
                        CargoHubAdmin.showMessage('error', response.data.message || cargohub_ajax.messages.error);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('CargoHub Delete Error:', error);
                    CargoHubAdmin.showMessage('error', cargohub_ajax.messages.error);
                },
                complete: function() {
                    $button.prop('disabled', false).text('Delete Tracking');
                }
            });
        },
        
        /**
         * Handle carrier selection change
         */
        onCarrierChange: function() {
            const $select = $(this);
            const $container = $select.closest('.cargohub-tracking-form');
            const $trackingInput = $container.find('input[name="cargohub_tracking_number"], #cargohub_tracking_number');
            const carrier = $select.val();
            
            // Update placeholder and validation based on carrier
            if (carrier) {
                $trackingInput.attr('placeholder', CargoHubAdmin.getTrackingPlaceholder(carrier));
                
                // Add carrier-specific class for styling
                $container.removeClass('carrier-yurtici carrier-aras carrier-dhl carrier-suratkargo carrier-ptt carrier-pttkargo carrier-pttgonderi');
                $container.addClass('carrier-' + carrier);
            } else {
                $trackingInput.attr('placeholder', 'Enter tracking number');
                $container.removeClass('carrier-yurtici carrier-aras carrier-dhl carrier-suratkargo carrier-ptt carrier-pttkargo carrier-pttgonderi');
            }
            
            // Clear any existing validation messages
            CargoHubAdmin.clearValidationMessage($trackingInput);
        },
        
        /**
         * Get tracking number placeholder for carrier
         */
        getTrackingPlaceholder: function(carrier) {
            const placeholders = {
                'yurtici': '123456789012',
                'aras': '0123456789TR',
                'dhl': '1234567890',
                'suratkargo': '1234567890123',
                'sratkargo': '1234567890123',
                'surat': '1234567890123',
                'ptt': '1234567890123',
                'pttkargo': '1234567890123',
                'pttgonderi': '1234567890123'
            };
            
            return placeholders[carrier] || 'Takip Kodu Giriniz';
        },
        
        /**
         * Validate tracking number in real-time
         */
        validateTrackingNumber: function() {
            const $input = $(this);
            // Remove inline validation hints; no real-time valid/invalid message is shown
            CargoHubAdmin.clearValidationMessage($input);
        },
        
        /**
         * Validate tracking number format
         */
        validateTrackingFormat: function(trackingNumber, carrier) {
            const cleanNumber = trackingNumber.replace(/\s/g, '');
            
            switch (carrier) {
                case 'yurtici':
                    return /^\d{12}$/.test(cleanNumber);
                case 'aras':
                    return /^AR\d+TR$/i.test(cleanNumber);
                case 'dhl':
                    return /^\d{10,11}$/.test(cleanNumber);
                case 'suratkargo':
                case 'sratkargo': 
                case 'surat':
                    return /^\d{10,13}$/.test(cleanNumber);
                case 'ptt':
                case 'pttkargo':
                case 'pttgonderi':
                    return /^\d{13}$/.test(cleanNumber);
                default:
                    return cleanNumber.length >= 6;
            }
        },
        
        
        
        /**
         * Clear validation message (noop after removal of inline hints)
         */
        clearValidationMessage: function($input) {
            $input.siblings('.cargohub-validation-message').remove();
        },
        
        /**
         * Validate form before submission
         */
        validateForm: function($form) {
            let isValid = true;
            
            // Check carrier selection
            const carrier = $form.find('select[name="carrier"]').val();
            if (!carrier) {
                CargoHubAdmin.showMessage('error', 'Please select a carrier.');
                isValid = false;
            }
            
            // Check tracking number
            const trackingNumber = $form.find('input[name="tracking_number"]').val().trim();
            if (!trackingNumber) {
                CargoHubAdmin.showMessage('error', 'Please enter a tracking number.');
                isValid = false;
            } else if (carrier && !CargoHubAdmin.validateTrackingFormat(trackingNumber, carrier)) {
                CargoHubAdmin.showMessage('error', 'Please enter a valid tracking number for the selected carrier.');
                isValid = false;
            }
            
            return isValid;
        },
        
        /**
         * Set loading state for form
         */
        setLoadingState: function($form, loading) {
            if (loading) {
                $form.addClass('cargohub-loading');
            } else {
                $form.removeClass('cargohub-loading');
            }
        },
        
        /**
         * Show message to user
         */
        showMessage: function(type, message) {
            // Remove existing messages
            $('.cargohub-message').remove();
            
            // Create new message
            const $message = $('<div class="cargohub-message ' + type + '">' + message + '</div>');
            
            // Insert message at the top of the page or in the tracking box
            const $target = $('.cargohub-tracking-box').first();
            if ($target.length) {
                $target.before($message);
            } else {
                $('.wrap').prepend($message);
            }
            
            // Auto-hide message after 5 seconds
            setTimeout(function() {
                $message.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 5000);
            
            // Scroll to message
            $('html, body').animate({
                scrollTop: $message.offset().top - 100
            }, 300);
        },
        
        /**
         * Initialize order status validation
         */
        initOrderStatusValidation: function() {
            // Only run on WooCommerce order edit pages
            if (!$('#order_status').length) return;
            
            // Check current status on page load
            this.updateCargoRequiredFields();
        },
        
        /**
         * Handle order status change
         */
        handleOrderStatusChange: function() {
            CargoHubAdmin.updateCargoRequiredFields();
        },
        
        /**
         * Update cargo fields required status based on order status
         */
        updateCargoRequiredFields: function() {
            const orderStatus = $('#order_status').val();
            
            // Try multiple selectors for cargo fields
            const $carrierField = $('select[name="cargohub_carrier"], #cargohub_carrier').first();
            const $trackingField = $('input[name="cargohub_tracking_number"], #cargohub_tracking_number').first();
            
            if (orderStatus === 'wc-shipped') {
                // Make fields required
                $carrierField.prop('required', true);
                $trackingField.prop('required', true);
                
                // Add visual indicators
                $carrierField.closest('p, td').find('label').addClass('required');
                $trackingField.closest('p, td').find('label').addClass('required');
                
                // Add required asterisk if not already present
                if (!$carrierField.closest('p, td').find('label .required-asterisk').length) {
                    $carrierField.closest('p, td').find('label').append(' <span class="required-asterisk">*</span>');
                }
                if (!$trackingField.closest('p, td').find('label .required-asterisk').length) {
                    $trackingField.closest('p, td').find('label').append(' <span class="required-asterisk">*</span>');
                }
                
                // Add red border to fields
                $carrierField.addClass('cargohub-required-field');
                $trackingField.addClass('cargohub-required-field');
                
                // Show warning message
                this.showCargoFieldsWarning();
            } else {
                // Remove required
                $carrierField.prop('required', false);
                $trackingField.prop('required', false);
                
                // Remove visual indicators
                $carrierField.closest('p, td').find('label').removeClass('required');
                $trackingField.closest('p, td').find('label').removeClass('required');
                
                // Remove required asterisk
                $carrierField.closest('p, td').find('label .required-asterisk').remove();
                $trackingField.closest('p, td').find('label .required-asterisk').remove();
                
                // Remove red border from fields
                $carrierField.removeClass('cargohub-required-field');
                $trackingField.removeClass('cargohub-required-field');
                
                // Hide warning message
                this.hideCargoFieldsWarning();
            }
        },
        
        /**
         * Show cargo fields warning
         */
        showCargoFieldsWarning: function() {
            if (!$('.cargohub-cargo-warning').length) {
                const warningHtml = '<div class="cargohub-cargo-warning" style="background: #fff3cd; border: 1px solid #ffeaa7; color: #856404; padding: 10px; margin: 10px 0; border-radius: 5px;">' +
                    '<strong>⚠️ UYARI:</strong> Sipariş durumu "Kargoya Verildi" olarak ayarlandığında Kargo Firması ve Takip Kodu alanları zorunludur!' +
                    '</div>';
                
                $('#order_status').closest('p').after(warningHtml);
            }
        },
        
        /**
         * Hide cargo fields warning
         */
        hideCargoFieldsWarning: function() {
            $('.cargohub-cargo-warning').remove();
        },
        
        /**
         * Validate WooCommerce order form
         */
        validateWooCommerceOrderForm: function(e) {
            return CargoHubAdmin.performOrderValidation(e);
        },
        
        /**
         * Validate WooCommerce order before submit button click
         */
        validateWooCommerceOrderBeforeSubmit: function(e) {
            return CargoHubAdmin.performOrderValidation(e);
        },
        
        /**
         * Core validation logic for WooCommerce order
         */
        performOrderValidation: function(e) {
            const orderStatus = $('#order_status').val();
            
            // Check if order status is "Kargoya Verildi" (shipped)
            if (orderStatus === 'wc-shipped') {
                // Block immediately if there are no carriers defined at all
                if (typeof cargohub_ajax !== 'undefined' && cargohub_ajax.has_carriers === false) {
                    e.preventDefault();
                    e.stopPropagation();
                    alert('⚠️ SİPARİŞ KAYIT EDİLEMEZ!\n\n' + (cargohub_ajax.messages.no_carriers || 'Önce kargo firması ekleyin.'));
                    return false;
                }

                const carrierValue = $('select[name="cargohub_carrier"], #cargohub_carrier').val();
                const trackingValue = $('input[name="cargohub_tracking_number"], #cargohub_tracking_number').val();
                
                let errorMessage = '';
                let hasErrors = false;
                
                // Check if carrier is selected
                if (!carrierValue || carrierValue === '' || carrierValue === 'Kargo Firması Seç') {
                    errorMessage += '• Kargo Firması seçimi zorunludur.\n';
                    hasErrors = true;
                }
                
                // Check if tracking number is entered
                if (!trackingValue || trackingValue.trim() === '') {
                    errorMessage += '• Takip Kodu girişi zorunludur.\n';
                    hasErrors = true;
                }
                
                if (hasErrors) {
                    e.preventDefault();
                    e.stopPropagation();
                    alert('⚠️ SİPARİŞ KAYIT EDİLEMEZ!\n\nSipariş durumu "Kargoya Verildi" olarak ayarlandığında:\n\n' + errorMessage);
                    return false;
                }
            }
            
            return true;
        },
        
        /**
         * Override WooCommerce AJAX for order save
         */
        overrideWooCommerceAjax: function() {
            // Only run on WooCommerce order pages
            if (!$('#order_status').length) return;
            
            // Store original jQuery AJAX
            const originalAjax = $.ajax;
            
            // Override AJAX for WooCommerce order save
            $.ajax = function(options) {
                // Check if this is a WooCommerce order save request
                if (options.url && options.url.indexOf('admin-ajax.php') !== -1) {
                    if (options.data && (
                        options.data.indexOf('action=woocommerce_save_order') !== -1 ||
                        options.data.indexOf('action=editpost') !== -1
                    )) {
                        // Perform validation before AJAX
                        if (!CargoHubAdmin.validateOrderBeforeAjax()) {
                            return false;
                        }
                    }
                }
                
                // Call original AJAX
                return originalAjax.apply(this, arguments);
            };
        },
        
        /**
         * Validate order before AJAX save
         */
        validateOrderBeforeAjax: function() {
            const orderStatus = $('#order_status').val();
            
            if (orderStatus === 'wc-shipped') {
                if (typeof cargohub_ajax !== 'undefined' && cargohub_ajax.has_carriers === false) {
                    alert('⚠️ SİPARİŞ KAYIT EDİLEMEZ!\n\n' + (cargohub_ajax.messages.no_carriers || 'Önce kargo firması ekleyin.'));
                    return false;
                }

                const carrierValue = $('select[name="cargohub_carrier"], #cargohub_carrier').val();
                const trackingValue = $('input[name="cargohub_tracking_number"], #cargohub_tracking_number').val();
                
                let errorMessage = '';
                let hasErrors = false;
                
                if (!carrierValue || carrierValue === '' || carrierValue === 'Kargo Firması Seç') {
                    errorMessage += '• Kargo Firması seçimi zorunludur.\n';
                    hasErrors = true;
                }
                
                if (!trackingValue || trackingValue.trim() === '') {
                    errorMessage += '• Takip Kodu girişi zorunludur.\n';
                    hasErrors = true;
                }
                
                if (hasErrors) {
                    alert('⚠️ SİPARİŞ KAYIT EDİLEMEZ!\n\nSipariş durumu "Kargoya Verildi" olarak ayarlandığında:\n\n' + errorMessage);
                    return false;
                }
            }
            
            return true;
        },
        
        /**
         * Handle manual email sending
         */
        handleManualEmailSend: function(e) {
            e.preventDefault();
            
            const $button = $(this);
            const orderId = $button.data('order-id');
            const $statusSpan = $button.siblings('.cargohub-email-status');
            
            // Check if we have tracking data
            const $trackingBox = $button.closest('.cargohub-tracking-box');
            const hasTrackingData = $trackingBox.find('.cargohub-existing-tracking').length > 0;
            
            if (!hasTrackingData) {
                CargoHubAdmin.showMessage('error', cargohub_ajax.messages.no_tracking_data || 'Takip bilgisi bulunamadı.');
                return;
            }
            
            // Disable button and show loading state
            $button.prop('disabled', true).text('Gönderiliyor...');
            $statusSpan.text('E-posta gönderiliyor...').removeClass('success error').addClass('sending');
            
            // Prepare AJAX data
            const data = {
                action: 'cargohub_send_tracking_email',
                nonce: cargohub_ajax.nonce,
                order_id: orderId
            };
            
            // Send AJAX request
            $.ajax({
                url: cargohub_ajax.ajax_url,
                type: 'POST',
                data: data,
                success: function(response) {
                    if (response.success) {
                        CargoHubAdmin.showMessage('success', response.data.message || cargohub_ajax.messages.email_sent || 'Takip e-postası başarıyla gönderildi.');
                        $statusSpan.text('E-posta gönderildi ✓').removeClass('sending error').addClass('success');
                        
                        // Hide status message after 3 seconds
                        setTimeout(function() {
                            $statusSpan.text('').removeClass('success');
                        }, 3000);
                    } else {
                        const errorMsg = response.data.message || cargohub_ajax.messages.email_error || 'E-posta gönderilirken hata oluştu.';
                        CargoHubAdmin.showMessage('error', errorMsg);
                        $statusSpan.text('Hata: ' + errorMsg).removeClass('sending success').addClass('error');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('CargoHub Email Send Error:', error);
                    const errorMsg = cargohub_ajax.messages.email_error || 'E-posta gönderilirken hata oluştu.';
                    CargoHubAdmin.showMessage('error', errorMsg);
                    $statusSpan.text('Network hatası').removeClass('sending success').addClass('error');
                },
                complete: function() {
                    // Re-enable button
                    $button.prop('disabled', false).text('Takip E-postası Gönder');
                }
            });
        },
        
        /**
         * Refresh tracking box content
         */
        refreshTrackingBox: function(orderId) {
            // This would typically reload the tracking box content via AJAX
            // For now, we'll just reload the page
            setTimeout(function() {
                window.location.reload();
            }, 1000);
        }
    };
    
    /**
     * Initialize when document is ready
     */
    $(document).ready(function() {
        CargoHubAdmin.init();
    });
    
    // Removed inline validation CSS injection (no longer used)

})(jQuery); 