<?php
// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class WC_Saved_Payment_Token_Removal_System {
    
    private static $instance = null;
    
    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new WC_Saved_Payment_Token_Removal_System();
        }
        return self::$instance;
    }
    
    public function __construct() {
        add_action('init', array($this, 'init'));
    }
    
    public function init() {
        // Check if WooCommerce is active
        if (!class_exists('WooCommerce')) {
            add_action('admin_notices', array($this, 'woocommerce_missing_notice'));
            return;
        }
        
        // Add AJAX handlers
        add_action('wp_ajax_remove_payment_token', array($this, 'ajax_remove_payment_token'));
        
        // Add WP-CLI command
        if (defined('WP_CLI') && WP_CLI) {
            WP_CLI::add_command('wc-token remove', array($this, 'cli_remove_token'));
        }
        
        // Enqueue admin scripts
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    }
    
    public function woocommerce_missing_notice() {
        echo '<div class="error"><p>WooCommerce Token Removal System requires WooCommerce to be installed and activated.</p></div>';
    }

    public function enqueue_admin_scripts($hook) {
        if ($hook !== 'woocommerce_page_wc-settings' || $_REQUEST['opt'] != 'Remove Token' ) {
            return;
        }
        
        wp_enqueue_script(
            'wc-token-removal-admin',
            TOTALPROCESSING_PAYMENTGATEWAY_PLUGIN_BASEURL . 'assets/js/admin.js',
            array('jquery'),
            '1.0.2',
            true
        );
        
        wp_localize_script('wc-token-removal-admin', 'wcTokenRemoval', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('wc_token_removal_nonce'),
            'confirm_text' => 'Are you sure you want to remove this payment token? This action cannot be undone.'
        ));
        
        wp_enqueue_style(
            'wc-token-removal-admin',
            TOTALPROCESSING_PAYMENTGATEWAY_PLUGIN_BASEURL . 'assets/css/admin.css',
            array(),
            '1.0.1'
        );
    }
    
    public function admin_page() {
        ob_start();
        ?>
        <div class="wrap">
            
            <div class="card w-100">
                <h2>Remove Payment Token</h2>
                <p><strong>Warning:</strong> This tool permanently removes saved payment tokens. Use with caution.</p>
                <div id="token-removal-form">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="customer_email">Customer Email</label>
                            </th>
                            <td>
                                <input type="email" id="customer_email" name="customer_email" class="regular-text search-tp-saved-token-avoidenterpress" required>
                                <p class="description">Enter the customer's email address</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="card_last_four">Last 4 Digits</label>
                            </th>
                            <td>
                                <input type="text" id="card_last_four" name="card_last_four" class="regular-text search-tp-saved-token-avoidenterpress" pattern="[0-9]{4}" maxlength="4" required>
                                <p class="description">Enter the last 4 digits of the card to be removed</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="issuing_bank">Issuing Bank (Optional)</label>
                            </th>
                            <td>
                                <input type="text" id="issuing_bank" name="issuing_bank" class="regular-text search-tp-saved-token-avoidenterpress">
                                <p class="description">Enter the issuing bank for additional verification</p>
                            </td>
                        </tr>
                    </table>
                    
                    <p class="token-submit">
                        <input type="button" id="search-tp-saved-token" class="button-primary" value="Search Tokens">
                    </p>
                </div>
            </div>
            
            <div id="search-results" style="display: none;">
                <div class="card w-100">
                    <h2>Found Tokens</h2>
                    <div id="tokens-list"></div>
                </div>
            </div>
            
            <div id="removal-log" style="display: none;">
                <div class="card w-100">
                    <h2>Removal Log</h2>
                    <div id="log-content"></div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
    
    public function ajax_remove_payment_token() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'wc_token_removal_nonce')) {
            wp_die('Security check failed');
        }
        
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_die('Insufficient permissions');
        }
        
        $action = sanitize_text_field($_POST['action_type']);
        $customer_email = sanitize_email($_POST['customer_email']);
        $card_last_four = sanitize_text_field($_POST['card_last_four']);
        $issuing_bank = sanitize_text_field($_POST['issuing_bank']);
        
        // Validate inputs
        if (!is_email($customer_email)) {
            wp_send_json_error('Invalid email address');
        }
        
        if (!preg_match('/^\d{4}$/', $card_last_four)) {
            wp_send_json_error('Last 4 digits must be exactly 4 numbers');
        }
        
        if ($action === 'search') {
            $tokens = $this->find_payment_tokens($customer_email, $card_last_four, $issuing_bank);
            wp_send_json_success($tokens);
        } elseif ($action === 'remove') {
            $token_id = intval($_POST['token_id']);
            $result = $this->remove_payment_token($token_id, $customer_email, $card_last_four);
            
            if ($result['success']) {
                wp_send_json_success($result['message']);
            } else {
                wp_send_json_error($result['message']);
            }
        }
    }
    
    public function find_payment_tokens($customer_email, $card_last_four, $issuing_bank = '') {
        global $wpdb;
        
        // Get customer by email
        $customer = get_user_by('email', $customer_email);
        if (!$customer) {
            return array('error' => 'Customer not found');
        }
        
        // Get all payment tokens for this customer
        $tokens = WC_Payment_Tokens::get_customer_tokens($customer->ID);
        $matching_tokens = array();
        
        // Get available payment gateways
        $payment_gateways = WC()->payment_gateways()->get_available_payment_gateways();
        
        foreach ($tokens as $token) {
            $token_data = $token->get_data();
            
            // Check if last 4 digits match
            if (isset($token_data['last4']) && $token_data['last4'] === $card_last_four) {
                $gateway_id = $token->get_gateway_id();
                $gateway_title = $gateway_id; // fallback to ID if title not found
                
                // Get gateway title/name
                if (isset($payment_gateways[$gateway_id])) {
                    $gateway_title = $payment_gateways[$gateway_id]->get_title();
                } else {
                    // Try to get from all gateways (including disabled ones)
                    $all_gateways = WC()->payment_gateways()->payment_gateways();
                    if (isset($all_gateways[$gateway_id])) {
                        $gateway_title = $all_gateways[$gateway_id]->get_title();
                    } else {
                        // Format gateway ID as title if not found
                        $gateway_title = ucwords(str_replace('_', ' ', $gateway_id));
                    }
                }
                
                $token_info = array(
                    'token_id' => $token->get_id(),
                    'token_type' => $token->get_type(),
                    'last4' => $token_data['last4'],
                    'expiry_month' => $token_data['expiry_month'] ?? '',
                    'expiry_year' => $token_data['expiry_year'] ?? '',
                    'card_type' => $token_data['card_type'] ?? '',
                    'gateway_id' => $gateway_id,
                    'gateway_title' => $gateway_title,
                    'created_date' => $token_data['created'] ?? '',
                    'customer_id' => $customer->ID,
                    'customer_email' => $customer_email
                );
                
                // Additional verification with issuing bank if provided
                if (!empty($issuing_bank)) {
                    // This would need to be customized based on your gateway's token structure
                    // For now, we'll include all matching tokens
                }
                
                $matching_tokens[] = $token_info;
            }
        }
        
        return array(
            'tokens' => $matching_tokens,
            'customer_id' => $customer->ID,
            'customer_email' => $customer_email
        );
    }
    
    public function remove_payment_token($token_id, $customer_email, $card_last_four) {
        try {
            // Get the token
            $token = WC_Payment_Tokens::get($token_id);
            
            if (!$token) {
                return array('success' => false, 'message' => 'Token not found');
            }
            
            // Verify the token belongs to the correct customer
            $customer = get_user_by('email', $customer_email);
            if (!$customer || $token->get_user_id() !== $customer->ID) {
                return array('success' => false, 'message' => 'Token does not belong to specified customer');
            }
            
            // Additional verification - check last 4 digits
            $token_data = $token->get_data();
            if (!isset($token_data['last4']) || $token_data['last4'] !== $card_last_four) {
                return array('success' => false, 'message' => 'Last 4 digits do not match');
            }
            
            // Log the removal action
            $this->log_token_removal($token_id, $customer_email, $card_last_four, wp_get_current_user());
            
            // Remove the token
            $result = WC_Payment_Tokens::delete($token_id);
            
            if ( is_null( $result ) ) {
                return array(
                    'success' => true, 
                    'message' => sprintf('Token %d removed successfully for customer %s', $token_id, $customer_email)
                );
            } else {
                return array('success' => false, 'message' => 'Failed to remove token');
            }
            
        } catch (Exception $e) {
            return array('success' => false, 'message' => 'Error: ' . $e->getMessage());
        }
    }
    
    public function log_token_removal($token_id, $customer_email, $card_last_four, $admin_user) {
        $log_entry = array(
            'timestamp' => current_time('mysql'),
            'token_id' => $token_id,
            'customer_email' => $customer_email,
            'card_last_four' => $card_last_four,
            'admin_user' => $admin_user->user_login,
            'admin_email' => $admin_user->user_email,
            'ip_address' => $this->get_client_ip()
        );
        
        // Log to WordPress
        error_log('WC Token Removal: ' . json_encode($log_entry));
        
        // Optionally store in custom table or meta
        update_option('wc_token_removal_log_' . time(), $log_entry);
    }
    
    private function get_client_ip() {
        $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR');
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
    
    /**
     * WP-CLI Command for token removal
     */
    public function cli_remove_token($args, $assoc_args) {
        if (empty($assoc_args['email']) || empty($assoc_args['last4'])) {
            WP_CLI::error('Required parameters: --email and --last4');
        }
        
        $customer_email = sanitize_email($assoc_args['email']);
        $card_last_four = sanitize_text_field($assoc_args['last4']);
        $issuing_bank = isset($assoc_args['bank']) ? sanitize_text_field($assoc_args['bank']) : '';
        $confirm = isset($assoc_args['confirm']) ? $assoc_args['confirm'] : false;
        
        // Validate inputs
        if (!is_email($customer_email)) {
            WP_CLI::error('Invalid email address');
        }
        
        if (!preg_match('/^\d{4}$/', $card_last_four)) {
            WP_CLI::error('Last 4 digits must be exactly 4 numbers');
        }
        
        // Find tokens
        $tokens_result = $this->find_payment_tokens($customer_email, $card_last_four, $issuing_bank);
        
        if (isset($tokens_result['error'])) {
            WP_CLI::error($tokens_result['error']);
        }
        
        if (empty($tokens_result['tokens'])) {
            WP_CLI::warning('No matching tokens found');
            return;
        }
        
        // Display found tokens
        WP_CLI::line('Found ' . count($tokens_result['tokens']) . ' matching token(s):');
        
        foreach ($tokens_result['tokens'] as $token) {
            WP_CLI::line(sprintf(
                'Token ID: %d, Type: %s, Last4: %s, Gateway: %s, Created: %s',
                $token['token_id'],
                $token['token_type'],
                $token['last4'],
                $token['gateway_title'],
                $token['created_date']
            ));
        }
        
        // Confirm removal
        if (!$confirm) {
            WP_CLI::line('Add --confirm=true to proceed with removal');
            return;
        }
        
        // Remove tokens
        $removed_count = 0;
        foreach ($tokens_result['tokens'] as $token) {
            $result = $this->remove_payment_token($token['token_id'], $customer_email, $card_last_four);
            
            if ($result['success']) {
                WP_CLI::success($result['message']);
                $removed_count++;
            } else {
                WP_CLI::error($result['message']);
            }
        }
        
        WP_CLI::success(sprintf('Removed %d token(s) successfully', $removed_count));
    }
}

