/**
 * Cloudflare Integration Admin JavaScript for BotFend Anti-Bot Firewall
 *
 * Handles connection testing, IP syncing, cache purging, rule management,
 * and all AJAX interactions for the Cloudflare integration.
 *
 * @package BotFend\Assets\JS
 * @since 4.9.0
 */

(function($) {
    'use strict';

    /**
     * Initialize all Cloudflare admin functionality
     */
    $(document).ready(function() {

        /**
         * Toggle authentication method fields
         * Shows/hides the appropriate credential fields based on selected method
         */
        function toggleAuthFields() {
            var method = $('#botfend-cf-auth-method').val();
            
            if ('key' === method) {
                // Global API Key is selected (Recommended)
                $('#cf-key-section, #cf-key-row').show();
                $('#cf-token-section, #cf-token-row').hide();
            } else {
                // API Token is selected (Advanced)
                $('#cf-key-section, #cf-key-row').hide();
                $('#cf-token-section, #cf-token-row').show();
            }
        }

        // Bind auth method change event
        $('#botfend-cf-auth-method').on('change', toggleAuthFields);
        toggleAuthFields();

        /**
         * Test Cloudflare API Connection
         */
        $('#botfend-cf-test-connection').on('click', function() {
            var $btn = $(this);
            var $result = $('#botfend-cf-test-result');
            
            $btn.prop('disabled', true);
            $result.text(botfendCF.i18n.testing).css('color', '#007cba');

            $.post(botfendCF.ajaxurl, {
                action: 'botfend_cf_test_connection',
                nonce: botfendCF.nonce
            }, function(response) {
                $btn.prop('disabled', false);
                
                if (response.success) {
                    $result.css('color', '#46b450').text(botfendCF.i18n.connection_ok);
                } else {
                    var errorMsg = response.data?.message || '';
                    $result.css('color', '#dc3232').text(botfendCF.i18n.connection_fail + ': ' + errorMsg);
                }
            }).fail(function() {
                $btn.prop('disabled', false);
                $result.css('color', '#dc3232').text(botfendCF.i18n.error);
            });
        });

        /**
         * Refresh Status (Reload Page)
         */
        $('#botfend-cf-refresh-status').on('click', function() {
            location.reload();
        });

        /**
         * Sync Blocked IPs to Cloudflare
         */
        $('#botfend-cf-sync-now').on('click', function() {
            if (!confirm(botfendCF.i18n.confirm_sync)) {
                return;
            }

            var $btn = $(this);
            var $status = $('#botfend-cf-action-status');
            
            $btn.prop('disabled', true);
            $status.text(botfendCF.i18n.syncing).css('color', '#007cba');

            $.post(botfendCF.ajaxurl, {
                action: 'botfend_cf_sync_now',
                nonce: botfendCF.nonce
            }, function(response) {
                $btn.prop('disabled', false);
                
                if (response.success) {
                    var msg = botfendCF.i18n.sync_complete
                        .replace('%d', response.data.synced)
                        .replace('%d', response.data.failed);
                    $status.css('color', '#46b450').text(msg);
                    
                    // Reload after 2 seconds to show updated data
                    setTimeout(function() {
                        location.reload();
                    }, 2000);
                } else {
                    var errorMsg = response.data?.message || botfendCF.i18n.error;
                    $status.css('color', '#dc3232').text(errorMsg);
                }
            }).fail(function() {
                $btn.prop('disabled', false);
                $status.css('color', '#dc3232').text(botfendCF.i18n.error);
            });
        });

        /**
         * Purge Cloudflare Cache
         */
        $('#botfend-cf-purge-cache').on('click', function() {
            if (!confirm(botfendCF.i18n.confirm_purge)) {
                return;
            }

            var $btn = $(this);
            var $status = $('#botfend-cf-action-status');
            
            $btn.prop('disabled', true);
            $status.text(botfendCF.i18n.purging).css('color', '#007cba');

            $.post(botfendCF.ajaxurl, {
                action: 'botfend_cf_purge_cache',
                nonce: botfendCF.nonce
            }, function(response) {
                $btn.prop('disabled', false);
                
                if (response.success) {
                    $status.css('color', '#46b450').text(botfendCF.i18n.purge_complete);
                    
                    // Clear status after 3 seconds
                    setTimeout(function() {
                        $status.fadeOut('slow', function() {
                            $(this).text('').show();
                        });
                    }, 3000);
                } else {
                    var errorMsg = response.data?.message || botfendCF.i18n.error;
                    $status.css('color', '#dc3232').text(errorMsg);
                }
            }).fail(function() {
                $btn.prop('disabled', false);
                $status.css('color', '#dc3232').text(botfendCF.i18n.error);
            });
        });

        /**
         * Fix Integrity Issues
         */
        $('#botfend-cf-fix-integrity').on('click', function() {
            if (!confirm(botfendCF.i18n.confirm_fix)) {
                return;
            }

            var $btn = $(this);
            $btn.prop('disabled', true).text(botfendCF.i18n.fixing);

            $.post(botfendCF.ajaxurl, {
                action: 'botfend_cf_fix_integrity',
                nonce: botfendCF.nonce
            }, function(response) {
                $btn.prop('disabled', false);
                
                if (response.success) {
                    var msg = botfendCF.i18n.fix_complete.replace('%d', response.data.fixed);
                    alert(msg);
                    location.reload();
                } else {
                    alert(response.data?.message || botfendCF.i18n.error);
                }
            }).fail(function() {
                $btn.prop('disabled', false);
                alert(botfendCF.i18n.error);
            });
        });

        /**
         * Remove Individual IP from Cloudflare Rule
         */
        $(document).on('click', '.botfend-remove-ip', function() {
            var $btn = $(this);
            var ip = $btn.data('ip');
            var $row = $btn.closest('tr');
            
            if (!confirm(botfendCF.i18n.confirm_remove_ip.replace('%s', ip))) {
                return;
            }

            $btn.prop('disabled', true).text(botfendCF.i18n.removing);

            $.post(botfendCF.ajaxurl, {
                action: 'botfend_cf_remove_ip',
                nonce: botfendCF.nonce,
                ip: ip
            }, function(response) {
                if (response.success) {
                    $row.fadeOut(300, function() {
                        $(this).remove();
                        
                        // Check if this was the last IP in the rule
                        var $tbody = $btn.closest('.botfend-rule-card').find('tbody');
                        if ($tbody.find('tr').length === 0) {
                            location.reload();
                        }
                    });
                } else {
                    alert(response.data.message || botfendCF.i18n.error);
                    $btn.prop('disabled', false).text(botfendCF.i18n.remove);
                }
            }).fail(function() {
                alert(botfendCF.i18n.error);
                $btn.prop('disabled', false).text(botfendCF.i18n.remove);
            });
        });

        /**
         * Delete Entire Cloudflare Rule
         */
        $(document).on('click', '.botfend-delete-rule', function() {
            var $btn = $(this);
            var ruleId = $btn.data('rule-id');
            var ruleName = $btn.data('rule-name');
            var $card = $btn.closest('.botfend-rule-card');
            
            if (!confirm(botfendCF.i18n.confirm_delete_rule.replace('%s', ruleName))) {
                return;
            }

            $btn.prop('disabled', true).text(botfendCF.i18n.deleting);

            $.post(botfendCF.ajaxurl, {
                action: 'botfend_cf_delete_rule',
                nonce: botfendCF.nonce,
                rule_id: ruleId
            }, function(response) {
                if (response.success) {
                    $card.fadeOut(300, function() {
                        $(this).remove();
                    });
                } else {
                    alert(response.data.message || botfendCF.i18n.error);
                    $btn.prop('disabled', false).text(botfendCF.i18n.delete_rule);
                }
            }).fail(function() {
                alert(botfendCF.i18n.error);
                $btn.prop('disabled', false).text(botfendCF.i18n.delete_rule);
            });
        });

    });

})(jQuery);