<?php 
namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class HelloPlus_Form_Spam_Blocker {
    public function __construct(){
        add_action('hello_plus/forms/validation',array($this,'form_validation'), 10, 2);
    }

    public function form_validation($record, $ajax_handler){
        $spam_settings = (array) get_option('cfkef_block_spam_settings', []);

        if ( ($spam_settings['enabled'] ?? '1') !== '1' ) return;

        // Targeted forms (blank => all)
        $current_form = strtolower( (string) $record->get_form_settings('form_name') );
        $forms_raw    = (string) ($spam_settings['forms'] ?? '');
        $forms_raw    = str_replace(["\r\n","\r"], "\n", $forms_raw);
        $form_list    = array_filter(array_map('trim', explode("\n", strtolower($forms_raw))));
        if ( !empty($form_list) && !in_array($current_form, $form_list, true) ) {
            return;
        }

        // Helpers
        $to_lines = function($str) {
            $str = str_replace(["\r\n","\r"], "\n", (string)$str);
            $arr = explode("\n", $str);
            $arr = array_filter(
                array_map(function($s){ return strtolower(trim(wp_strip_all_tags($s))); }, $arr),
                'strlen'
            );
            return array_values(array_unique($arr));
        };

        $contains_any = function(array $needles, string $haystack): bool {
            if ($haystack === '') return false;
            $haystack = strtolower($haystack);
            foreach ($needles as $n) {
                if ($n !== '' && strpos($haystack, $n) !== false) return true;
            }
            return false;
        };

        $text_words     = $to_lines($spam_settings['text_words']     ?? '');
        $textarea_words = $to_lines($spam_settings['textarea_words'] ?? '');
        $phone_words    = $to_lines($spam_settings['phone_words']    ?? '');
        $url_words      = $to_lines($spam_settings['url_words']      ?? ''); 

        $email_list_raw = $to_lines($spam_settings['email_list'] ?? '');
        $email_list = [];
        foreach ($email_list_raw as $e) {
            $e2 = sanitize_email($e);
            if ($e2) $email_list[] = strtolower($e2);
        }
        $email_list = array_values(array_unique($email_list));

        $mode = in_array(($spam_settings['mode'] ?? 'blocklist'), ['whitelist','blocklist'], true)
            ? $spam_settings['mode']
            : 'blocklist';

        $msg_blocklist = trim((string)($spam_settings['msg_blocklist'] ?? ''));
        $msg_whitelist = trim((string)($spam_settings['msg_whitelist'] ?? ''));

        $defaults = [
            'text_block'        => esc_html__('Please remove any restricted words from your input.', 'cool-formkit'),
            'text_allow'        => esc_html__('Please enter the required words to continue.', 'cool-formkit'),
            'textarea_block'    => esc_html__('Your message includes words that are not allowed. Kindly edit and try again.', 'cool-formkit'),
            'textarea_allow'    => esc_html__('Your message must include the required words.', 'cool-formkit'),
            'phone_block'       => esc_html__('The phone number contains invalid characters or words. Please check and try again.', 'cool-formkit'),
            'phone_allow'       => esc_html__('That phone number is not allowed. Please use a valid one.', 'cool-formkit'),
            'url_block'         => esc_html__('The link you entered contains invalid or restricted content.', 'cool-formkit'),
            'url_allow'         => esc_html__('This link is not allowed. Please provide a valid one.', 'cool-formkit'),
            'email_not_allowed' => esc_html__('This email address cannot be used. Please try another.', 'cool-formkit'),
        ];


        // Picks custom message first; otherwise field default
        $pick_msg = function(string $fallback_key) use ($mode, $msg_blocklist, $msg_whitelist, $defaults) : string {
            if ($mode === 'blocklist') return $msg_blocklist !== '' ? esc_html($msg_blocklist) : $defaults[$fallback_key];
            return $msg_whitelist !== '' ? esc_html($msg_whitelist) : $defaults[$fallback_key];
        };

        $fields = (array) $record->get('fields');
        if (empty($fields)) return;

        $has_errors = false;

        foreach ($fields as $id => $field) {
            $type  = isset($field['type']) ? strtolower((string)$field['type']) : '';
            $value = isset($field['value']) ? (string)$field['value'] : '';
            $v     = strtolower(wp_strip_all_tags($value));
            if ($v === '') continue;

            switch ($type) {
                case 'text':
                // case 'number':
                    if ($mode === 'blocklist') {
                        if (!empty($text_words) && $contains_any($text_words, $v)) {
                            $ajax_handler->add_error($id, $pick_msg('text_block'));
                            $has_errors = true;
                        }
                    } else { 
                        if (!empty($text_words) && !$contains_any($text_words, $v)) {
                            $ajax_handler->add_error($id, $pick_msg('text_allow'));
                            $has_errors = true;
                        }
                    }
                    break;

                case 'url':
                    $list_for_url = !empty($url_words) ? $url_words : $text_words;
                    if ($mode === 'blocklist') {
                        if (!empty($list_for_url) && $contains_any($list_for_url, $v)) {
                            $ajax_handler->add_error($id, $pick_msg('url_block'));
                            $has_errors = true;
                        }
                    } else { 
                        if (!empty($list_for_url) && !$contains_any($list_for_url, $v)) {
                            $ajax_handler->add_error($id, $pick_msg('url_allow'));
                            $has_errors = true;
                        }
                    }
                    break;

                case 'textarea':
                    if ($mode === 'blocklist') {
                        if (!empty($textarea_words) && $contains_any($textarea_words, $v)) {
                            $ajax_handler->add_error($id, $pick_msg('textarea_block'));
                            $has_errors = true;
                        }
                    } else {
                        if (!empty($textarea_words) && !$contains_any($textarea_words, $v)) {
                            $ajax_handler->add_error($id, $pick_msg('textarea_allow'));
                            $has_errors = true;
                        }
                    }
                    break;

                case 'tel':
                case 'phone':
                    if ($mode === 'blocklist') {
                        if (!empty($phone_words) && $contains_any($phone_words, $v)) {
                            $ajax_handler->add_error($id, $pick_msg('phone_block'));
                            $has_errors = true;
                        }
                    } else {
                        if (!empty($phone_words) && !$contains_any($phone_words, $v)) {
                            $ajax_handler->add_error($id, $pick_msg('phone_allow'));
                            $has_errors = true;
                        }
                    }
                    break;

                case 'email':
                    $email = sanitize_email($value);
                    if (!$email) break; 
                    $email = strtolower($email);

                    if ($mode === 'blocklist') {
                        if (!empty($email_list) && in_array($email, $email_list, true)) {
                            $msg = $msg_blocklist !== '' ? esc_html($msg_blocklist)
                                : sprintf(
                                    esc_html__('The email address (%s) is not allowed.', 'cool-formkit'),
                                    esc_html($email)
                                );
                            $ajax_handler->add_error($id, $msg);
                            $has_errors = true;
                        }
                    } else { 
                        if (!empty($email_list) && !in_array($email, $email_list, true)) {
                            $msg = $msg_whitelist !== '' ? esc_html($msg_whitelist)
                                : sprintf(
                                    esc_html__('The email address (%s) is not allowed.', 'cool-formkit'),
                                    esc_html($email)
                                );
                            $ajax_handler->add_error($id, $msg);
                            $has_errors = true;
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        if ($has_errors) return; 
    }
}
new HelloPlus_Form_Spam_Blocker;