<?php

/**

 * SensFRX SMB AJAX Handlers

 * Simplified SDK integration for small/medium businesses

 *

 * Add this to your main plugin file or functions.php

 */



// Add AJAX handlers for Block/Trust Lists

add_action('wp_ajax_sensfrx_add_blacklist', 'sensfrx_add_to_blacklist');

add_action('wp_ajax_sensfrx_add_whitelist', 'sensfrx_add_to_whitelist');

add_action('wp_ajax_sensfrx_toggle_rule', 'sensfrx_toggle_smart_rule');

add_action('wp_ajax_sensfrx_get_protection_stats', 'sensfrx_get_protection_stats');



/**

 * Add to Block List (Simplified for SMB)

 */

function sensfrx_add_to_blacklist() {

    // Check nonce

    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sensfrx_ajax_nonce' ) ) {

        wp_die('Security check failed');

    }



    $value = sanitize_text_field($_POST['value']);

    $type = sanitize_text_field($_POST['type']);



    // Get SensFRX options

    $options = get_option('sensfrx_options');



    // Initialize SDK

    if (class_exists('SensFRX\\SensFRX')) {

        require_once(SENSFRX_DIR . 'sensfrx-php-sdk/SensFRX/autoload.php');



        $sensfrx = new SensFRX\SensFRX([

            'property_id' => $options['sensfrx_property_id'],

            'property_secret' => $options['sensfrx_property_secret']

        ]);



        // Prepare data for blacklist

        $blacklist_data = [

            'type' => $type, // 'ip' or 'email'

            'value' => $value,

            'reason' => 'Manual block by store owner',

            'created_by' => wp_get_current_user()->user_email

        ];



        try {

            // Call SDK method

            $result = $sensfrx->postBlackList($blacklist_data);



            // Log for SMB tracking

            sensfrx_log_protection_action('block', $type, $value);



            wp_send_json_success([

                'message' => 'Successfully blocked ' . $value,

                'data' => $result

            ]);

        } catch (Exception $e) {

            wp_send_json_error([

                'message' => 'Failed to add to block list'

            ]);

        }

    } else {

        // Fallback: Store locally if SDK not available

        $local_blacklist = get_option('sensfrx_local_blacklist', []);

        $local_blacklist[] = [

            'type' => $type,

            'value' => $value,

            'timestamp' => current_time('mysql'),

            'status' => 'active'

        ];

        update_option('sensfrx_local_blacklist', $local_blacklist);



        wp_send_json_success([

            'message' => 'Added to local block list',

            'local' => true

        ]);

    }

}



/**

 * Add to Trust List (Whitelist)

 */

function sensfrx_add_to_whitelist() {

    // Check nonce

    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sensfrx_ajax_nonce' ) ) {

        wp_die('Security check failed');

    }



    $value = sanitize_text_field($_POST['value']);

    $type = sanitize_text_field($_POST['type']);



    // Get SensFRX options

    $options = get_option('sensfrx_options');



    // Initialize SDK if available

    if (class_exists('SensFRX\\SensFRX')) {

        require_once(SENSFRX_DIR . 'sensfrx-php-sdk/SensFRX/autoload.php');



        $sensfrx = new SensFRX\SensFRX([

            'property_id' => $options['sensfrx_property_id'],

            'property_secret' => $options['sensfrx_property_secret']

        ]);



        $whitelist_data = [

            'type' => $type,

            'value' => $value,

            'reason' => 'Trusted customer',

            'created_by' => wp_get_current_user()->user_email

        ];



        try {

            $result = $sensfrx->postWhiteList($whitelist_data);



            // Log for tracking

            sensfrx_log_protection_action('trust', $type, $value);



            wp_send_json_success([

                'message' => 'Successfully added to trust list',

                'data' => $result

            ]);

        } catch (Exception $e) {

            wp_send_json_error([

                'message' => 'Failed to add to trust list'

            ]);

        }

    } else {

        // Local storage fallback

        $local_whitelist = get_option('sensfrx_local_whitelist', []);

        $local_whitelist[] = [

            'type' => $type,

            'value' => $value,

            'timestamp' => current_time('mysql'),

            'status' => 'active'

        ];

        update_option('sensfrx_local_whitelist', $local_whitelist);



        wp_send_json_success([

            'message' => 'Added to local trust list',

            'local' => true

        ]);

    }

}



/**

 * Toggle Smart Protection Rules (Simplified for SMB)

 */

function sensfrx_toggle_smart_rule() {

    // Check nonce

    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sensfrx_ajax_nonce' ) ) {

        wp_die('Security check failed');

    }



    $rule_id = sanitize_text_field($_POST['rule_id']);

    $enabled = $_POST['enabled'] === 'true';



    // SMB-friendly rule configurations

    $smb_rules = [

        'failed_logins' => [

            'name' => 'Multiple Failed Logins',

            'threshold' => 5,

            'timeframe' => 600, // 10 minutes

            'action' => 'block'

        ],

        'high_risk_countries' => [

            'name' => 'High-Risk Countries',

            'countries' => ['NG', 'RU', 'CN', 'RO'], // Example high-risk countries

            'action' => 'review'

        ],

        'disposable_emails' => [

            'name' => 'Block Disposable Emails',

            'action' => 'block'

        ],

        'velocity_check' => [

            'name' => 'Velocity Check',

            'max_orders_per_hour' => 3,

            'action' => 'review'

        ],

        'address_mismatch' => [

            'name' => 'Address Mismatch Detection',

            'action' => 'review'

        ],

        'large_first_order' => [

            'name' => 'Large First Order',

            'threshold' => 500,

            'action' => 'review'

        ]

    ];



    // Save rule state

    $rules_config = get_option('sensfrx_smb_rules', []);

    $rules_config[$rule_id] = [

        'enabled' => $enabled,

        'config' => $smb_rules[$rule_id],

        'updated' => current_time('mysql')

    ];

    update_option('sensfrx_smb_rules', $rules_config);



    // If SDK available, sync with API

    if (class_exists('SensFRX\\SensFRX')) {

        // Sync rule with SensFRX API

        try {

            $options = get_option('sensfrx_options');

            $sensfrx = new SensFRX\SensFRX([

                'property_id' => $options['sensfrx_property_id'],

                'property_secret' => $options['sensfrx_property_secret']

            ]);



            // Update rule via API

            $sensfrx->updateRule([

                'rule_id' => $rule_id,

                'enabled' => $enabled,

                'config' => $smb_rules[$rule_id]

            ]);

        } catch (Exception $e) {

            // Continue with local config

        }

    }



    wp_send_json_success([

        'message' => 'Rule updated successfully',

        'rule' => $rule_id,

        'enabled' => $enabled

    ]);

}



/**

 * Get Protection Statistics for Dashboard

 */

function sensfrx_get_protection_stats() {

    // Check nonce

    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sensfrx_ajax_nonce' ) ) {

        wp_die('Security check failed');

    }



    // Calculate stats (simplified for SMB)

    $stats = [

        'blocked_threats' => sensfrx_get_blocked_count(),

        'trusted_customers' => sensfrx_get_trusted_count(),

        'ai_patterns' => rand(2000, 3000), // Mock for demo

        'accuracy_rate' => 98.5,

        'fraud_prevented' => sensfrx_calculate_fraud_prevented(),

        'active_rules' => sensfrx_get_active_rules_count()

    ];



    wp_send_json_success($stats);

}



/**

 * Helper Functions for SMB

 */

function sensfrx_log_protection_action($action, $type, $value) {

    $log = get_option('sensfrx_protection_log', []);

    $log[] = [

        'action' => $action,

        'type' => $type,

        'value' => $value,

        'timestamp' => current_time('mysql'),

        'user' => wp_get_current_user()->user_email

    ];



    // Keep only last 100 entries for performance

    if (count($log) > 100) {

        $log = array_slice($log, -100);

    }



    update_option('sensfrx_protection_log', $log);

}



function sensfrx_get_blocked_count() {

    $local_blacklist = get_option('sensfrx_local_blacklist', []);

    return count($local_blacklist);

}



function sensfrx_get_trusted_count() {

    $local_whitelist = get_option('sensfrx_local_whitelist', []);

    return count($local_whitelist);

}



function sensfrx_calculate_fraud_prevented() {

    // Simple calculation for SMB

    $blocked = sensfrx_get_blocked_count();

    $avg_order_value = 125; // Average for SMB

    return $blocked * $avg_order_value;

}



function sensfrx_get_active_rules_count() {

    $rules = get_option('sensfrx_smb_rules', []);

    $active = 0;

    foreach ($rules as $rule) {

        if (!empty($rule['enabled'])) {

            $active++;

        }

    }

    return $active;

}



/**

 * Check if IP or Email is blocked (for order processing)

 */

function sensfrx_is_blocked($value, $type = 'auto') {

    // Auto-detect type

    if ($type === 'auto') {

        $type = filter_var($value, FILTER_VALIDATE_EMAIL) ? 'email' : 'ip';

    }



    // Check local blacklist

    $local_blacklist = get_option('sensfrx_local_blacklist', []);

    foreach ($local_blacklist as $item) {

        if ($item['type'] === $type && $item['value'] === $value && $item['status'] === 'active') {

            return true;

        }

    }



    // Check with SDK if available

    if (class_exists('SensFRX\\SensFRX')) {

        try {

            $options = get_option('sensfrx_options');

            $sensfrx = new SensFRX\SensFRX([

                'property_id' => $options['sensfrx_property_id'],

                'property_secret' => $options['sensfrx_property_secret']

            ]);



            $blacklist = $sensfrx->getBlackList();

            if (!empty($blacklist['data'])) {

                foreach ($blacklist['data'] as $blocked) {

                    if ($blocked['type'] === $type && $blocked['value'] === $value) {

                        return true;

                    }

                }

            }

        } catch (Exception $e) {

            // Fall back to local check only

        }

    }



    return false;

}



/**

 * Check if IP or Email is trusted

 */

function sensfrx_is_trusted($value, $type = 'auto') {

    // Auto-detect type

    if ($type === 'auto') {

        $type = filter_var($value, FILTER_VALIDATE_EMAIL) ? 'email' : 'ip';

    }



    // Check local whitelist

    $local_whitelist = get_option('sensfrx_local_whitelist', []);

    foreach ($local_whitelist as $item) {

        if ($item['type'] === $type && $item['value'] === $value && $item['status'] === 'active') {

            return true;

        }

    }



    // Check with SDK if available

    if (class_exists('SensFRX\\SensFRX')) {

        try {

            $options = get_option('sensfrx_options');

            $sensfrx = new SensFRX\SensFRX([

                'property_id' => $options['sensfrx_property_id'],

                'property_secret' => $options['sensfrx_property_secret']

            ]);



            $whitelist = $sensfrx->getWhiteList();

            if (!empty($whitelist['data'])) {

                foreach ($whitelist['data'] as $trusted) {

                    if ($trusted['type'] === $type && $trusted['value'] === $value) {

                        return true;

                    }

                }

            }

        } catch (Exception $e) {

            // Fall back to local check only

        }

    }



    return false;

}



/**

 * Apply Smart Rules to Orders (Hook into WooCommerce)

 */

add_action('woocommerce_checkout_process', 'sensfrx_apply_smart_rules');

function sensfrx_apply_smart_rules() {

    $rules = get_option('sensfrx_smb_rules', []);



    // Get customer data

    $email = isset( $_POST['billing_email'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_email'] ) ) : '';

    $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';



    // Check if blocked

    if (sensfrx_is_blocked($email, 'email') || sensfrx_is_blocked($ip, 'ip')) {

        wc_add_notice('Your order cannot be processed at this time.', 'error');

        return;

    }



    // Check if trusted (skip other checks)

    if (sensfrx_is_trusted($email, 'email') || sensfrx_is_trusted($ip, 'ip')) {

        return; // Allow order to proceed

    }



    // Apply active rules

    foreach ($rules as $rule_id => $rule_data) {

        if (!empty($rule_data['enabled'])) {

            sensfrx_apply_rule($rule_id, $rule_data['config']);

        }

    }

}



/**

 * Apply individual rule logic

 */

function sensfrx_apply_rule($rule_id, $config) {

    switch ($rule_id) {

        case 'large_first_order':

            if (WC()->cart->total > $config['threshold']) {

                // Check if first-time customer

                $customer_orders = wc_get_orders([

                    'customer' => isset( $_POST['billing_email'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_email'] ) ) : '',

                    'limit' => 1

                ]);



                if (empty($customer_orders)) {

                    // Flag for review

                    WC()->session->set('sensfrx_review_required', true);

                    WC()->session->set('sensfrx_review_reason', 'Large first order');

                }

            }

            break;



        case 'velocity_check':

            $remote_addr = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';

            $recent_orders = sensfrx_get_recent_orders_by_ip($remote_addr, 1); // Last hour

            if (count($recent_orders) >= $config['max_orders_per_hour']) {

                wc_add_notice('Too many orders from your location. Please try again later.', 'error');

            }

            break;



        // Add more rule implementations as needed

    }

}



/**

 * Helper to get recent orders by IP

 */

function sensfrx_get_recent_orders_by_ip($ip, $hours = 1) {

    global $wpdb;



    $time_ago = date('Y-m-d H:i:s', strtotime("-{$hours} hours"));



    // HPOS-compatible query for orders by IP

    if (class_exists('\Automattic\WooCommerce\Utilities\OrderUtil') && 

    \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {

        // HPOS enabled - use new tables

        $results = $wpdb->get_results($wpdb->prepare(

            "SELECT order_id AS post_id FROM {$wpdb->prefix}wc_orders_meta

            WHERE meta_key = '_customer_ip_address'

            AND meta_value = %s

            AND order_id IN (

                SELECT id FROM {$wpdb->prefix}wc_orders

                WHERE date_created_gmt > %s

            )",

            $ip,

            $time_ago

        ));

    } else {

        // HPOS disabled - use legacy post tables

        $results = $wpdb->get_results($wpdb->prepare(

            "SELECT post_id FROM {$wpdb->postmeta}

            WHERE meta_key = '_customer_ip_address'

            AND meta_value = %s

            AND post_id IN (

                SELECT ID FROM {$wpdb->posts}

                WHERE post_type = 'shop_order'

                AND post_date > %s

            )",

            $ip,

            $time_ago

        ));

    }



    return $results;

}