<?php
namespace WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers;

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Support\Validation\IpAddressValidator;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\IpHelper;
class AjaxAPI
{
    public static function register()
    {
        add_action('wp_ajax_ultimate_security_search_recent_ips', [self::class, 'ultimate_security_search_recent_ips']);
        add_action('wp_ajax_ultimate_security_ip_set', [self::class, 'ultimate_security_ip_set']);
        add_action('wp_ajax_ultimate_security_ip_validate', [self::class, 'ultimate_security_ip_validate']);
        add_action('wp_ajax_ultimate_security_shop_ip_reset', [self::class, 'ultimate_security_shop_ip_reset']);
        add_action('wp_ajax_ultimate_security_review_action', [self::class, 'handle_review_action']);
        add_action('wp_ajax_ultimate_security_deact_submit', [self::class, 'ultimate_security_deact_submit']);
        add_action('wp_ajax_ultimate_security_dismiss_passkey_notice', [self::class, 'ultimate_security_dismiss_passkey_notice']);
    }
    public static function ultimate_security_deact_submit() {
        if (!current_user_can('activate_plugins')) wp_send_json_error('forbidden', 403);
        check_ajax_referer('ultimate_security_deact_nonce');

        $reason  = isset($_POST['reason'])?sanitize_text_field(wp_unslash($_POST['reason'])):'';
        $notes   = isset($_POST['notes'])?wp_kses_post(wp_unslash($_POST['notes'])):'';
        $consent = !empty($_POST['consent']);
        // $email   = $consent ? sanitize_email(wp_get_current_user()->user_email) : null;
        $email = 'support@wpultimatesecurity.com';
        // $subject = sprintf(
        //     /* translators: %s = site URL */
        //     esc_html__('Error notification for %s', 'ultimate-security'),
        //     get_home_url()
        // );
        $output = '<strong>Reason:</strong> ' . $reason . '<br/><strong>Notes:</strong> ' . $notes;
        $headers = array(
            // 'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>',
            'Content-Type: text/html; charset=UTF-8'
        );

        // Add rate limiting
        $rate_limit_key = 'ultimate_security_feedback_' . get_current_user_id();
        if (get_transient($rate_limit_key)) {
            wp_send_json_error('Rate limit exceeded', 429);
        }
        set_transient($rate_limit_key, 1, 300);  // 5 minutes


        wp_mail($email, 'Deactivate reason of Ultimate Security Plugin', $output, $headers);
        wp_send_json_success(
            array(
                'message' => esc_html__('Deactivation feedback send successfully.', 'ultimate-security'),
                
            )
        );
    }

    public static function ultimate_security_ip_validate()
    {
        if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
            $ip = isset($_POST['ip']) ? sanitize_text_field(wp_unslash($_POST['ip'])) : '';

            // Use IpAddressValidator for comprehensive validation
            $validator = IpAddressValidator::create();
            $is_valid = $validator->validate($ip);

            if ($is_valid) {
                wp_send_json_success(array(
                    'message' => __('Valid IP address', 'ultimate-security'),
                    'is_valid' => true
                ));
            } else {
                $errors = $validator->getErrors();
                wp_send_json_error(array(
                    'message' => !empty($errors) ? $errors[0] : __('Invalid IP address format', 'ultimate-security'),
                    'is_valid' => false
                ));
            }
        } else {
            wp_send_json_error(array(
                'error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security'),
                'is_valid' => false
            ));
        }

        wp_die();
    }


    public static function ultimate_security_search_recent_ips()
    {
        if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
            $search_term = isset($_POST['search_term']) ? sanitize_text_field(wp_unslash($_POST['search_term'])) : '';
            $redirect_url = isset($_POST['redirect_url']) ? esc_url_raw(wp_unslash($_POST['redirect_url'])) : home_url();

            $ultimate_security_recent_ips = get_option('ultimate_security_recent_ips', []);
            $filtered_ips = [];

            if (!empty($search_term) && !empty($ultimate_security_recent_ips)) {
                foreach ($ultimate_security_recent_ips as $ip) {
                    if (strpos($ip, $search_term) !== false) {
                        $filtered_ips[] = $ip;
                    }
                }
            }

            $html = '';
            if (!empty($filtered_ips)) {
                $html .= '<div class="recent-ips-dropdown">';
                $html .= sprintf(
                    '<div class="dropdown-title">%s</div>',
                    sprintf(
                        __('Recent IPs matching "%s":', 'ultimate-security'),
                        esc_html($search_term)
                    )
                );
                
                foreach (array_reverse($filtered_ips) as $ip) {
                    $html .= '<div class="ip-option" data-ip="' . esc_attr($ip) . '" data-redirect="' . esc_attr($redirect_url) . '">' . esc_html($ip) . '</div>';
                }
                $html .= '</div>';
            }

            wp_send_json_success(array(
                'html' => $html,
                'count' => count($filtered_ips)
            ));
        } else {
            wp_send_json_error(array(
                'error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')
            ));
        }

        wp_die();
    }

    public static function ultimate_security_ip_set()
    {
        if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
            $ip = isset($_POST['ip']) ? sanitize_text_field(wp_unslash($_POST['ip'])) : '';

            // Validate IP using IpAddressValidator
            $validator = IpAddressValidator::create();
            if (!$validator->validate($ip)) {
                $errors = $validator->getErrors();
                wp_send_json_error(array('error_message' => !empty($errors) ? esc_html($errors[0]) : esc_html__('Invalid IP address format.', 'ultimate-security')));
                wp_die();
            }

            $cookie_name = "ultimate_security_debug_ip";
            setcookie(
                $cookie_name,
                $ip,
                [
                    'expires' => time() + (86400 * 30),
                    'path' => '/',
                    'secure' => is_ssl(),
                    'httponly' => true,
                    'samesite' => 'Strict'
                ]
            );

            $ultimate_security_recent_ips = get_option('ultimate_security_recent_ips', []);

            if (in_array($ip, $ultimate_security_recent_ips)) {
                array_splice($ultimate_security_recent_ips, array_search($ip, $ultimate_security_recent_ips), 1);
            }
            $ultimate_security_recent_ips[] = $ip;
            update_option('ultimate_security_recent_ips', $ultimate_security_recent_ips);

            wp_send_json_success(array('ip' => $ip));
        } else {
            wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
        }

        wp_die();
    }


    /**
     * REMOVED: IP reset was part of restrictions (server-level features)
     * Kept for backwards compatibility - just returns current IP
     */
    public static function ultimate_security_shop_ip_reset()
    {
        if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
            $ultimate_security_get_visitor_ip = IpHelper::getClientIp();

            wp_send_json_success(array(
                'ultimate_security_get_visitor_ip' => esc_html($ultimate_security_get_visitor_ip),
            ));
        } else {
            wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
        }

        wp_die();
    }

    /**
     * Handle review notice actions
     *
     * @return void
     */
    public static function handle_review_action()
    {
        check_ajax_referer('ultimate_security_nonce', 'security');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized'], 403);
        }

        $action = isset($_POST['review_action']) ? sanitize_text_field(wp_unslash($_POST['review_action'])) : '';

        switch ($action) {
            case 'review':
            case 'already-reviewed':
                update_option('ultimate_security_feedback_clicked', 1);
                break;
            case 'remind-later':
                // Progressive delay: 7 days, then 14 days, then 30 days
                $remind_count = (int) get_option('ultimate_security_feedback_remind_count', 0);
                $delays = [7, 14, 30, 90, 180, 365];
                $delay_days = $delays[min($remind_count, count($delays) - 1)];
                update_option('ultimate_security_feedback_next_show', time() + ($delay_days * DAY_IN_SECONDS));
                update_option('ultimate_security_feedback_remind_count', $remind_count + 1);
                break;
            case 'never-ask':
                update_option('ultimate_security_feedback_dismissed_permanently', 1);
                break;
            default:
                wp_send_json_error(['message' => 'Invalid action']);
                return;
        }

        wp_send_json_success(['message' => 'Preference saved']);
    }

    /**
     * Dismiss passkey setup notice
     *
     * @return void
     */
    public static function ultimate_security_dismiss_passkey_notice()
    {
        check_ajax_referer('dismiss_passkey_notice');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized'], 403);
        }

        $user_id = get_current_user_id();
        update_user_meta($user_id, 'ultimate_security_passkey_notice_dismissed', true);

        // Set reminder to show again in 7 days
        $remind_time = time() + (7 * DAY_IN_SECONDS);
        update_user_meta($user_id, 'ultimate_security_passkey_notice_remind_at', $remind_time);

        wp_send_json_success(['message' => 'Notice dismissed']);
    }
}
