/**
 * Admin JavaScript for the Subscription System plugin
 */
(function($) {
    'use strict';

    $(document).ready(function() {
        // Handle subscription actions (cancel, delete, etc.)
        $('.ss-admin-action').on('click', function(e) {
            e.preventDefault();
            
            var action = $(this).data('action');
            var subscriptionId = $(this).data('id');
            var confirmMessage = '';
            
            // Confirm action
            if (action === 'delete') {
                confirmMessage = ss_admin_vars.i18n.confirm_delete;
            } else if (action === 'cancel') {
                confirmMessage = ss_admin_vars.i18n.confirm_cancel;
            }
            
            if (confirmMessage && !confirm(confirmMessage)) {
                return;
            }
            
            // Show loading state
            $(this).addClass('disabled').text('Processing...');
            
            // Send AJAX request
            $.ajax({
                url: ss_admin_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'ss_manage_subscription',
                    ss_action: action,
                    subscription_id: subscriptionId,
                    nonce: ss_admin_vars.nonce
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        
                        // Reload page to show updated data
                        window.location.reload();
                    } else {
                        alert(ss_admin_vars.i18n.error + ' ' + response.data.message);
                    }
                },
                error: function() {
                    alert(ss_admin_vars.i18n.error);
                }
            });
        });
        
        // Handle status change
        $('.ss-status-select').on('change', function() {
            var subscriptionId = $(this).data('id');
            var status = $(this).val();
            
            // Send AJAX request
            $.ajax({
                url: ss_admin_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'ss_manage_subscription',
                    ss_action: 'update_status',
                    subscription_id: subscriptionId,
                    status: status,
                    nonce: ss_admin_vars.nonce
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                    } else {
                        alert(ss_admin_vars.i18n.error + ' ' + response.data.message);
                    }
                },
                error: function() {
                    alert(ss_admin_vars.i18n.error);
                }
            });
        });
        
        // Add new plan
        $('#ss-add-plan').on('click', function(e) {
            e.preventDefault();
            
            var planId = 'plan_' + Math.floor(Math.random() * 1000000);
            var planTemplate = $('#ss-plan-template').html();
            
            // Replace template variables
            planTemplate = planTemplate.replace(/\{plan_id\}/g, planId);
            
            // Add to plans container
            $('.ss-admin-plans').append(planTemplate);
        });
        
        // Remove plan
        $(document).on('click', '.ss-remove-plan', function(e) {
            e.preventDefault();
            
            if (confirm('Are you sure you want to remove this plan?')) {
                $(this).closest('.ss-admin-plan').remove();
            }
        });
        
        // Layout preview toggle
        $('select[name="default_pricing_layout"]').on('change', function() {
            var selectedLayout = $(this).val();
            $('.layout-preview').hide();
            $('#' + selectedLayout + '-preview').show();
        });
        
        // Sync plan with Stripe
        $('.sync-with-stripe').on('click', function(e) {
            e.preventDefault();
            
            var button = $(this);
            var planId = button.data('plan-id');
            
            if (!planId) {
                alert('Invalid plan ID');
                return;
            }
            
            button.text('Syncing...').addClass('disabled');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sync_plan_with_stripe',
                    plan_id: planId,
                    security: subscription_system_admin.nonces.test_stripe_connection
                },
                success: function(response) {
                    if (response.success) {
                        var statusCell = button.closest('td');
                        var isMock = response.data.mock_mode;
                        
                        var statusHtml = '<span class="stripe-status ' + (isMock ? 'mock-connected' : 'connected') + '">' +
                            '<span class="dashicons dashicons-' + (isMock ? 'warning' : 'yes-alt') + '"></span> ' +
                            (isMock ? 'Mock Connected' : 'Connected') + '</span>';
                        
                        if (isMock) {
                            statusHtml += '<br><small>Using test data - not connected to Stripe</small>';
                        } else {
                            statusHtml += '<br><small>Product ID: ' + response.data.product_id.substring(0, 8) + '...</small>';
                            statusHtml += '<br><small>Price ID: ' + response.data.price_id.substring(0, 8) + '...</small>';
                        }
                        
                        statusCell.html(statusHtml);
                        statusCell.append('<br><a href="#" class="sync-with-stripe" data-plan-id="' + planId + '">Sync with Stripe</a>');
                        
                        // Show success message
                        $('h1.wp-heading-inline').after('<div class="notice notice-' + (isMock ? 'warning' : 'success') + ' is-dismissible"><p>' + response.data.message + '</p></div>');
                    } else {
                        button.text('Sync with Stripe').removeClass('disabled');
                        
                        // Show error message
                        $('h1.wp-heading-inline').after('<div class="notice notice-error is-dismissible"><p>' + response.data.message + '</p></div>');
                    }
                    
                    // Initialize dismissible notices
                    $('.notice.is-dismissible').each(function() {
                        var $notice = $(this);
                        $notice.append('<button type="button" class="notice-dismiss"></button>');
                        $notice.on('click', '.notice-dismiss', function() {
                            $notice.fadeOut(300, function() { $notice.remove(); });
                        });
                    });
                },
                error: function() {
                    button.text('Sync with Stripe').removeClass('disabled');
                    
                    // Show error message
                    $('h1.wp-heading-inline').after('<div class="notice notice-error is-dismissible"><p>An error occurred. Please try again.</p></div>');
                }
            });
        });
        
        // Test Stripe connection
        $('#test-stripe-connection').on('click', function() {
            var button = $(this);
            var resultSpan = $('#stripe-connection-result');
            
            button.prop('disabled', true).text('Testing...');
            resultSpan.html('');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'test_stripe_connection',
                    security: subscription_system_admin.nonce
                },
                success: function(response) {
                    button.prop('disabled', false).text('Test Connection');
                    
                    if (response.success) {
                        resultSpan.html('<span style="color: green;">✓ Connection successful! Your Stripe API keys are working correctly.</span>');
                    } else {
                        var errorMessage = response.data.message;
                        var errorCode = response.data.code || '';
                        
                        // Provide more helpful messages for common errors
                        if (errorCode === 'invalid_api_key') {
                            errorMessage += '<br>Please check that you are using the correct API key (test or live).';
                        } else if (errorCode === 'stripe_sdk_missing') {
                            errorMessage += '<br>The plugin is using a mock implementation for testing. For production, please install the Stripe PHP SDK.';
                        }
                        
                        resultSpan.html('<span style="color: red;">✗ ' + errorMessage + '</span>');
                    }
                },
                error: function() {
                    button.prop('disabled', false).text('Test Connection');
                    resultSpan.html('<span style="color: red;">✗ Connection failed. Please check your server\'s internet connection and PHP configuration.</span>');
                }
            });
        });
        
        // Install Stripe SDK
        $('#install-stripe-sdk').on('click', function() {
            var $button = $(this);
            var $result = $('#stripe-sdk-install-result');
            
            $button.prop('disabled', true);
            $result.html('Installing Stripe SDK...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'install_stripe_sdk',
                    nonce: subscription_system_admin.nonces.install_stripe_sdk
                },
                success: function(response) {
                    if (response.success) {
                        $result.html('<span style="color: green;">' + response.data.message + '</span>');
                        setTimeout(function() {
                            location.reload();
                        }, 2000);
                    } else {
                        $result.html('<span style="color: red;">' + response.data.message + '</span>');
                    }
                },
                error: function() {
                    $result.html('<span style="color: red;">Error installing Stripe SDK.</span>');
                },
                complete: function() {
                    $button.prop('disabled', false);
                }
            });
        });
        
        // Handle Stripe mode selection
        $('#stripe_mode').on('change', function() {
            var mode = $(this).val();
            var apiKeyField = $('input[name="stripe_api_key"]');
            var publishableKeyField = $('input[name="stripe_publishable_key"]');
            var apiKeyDesc = apiKeyField.siblings('.description').not('.current-key');
            var publishableKeyDesc = publishableKeyField.siblings('.description');
            
            if (mode === 'test') {
                apiKeyDesc.html('<strong>Important:</strong> This must be your <em>Secret</em> API Key, starting with "sk_test_" for test mode. You can find this in your <a href="https://dashboard.stripe.com/apikeys" target="_blank">Stripe Dashboard</a>.');
                publishableKeyDesc.html('Your Stripe Publishable Key, starting with "pk_test_" for test mode.');
            } else {
                apiKeyDesc.html('<strong>Important:</strong> This must be your <em>Secret</em> API Key, starting with "sk_live_" for live mode. You can find this in your <a href="https://dashboard.stripe.com/apikeys" target="_blank">Stripe Dashboard</a>.');
                publishableKeyDesc.html('Your Stripe Publishable Key, starting with "pk_live_" for live mode.');
            }
            
            // Show warning if switching to live mode
            if (mode === 'live') {
                if (!$('#live-mode-warning').length) {
                    $('<div id="live-mode-warning" class="notice notice-warning"><p><strong>Warning:</strong> You are switching to live mode. Make sure your site is properly configured and tested before processing real payments.</p></div>').insertAfter($(this).closest('tr'));
                }
            } else {
                $('#live-mode-warning').remove();
            }
        });
        
        // Trigger the change event on page load
        $('#stripe_mode').trigger('change');
        
        // Check API key
        $('#check-api-key').on('click', function() {
            var $button = $(this);
            var $result = $('#api-key-result');
            
            $button.prop('disabled', true);
            $result.html('Checking API key...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'check_stripe_api_key',
                    security: subscription_system_admin.nonces.test_stripe_connection
                },
                success: function(response) {
                    if (response.success) {
                        $result.html('<span style="color: green;">' + response.data.message + '</span>');
                    } else {
                        $result.html('<span style="color: red;">' + response.data.message + '</span>');
                    }
                },
                error: function() {
                    $result.html('<span style="color: red;">Error checking API key.</span>');
                },
                complete: function() {
                    $button.prop('disabled', false);
                }
            });
        });
    });
})(jQuery); 