/**
 * Utility Server CDN Manager - Admin JavaScript
 */

(function($) {
    'use strict';
    
    $(document).ready(function() {
        
        // Tab Switching
        $('.uscdn-tab').on('click', function() {
            const tabId = $(this).data('tab');
            
            // Update tab buttons
            $('.uscdn-tab').removeClass('active');
            $(this).addClass('active');
            
            // Update tab content
            $('.uscdn-tab-content').removeClass('active');
            $('#' + tabId).addClass('active');
        });
        
        // Test CDN Button
        $('.uscdn-test-btn').on('click', function() {
            const $btn = $(this);
            const $result = $btn.siblings('.uscdn-test-result');
            const cdnUrl = $btn.data('cdn-url');
            const cdnType = $btn.data('cdn-type');
            
            if (!cdnUrl) {
                showResult($result, 'error', 'CDN URL is not configured');
                return;
            }
            
            // Show loading state
            $btn.prop('disabled', true).text(uscdnAdmin.strings.testing);
            $result.removeClass('success error').addClass('loading').text('Testing connection...').show();
            
            // Make AJAX request
            $.ajax({
                url: uscdnAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'uscdn_test_cdn',
                    nonce: uscdnAdmin.nonce,
                    cdn_url: cdnUrl,
                    cdn_type: cdnType
                },
                success: function(response) {
                    if (response.success) {
                        showResult($result, 'success', '✓ ' + response.data.message);
                    } else {
                        showResult($result, 'error', '✗ ' + response.data.message);
                    }
                },
                error: function() {
                    showResult($result, 'error', '✗ Connection failed. Please check your configuration.');
                },
                complete: function() {
                    $btn.prop('disabled', false).text('Test Connection');
                }
            });
        });
        
        // Clear Cache Button
        $('.uscdn-clear-cache-btn').on('click', function() {
            const $btn = $(this);
            
            if (!confirm('Are you sure you want to clear all cached CSS files? This will send the X-Cache-Flush: TRUE header.')) {
                return;
            }
            
            // Show loading state
            $btn.prop('disabled', true).text(uscdnAdmin.strings.clearing);
            
            // Make AJAX request
            $.ajax({
                url: uscdnAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'uscdn_clear_cache',
                    nonce: uscdnAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        alert(uscdnAdmin.strings.success + ' ' + response.data.message);
                        location.reload();
                    } else {
                        alert(uscdnAdmin.strings.error + ' ' + response.data.message);
                    }
                },
                error: function() {
                    alert(uscdnAdmin.strings.error + ' Failed to clear cache.');
                },
                complete: function() {
                    $btn.prop('disabled', false).text('Clear All Cache');
                }
            });
        });
        
        // Helper function to show result
        function showResult($element, type, message) {
            $element
                .removeClass('loading success error')
                .addClass(type)
                .text(message)
                .show();
        }
        
        // Form validation
        $('.uscdn-form').on('submit', function(e) {
            let hasErrors = false;
            const $form = $(this);
            
            // Check if any CDN is enabled
            const imageEnabled = $form.find('input[name="enable_image_cdn"]').is(':checked');
            const staticEnabled = $form.find('input[name="enable_static_cdn"]').is(':checked');
            const linkEnabled = $form.find('input[name="enable_link_cdn"]').is(':checked');
            
            // Validate Image CDN
            if (imageEnabled) {
                const imageUrl = $form.find('input[name="cdn_image_base"]').val();
                if (!imageUrl) {
                    alert('Please enter Image CDN Base URL or disable Image CDN.');
                    hasErrors = true;
                }
            }
            
            // Validate Static CDN
            if (staticEnabled) {
                const staticUrl = $form.find('input[name="cdn_static_base"]').val();
                if (!staticUrl) {
                    alert('Please enter Static CDN Base URL or disable Static CDN.');
                    hasErrors = true;
                }
            }
            
            // Validate Link CDN
            if (linkEnabled) {
                const linkUrl = $form.find('input[name="cdn_link_base"]').val();
                if (!linkUrl) {
                    alert('Please enter Link CDN Base URL or disable Link CDN.');
                    hasErrors = true;
                }
            }
            
            if (hasErrors) {
                e.preventDefault();
                return false;
            }
        });
        
    });
    
})(jQuery);
