<?php
/**
 * Payment settings admin page
 *
 * @package    Subscription_System
 * @subpackage Subscription_System/admin/partials
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Save settings if form is submitted
if (isset($_POST['subscription_payment_settings_nonce']) && wp_verify_nonce(wp_unslash($_POST['subscription_payment_settings_nonce']), 'subscription_payment_settings')) {
    // Save Stripe settings
    update_option('subscription_stripe_enabled', isset($_POST['stripe_enabled']) ? 1 : 0);
    update_option('subscription_stripe_test_mode', isset($_POST['stripe_test_mode']) ? 1 : 0);
    
    // Make sure to save these values with proper validation
    if (isset($_POST['stripe_publishable_key'])) {
        update_option('subscription_stripe_publishable_key', sanitize_text_field(wp_unslash($_POST['stripe_publishable_key'])));
    }
    if (isset($_POST['stripe_secret_key'])) {
        update_option('subscription_stripe_secret_key', sanitize_text_field(wp_unslash($_POST['stripe_secret_key'])));
    }
    if (isset($_POST['stripe_webhook_secret'])) {
        update_option('subscription_stripe_webhook_secret', sanitize_text_field(wp_unslash($_POST['stripe_webhook_secret'])));
    }
    
    // Save test mode keys separately
    if (isset($_POST['stripe_test_mode']) && $_POST['stripe_test_mode'] == 1) {
        if (isset($_POST['stripe_publishable_key'])) {
            update_option('subscription_stripe_test_publishable_key', sanitize_text_field(wp_unslash($_POST['stripe_publishable_key'])));
        }
        if (isset($_POST['stripe_secret_key'])) {
            update_option('subscription_stripe_test_secret_key', sanitize_text_field(wp_unslash($_POST['stripe_secret_key'])));
        }
        if (isset($_POST['stripe_webhook_secret'])) {
            update_option('subscription_stripe_test_webhook_secret', sanitize_text_field(wp_unslash($_POST['stripe_webhook_secret'])));
        }
    } else {
        if (isset($_POST['stripe_publishable_key'])) {
            update_option('subscription_stripe_live_publishable_key', sanitize_text_field(wp_unslash($_POST['stripe_publishable_key'])));
        }
        if (isset($_POST['stripe_secret_key'])) {
            update_option('subscription_stripe_live_secret_key', sanitize_text_field(wp_unslash($_POST['stripe_secret_key'])));
        }
        if (isset($_POST['stripe_webhook_secret'])) {
            update_option('subscription_stripe_live_webhook_secret', sanitize_text_field(wp_unslash($_POST['stripe_webhook_secret'])));
        }
    }
    
    // Debug log - this is intentional debug code for troubleshooting
    error_log('Saving Stripe settings - Secret key set: ' . (!empty($_POST['stripe_secret_key']) ? 'YES' : 'NO')); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    error_log('Stripe test mode: ' . (isset($_POST['stripe_test_mode']) ? 'YES' : 'NO')); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    
    // Save checkout page
    if (isset($_POST['checkout_page']) && !empty($_POST['checkout_page'])) {
        update_option('subscription_checkout_page', intval($_POST['checkout_page']));
    }
    
    // Save debug mode
    update_option('subscription_debug_mode', isset($_POST['debug_mode']) ? 1 : 0);
    
    // Show success message
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Payment settings saved successfully.', 'subscription-system') . '</p></div>';
}

// Get current settings
$stripe_enabled = get_option('subscription_stripe_enabled', 0);
$stripe_test_mode = get_option('subscription_stripe_test_mode', 1);

// Get the appropriate keys based on test mode
if ($stripe_test_mode) {
    $stripe_publishable_key = get_option('subscription_stripe_test_publishable_key', '');
    $stripe_secret_key = get_option('subscription_stripe_test_secret_key', '');
    $stripe_webhook_secret = get_option('subscription_stripe_test_webhook_secret', '');
} else {
    $stripe_publishable_key = get_option('subscription_stripe_live_publishable_key', '');
    $stripe_secret_key = get_option('subscription_stripe_live_secret_key', '');
    $stripe_webhook_secret = get_option('subscription_stripe_live_webhook_secret', '');
}

// Fallback to the general keys if specific ones are not set
if (empty($stripe_publishable_key)) {
    $stripe_publishable_key = get_option('subscription_stripe_publishable_key', '');
}
if (empty($stripe_secret_key)) {
    $stripe_secret_key = get_option('subscription_stripe_secret_key', '');
}
if (empty($stripe_webhook_secret)) {
    $stripe_webhook_secret = get_option('subscription_stripe_webhook_secret', '');
}

$checkout_page = get_option('subscription_checkout_page', 0);
$debug_mode = get_option('subscription_debug_mode', 0);
?>

<div class="wrap">
    
    <form method="post" action="">
        <?php wp_nonce_field('subscription_payment_settings', 'subscription_payment_settings_nonce'); ?>
        
        <h2><?php esc_html_e('Stripe Settings', 'subscription-system'); ?></h2>
        
        <?php if ($stripe_test_mode): ?>
        <div class="notice notice-warning inline">
            <p><strong><?php esc_html_e('Test Mode Active:', 'subscription-system'); ?></strong> <?php esc_html_e('Stripe is currently in test mode. No real charges will be made.', 'subscription-system'); ?></p>
        </div>
        <?php endif; ?>
        
        <table class="form-table">
            <tr>
                <th scope="row"><?php esc_html_e('Enable Stripe', 'subscription-system'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="stripe_enabled" value="1" <?php checked($stripe_enabled, 1); ?>>
                        <?php esc_html_e('Enable Stripe payments', 'subscription-system'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Mode', 'subscription-system'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="stripe_test_mode" id="stripe_test_mode" value="1" <?php checked($stripe_test_mode, 1); ?>>
                        <?php esc_html_e('Enable test mode (use Stripe test API keys)', 'subscription-system'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('When test mode is active, use your Stripe test API keys. When disabled, use your live API keys.', 'subscription-system'); ?>
                    </p>
                    <p>
                        <button type="button" id="toggle-mode" class="button">
                            <?php echo $stripe_test_mode ? esc_html__('Switch to Live Mode', 'subscription-system') : esc_html__('Switch to Test Mode', 'subscription-system'); ?>
                        </button>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Publishable Key', 'subscription-system'); ?></th>
                <td>
                    <input type="text" name="stripe_publishable_key" id="stripe_publishable_key" value="<?php echo esc_attr($stripe_publishable_key); ?>" class="regular-text">
                    <p class="description"><?php esc_html_e('Enter your Stripe Publishable Key. You can find this in your Stripe Dashboard.', 'subscription-system'); ?></p>
                    <p class="description key-prefix">
                        <?php echo $stripe_test_mode ? 
                            esc_html__('Test mode keys start with <code>pk_test_</code>', 'subscription-system') : 
                            esc_html__('Live mode keys start with <code>pk_live_</code>', 'subscription-system'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Secret Key', 'subscription-system'); ?></th>
                <td>
                    <input type="password" name="stripe_secret_key" id="stripe_secret_key" value="<?php echo esc_attr($stripe_secret_key); ?>" class="regular-text">
                    <p class="description"><?php esc_html_e('Enter your Stripe Secret Key. You can find this in your Stripe Dashboard.', 'subscription-system'); ?></p>
                    <p class="description key-prefix">
                        <?php echo $stripe_test_mode ? 
                            esc_html__('Test mode keys start with <code>sk_test_</code>', 'subscription-system') : 
                            esc_html__('Live mode keys start with <code>sk_live_</code>', 'subscription-system'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Webhook Secret', 'subscription-system'); ?></th>
                <td>
                    <input type="text" name="stripe_webhook_secret" id="stripe_webhook_secret" value="<?php echo esc_attr($stripe_webhook_secret); ?>" class="regular-text">
                    <p class="description"><?php esc_html_e('Enter your Stripe Webhook Secret. You can find this in your Stripe Dashboard.', 'subscription-system'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Test Connection', 'subscription-system'); ?></th>
                <td>
                    <button type="button" id="test-stripe-connection" class="button"><?php esc_html_e('Test Connection', 'subscription-system'); ?></button>
                    <span id="stripe-connection-result"></span>
                    <p class="description"><?php esc_html_e('Click to test your Stripe API connection.', 'subscription-system'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('API Key Status', 'subscription-system'); ?></th>
                <td>
                    <button type="button" id="check-api-key" class="button"><?php esc_html_e('Check API Key', 'subscription-system'); ?></button>
                    <span id="api-key-result"></span>
                    <p class="description"><?php esc_html_e('Click to check if the API key is correctly saved in the database.', 'subscription-system'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Debug Mode', 'subscription-system'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="debug_mode" value="1" <?php checked($debug_mode, 1); ?>>
                        <?php esc_html_e('Enable debug mode (logs detailed information for troubleshooting)', 'subscription-system'); ?>
                    </label>
                </td>
            </tr>
        </table>
        
        <h2><?php esc_html_e('Checkout Page', 'subscription-system'); ?></h2>
        <table class="form-table">
            <tr>
                <th scope="row"><?php esc_html_e('Checkout Page', 'subscription-system'); ?></th>
                <td>
                    <?php 
                    wp_dropdown_pages(array(
                        'name' => 'checkout_page',
                        'selected' => esc_attr($checkout_page),
                        'show_option_none' => esc_html__('Select a page', 'subscription-system'),
                    ));
                    ?>
                    <p class="description"><?php esc_html_e('Select the page where users will complete their subscription purchase. This page should contain the [subscription_checkout] shortcode.', 'subscription-system'); ?></p>
                    
                    <?php if ($checkout_page > 0): ?>
                    <p>
                        <a href="<?php echo esc_url(get_permalink($checkout_page)); ?>" target="_blank" class="button"><?php esc_html_e('View Checkout Page', 'subscription-system'); ?></a>
                        <a href="<?php echo esc_url(admin_url('post.php?post=' . $checkout_page . '&action=edit')); ?>" class="button"><?php esc_html_e('Edit Checkout Page', 'subscription-system'); ?></a>
                    </p>
                    <?php else: ?>
                    <p>
                        <a href="<?php echo esc_url(admin_url('post-new.php?post_type=page&checkout_page=1')); ?>" class="button"><?php esc_html_e('Create Checkout Page', 'subscription-system'); ?></a>
                    </p>
                    <?php endif; ?>
                </td>
            </tr>
        </table>
    
        <?php submit_button(esc_html__('Save Settings', 'subscription-system')); ?>
    </form> 
    
    <div class="stripe-integration-guide">
        <h2><?php esc_html_e('Stripe Integration Guide', 'subscription-system'); ?></h2>
        <div class="card">
            <h3><?php esc_html_e('Setting Up Stripe', 'subscription-system'); ?></h3>
            <ol>
                <li><?php esc_html_e('Create a <a href="https://dashboard.stripe.com/register" target="_blank">Stripe account</a> if you don\'t have one.', 'subscription-system'); ?></li>
                <li><?php esc_html_e('Get your API keys from the <a href="https://dashboard.stripe.com/apikeys" target="_blank">Stripe Dashboard</a>.', 'subscription-system'); ?></li>
                <li><?php esc_html_e('For testing, use the test mode keys that start with "pk_test_" and "sk_test_".', 'subscription-system'); ?></li>
                <li><?php esc_html_e('For production, use the live mode keys that start with "pk_live_" and "sk_live_".', 'subscription-system'); ?></li>
                <li><?php esc_html_e('Set up a webhook in your <a href="https://dashboard.stripe.com/webhooks" target="_blank">Stripe Dashboard</a> pointing to:', 'subscription-system'); ?> <code><?php echo esc_url(site_url('/wp-json/subscription-system/v1/webhook')); ?></code></li>
            </ol>
            
            <h3><?php esc_html_e('Testing Stripe Payments', 'subscription-system'); ?></h3>
            <p><?php esc_html_e('When in test mode, you can use the following test card numbers:', 'subscription-system'); ?></p>
            <ul>
                <li><strong>4242 4242 4242 4242</strong> - <?php esc_html_e('Successful payment', 'subscription-system'); ?></li>
                <li><strong>4000 0000 0000 0002</strong> - <?php esc_html_e('Declined payment (generic decline)', 'subscription-system'); ?></li>
                <li><strong>4000 0025 0000 3155</strong> - <?php esc_html_e('Requires 3D Secure authentication', 'subscription-system'); ?></li>
            </ul>
            <p><?php esc_html_e('For more test cards, see the <a href="https://stripe.com/docs/testing" target="_blank">Stripe testing documentation</a>.', 'subscription-system'); ?></p>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Store the original keys
    var testPublishableKey = '<?php echo esc_js(get_option('subscription_stripe_test_publishable_key', '')); ?>';
    var testSecretKey = '<?php echo esc_js(get_option('subscription_stripe_test_secret_key', '')); ?>';
    var testWebhookSecret = '<?php echo esc_js(get_option('subscription_stripe_test_webhook_secret', '')); ?>';
    
    var livePublishableKey = '<?php echo esc_js(get_option('subscription_stripe_live_publishable_key', '')); ?>';
    var liveSecretKey = '<?php echo esc_js(get_option('subscription_stripe_live_secret_key', '')); ?>';
    var liveWebhookSecret = '<?php echo esc_js(get_option('subscription_stripe_live_webhook_secret', '')); ?>';
    
    // Toggle mode button
    $('#toggle-mode').on('click', function() {
        var isTestMode = $('#stripe_test_mode').prop('checked');
        
        // Save current values before switching
        if (isTestMode) {
            testPublishableKey = $('#stripe_publishable_key').val();
            testSecretKey = $('#stripe_secret_key').val();
            testWebhookSecret = $('#stripe_webhook_secret').val();
            
            // Switch to live mode
            $('#stripe_test_mode').prop('checked', false);
            $('#stripe_publishable_key').val(livePublishableKey);
            $('#stripe_secret_key').val(liveSecretKey);
            $('#stripe_webhook_secret').val(liveWebhookSecret);
            $(this).text('<?php echo esc_js(__('Switch to Test Mode', 'subscription-system')); ?>');
            $('.key-prefix').text('<?php echo esc_js(__('Live mode keys start with pk_live_', 'subscription-system')); ?>');
        } else {
            livePublishableKey = $('#stripe_publishable_key').val();
            liveSecretKey = $('#stripe_secret_key').val();
            liveWebhookSecret = $('#stripe_webhook_secret').val();
            
            // Switch to test mode
            $('#stripe_test_mode').prop('checked', true);
            $('#stripe_publishable_key').val(testPublishableKey);
            $('#stripe_secret_key').val(testSecretKey);
            $('#stripe_webhook_secret').val(testWebhookSecret);
            $(this).text('<?php echo esc_js(__('Switch to Live Mode', 'subscription-system')); ?>');
            $('.key-prefix').text('<?php echo esc_js(__('Test mode keys start with pk_test_', 'subscription-system')); ?>');
        }
    });
    
    // Test mode checkbox change
    $('#stripe_test_mode').on('change', function() {
        var isTestMode = $(this).prop('checked');
        
        // Update the toggle button text
        if (isTestMode) {
            $('#toggle-mode').text('<?php echo esc_js(__('Switch to Live Mode', 'subscription-system')); ?>');
            $('.key-prefix').text('<?php echo esc_js(__('Test mode keys start with pk_test_', 'subscription-system')); ?>');
        } else {
            $('#toggle-mode').text('<?php echo esc_js(__('Switch to Test Mode', 'subscription-system')); ?>');
            $('.key-prefix').text('<?php echo esc_js(__('Live mode keys start with pk_live_', 'subscription-system')); ?>');
        }
    });
    
    // Test Stripe connection
    $('#test-stripe-connection').on('click', function() {
        var $button = $(this);
        var $result = $('#stripe-connection-result');
        
        $button.prop('disabled', true);
        $result.html('<?php esc_html_e('Testing connection...', 'subscription-system'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'test_stripe_connection',
                nonce: '<?php echo esc_attr(wp_create_nonce('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;"><?php esc_html_e('Error testing connection.', 'subscription-system'); ?></span>');
            },
            complete: function() {
                $button.prop('disabled', false);
            }
        });
    });
    
    // Check API key
    $('#check-api-key').on('click', function() {
        var $button = $(this);
        var $result = $('#api-key-result');
        
        $button.prop('disabled', true);
        $result.html('<?php esc_html_e('Checking API key...', 'subscription-system'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'check_stripe_api_key',
                nonce: '<?php echo esc_attr(wp_create_nonce('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;"><?php esc_html_e('Error checking API key.', 'subscription-system'); ?></span>');
            },
            complete: function() {
                $button.prop('disabled', false);
            }
        });
    });
});
</script>

<style>
.stripe-integration-guide {
    margin-top: 30px;
}
.stripe-integration-guide .card {
    background: #fff;
    border: 1px solid #ccd0d4;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
    padding: 15px 20px;
    margin-top: 10px;
}
.stripe-integration-guide h3 {
    margin-top: 0;
}
.stripe-integration-guide ul, 
.stripe-integration-guide ol {
    margin-left: 20px;
}
.stripe-integration-guide code {
    background: #f0f0f1;
    padding: 3px 5px;
    border-radius: 3px;
}
.notice.inline {
    margin: 15px 0;
    padding: 5px 12px;
}
.key-prefix {
    font-style: italic;
    margin-top: 5px !important;
}
</style>
 