<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit();
}

function migrate_paychef_settings() {
    // Überprüfen, ob die Migration bereits durchgeführt wurde
    if (get_option('paychef_migration_completed')) {
        return;
    }

    $old_settings = get_option('woocommerce_paychef_settings', array());

    if (!is_array($old_settings)) {
        return;
    }

    $mapping = array(
        'instance' => 'instance',
        'sid' => 'api_key',
        'prefix' => 'prefix',
        'save_cards' => 'save_cards',
        'lookAndFeelId' => 'look_and_feel_id'
    );

    foreach ($mapping as $old_key => $new_key) {
        $new_option_name = PAYCHEF_CONFIGS_PREFIX . $new_key;
        $value = isset($old_settings[$old_key]) ? $old_settings[$old_key] : '';

        if (!empty($value) || get_option($new_option_name) === false) {
            update_option($new_option_name, $value);
        }
    }

    // Setzen Sie die Plattform standardmäßig auf 'paychef.com'
    update_option(PAYCHEF_CONFIGS_PREFIX . 'platform', 'paychef.com');

    // Migrieren Sie die Logos als separate Option
    if (isset($old_settings['logos']) && is_array($old_settings['logos'])) {
        update_option(PAYCHEF_CONFIGS_PREFIX . 'logos', $old_settings['logos']);
    }

    // Markieren Sie die Migration als abgeschlossen
    update_option('paychef_migration_completed', true);
}

// Führen Sie diese Funktion nur beim Plugin-Aktivieren aus
register_activation_hook(PAYCHEF_MAIN_FILE, 'migrate_paychef_settings');

add_action('wp_ajax_paychef_delete_token', 'paychef_delete_token_ajax');

function paychef_delete_token_ajax() {
    // Verify nonce
    if (!isset($_POST['security']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'paychef_delete_token_nonce')) {
        wp_send_json_error('Invalid security token');
    }

    // Check user permissions
    if (!current_user_can('edit_user', get_current_user_id())) {
        wp_send_json_error('Permission denied');
    }

    $token_id = isset($_POST['token_id']) ? absint($_POST['token_id']) : 0;
    $token = WC_Payment_Tokens::get($token_id);

    // Verify token ownership
    if ($token && $token->get_user_id() === get_current_user_id()) {
        $deleted = $token->delete();
        if ($deleted) {
            wp_send_json_success('Token deleted successfully');
        } else {
            wp_send_json_error('Failed to delete token');
        }
    } else {
        wp_send_json_error('Invalid token');
    }
}

