<?php
/**
 * VMPFence WooCommerce Integration
 * 
 * Adds 2FA prompts and reCAPTCHA support to WooCommerce login and registration forms
 * when the WooCommerce integration setting is enabled.
 * 
 * @package VMPFence
 * @since 2.1.0
 */

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

class VMPFence_WooCommerce_Integration {
    
    /**
     * Initialize the WooCommerce integration
     */
    public static function init() {
        // Only proceed if WooCommerce integration is enabled
        if (!self::is_enabled()) {
            return;
        }
        
        // Check if WooCommerce is active
        if (!self::is_woocommerce_active()) {
            return;
        }
        
        // Add hooks for WooCommerce forms
        add_action('woocommerce_login_form', array(__CLASS__, 'add_recaptcha_to_login'), 10);
        add_action('woocommerce_register_form', array(__CLASS__, 'add_recaptcha_to_register'), 10);
        
        // Add 2FA check to WooCommerce login process
        add_filter('woocommerce_process_login_errors', array(__CLASS__, 'check_2fa_on_login'), 10, 3);
        
        // Add reCAPTCHA verification
        add_filter('woocommerce_process_login_errors', array(__CLASS__, 'verify_recaptcha_on_login'), 5, 3);
        add_filter('woocommerce_process_registration_errors', array(__CLASS__, 'verify_recaptcha_on_register'), 5, 4);
    }
    
    /**
     * Check if WooCommerce integration is enabled
     */
    private static function is_enabled() {
        return VMPFence_Config::get('vmpfence_woocommerce_integration', false);
    }
    
    /**
     * Check if WooCommerce is active
     */
    private static function is_woocommerce_active() {
        return class_exists('WooCommerce');
    }
    
    /**
     * Add reCAPTCHA to WooCommerce login form
     */
    public static function add_recaptcha_to_login() {
        // Check if reCAPTCHA is enabled (Phase 6 setting)
        $recaptcha_enabled = VMPFence_Config::get('vmpfence_recaptcha_enabled', false);
        
        if (!$recaptcha_enabled) {
            return;
        }
        
        $site_key = VMPFence_Config::get('vmpfence_recaptcha_site_key', '');
        
        if (empty($site_key)) {
            return;
        }
        
        echo '<div class="vmpfence-recaptcha-container" style="margin: 10px 0;">';
        echo '<div class="g-recaptcha" data-sitekey="' . esc_attr($site_key) . '"></div>';
        echo '</div>';
    }
    
    /**
     * Add reCAPTCHA to WooCommerce registration form
     */
    public static function add_recaptcha_to_register() {
        // Same as login
        self::add_recaptcha_to_login();
    }
    
    /**
     * Verify reCAPTCHA on WooCommerce login
     */
    public static function verify_recaptcha_on_login($validation_error, $username, $password) {
        // Check if reCAPTCHA is enabled
        $recaptcha_enabled = VMPFence_Config::get('vmpfence_recaptcha_enabled', false);
        
        if (!$recaptcha_enabled) {
            return $validation_error;
        }
        
        $secret_key = VMPFence_Config::get('vmpfence_recaptcha_secret_key', '');
        
        if (empty($secret_key)) {
            return $validation_error;
        }
        
        // Get reCAPTCHA response
        $recaptcha_response = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : '';
        
        if (empty($recaptcha_response)) {
            return new WP_Error('recaptcha_missing', __('Please complete the reCAPTCHA verification.', 'vmpfence-security'));
        }
        
        // Verify with Google
        $response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', array(
            'body' => array(
                'secret' => $secret_key,
                'response' => $recaptcha_response,
                'remoteip' => $_SERVER['REMOTE_ADDR']
            )
        ));
        
        if (is_wp_error($response)) {
            return new WP_Error('recaptcha_error', __('reCAPTCHA verification failed. Please try again.', 'vmpfence-security'));
        }
        
        $response_body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (!isset($response_body['success']) || !$response_body['success']) {
            return new WP_Error('recaptcha_invalid', __('reCAPTCHA verification failed. Please try again.', 'vmpfence-security'));
        }
        
        return $validation_error;
    }
    
    /**
     * Verify reCAPTCHA on WooCommerce registration
     */
    public static function verify_recaptcha_on_register($validation_error, $username, $password, $email) {
        // Same verification as login
        $result = self::verify_recaptcha_on_login($validation_error, $username, $password);
        
        // If result is WP_Error, return it
        if (is_wp_error($result)) {
            return $result;
        }
        
        return $validation_error;
    }
    
    /**
     * Check 2FA on WooCommerce login
     */
    public static function check_2fa_on_login($validation_error, $username, $password) {
        // If there's already an error, return it
        if (is_wp_error($validation_error) && $validation_error->get_error_code()) {
            return $validation_error;
        }
        
        // Get user by username or email
        $user = get_user_by('login', $username);
        if (!$user) {
            $user = get_user_by('email', $username);
        }
        
        if (!$user) {
            // User not found, let WooCommerce handle it
            return $validation_error;
        }
        
        // Check if user has 2FA enabled via API
        $api_key = VMPFence_Config::get('central_api_key');
        
        if (empty($api_key)) {
            // No API key configured, skip 2FA check
            return $validation_error;
        }
        
        $api_client = new VMPFence_API_Client();
        $status = $api_client->get_2fa_status($api_key, $user->ID);
        
        if (is_wp_error($status)) {
            // API error, log it but don't block login
            VMPFence_Secure_Logger::error('WooCommerce 2FA Check Failed', array(
                'error' => $status->get_error_message(),
                'user_id' => $user->ID
            ));
            return $validation_error;
        }
        
        // If 2FA is not enabled for this user, allow login
        if (!isset($status['enabled']) || !$status['enabled']) {
            return $validation_error;
        }
        
        // Check if device is remembered
        if (self::is_device_remembered($user->ID)) {
            return $validation_error;
        }
        
        // TODO: Implement complete 2FA verification flow for WooCommerce
        // Currently this stores session data but lacks the redirect handler and verification page.
        // For now, allow login and let the forced 2FA enforcement handle it if needed.
        // Future enhancement: Create dedicated WooCommerce 2FA verification page.
        
        /* INCOMPLETE IMPLEMENTATION - COMMENTED OUT
        // 2FA is required - store user data in session and redirect
        if (!isset($_SESSION)) {
            @session_start();
        }
        
        $_SESSION['vmpfence_wc_2fa_user_id'] = $user->ID;
        $_SESSION['vmpfence_wc_2fa_redirect'] = wc_get_page_permalink('myaccount');
        
        // Return error with redirect instruction
        return new WP_Error('2fa_required', __('Two-Factor Authentication required. Redirecting...', 'vmpfence-security'));
        */
        
        // Allow login for now - rely on forced 2FA enforcement if applicable
        return $validation_error;
    }
    
    /**
     * Check if device is remembered for this user
     */
    private static function is_device_remembered($user_id) {
        // Check if remember device is enabled
        $remember_enabled = VMPFence_Config::get('vmpfence_2fa_remember_device', false);
        
        if (!$remember_enabled) {
            return false;
        }
        
        // Check for remember device cookie
        $cookie_name = 'vmpfence_remember_device_' . $user_id;
        
        if (!isset($_COOKIE[$cookie_name])) {
            return false;
        }
        
        $token = $_COOKIE[$cookie_name];
        
        // Verify token against user meta
        $stored_tokens = get_user_meta($user_id, 'vmpfence_remembered_devices', true);
        
        if (!is_array($stored_tokens)) {
            return false;
        }
        
        // Check if token exists and is not expired
        foreach ($stored_tokens as $stored_token) {
            if ($stored_token['token'] === $token && $stored_token['expires'] > time()) {
                return true;
            }
        }
        
        return false;
    }
}

// Initialize on plugins_loaded
add_action('plugins_loaded', array('VMPFence_WooCommerce_Integration', 'init'), 20);
