<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit; // Prevent direct access to the file.
}

// Check if the class already exists to avoid redeclaration.
if (!class_exists('IAFWZDESK_SmartForm_Filter')) {
    class IAFWZDESK_SmartForm_Filter
    {
        private $spam_keywords = [
            'free',
            'offer',
            'win',
            'money',
            'click here',
            'subscribe',
            'bonus',
            'guarantee',
            'credit card',
            'loan',
            'debt',
            'discount',
            'urgent',
            'limited time',
            'exclusive',
            'double your',
            'no cost',
            'special promotion',
            'risk-free',
            'increase sales',
            'investment opportunity',
            'miracle',
            'get rich',
            '100% free',
            'unlimited',
            'order now',
            'call now',
            'limited offer',
            'act now',
            'apply now',
            'buy direct',
            'money back',
            'hidden fees',
            'extra cash',
            'instant',
            'no obligation',
            'pre-approved',
            'prize',
            'big savings',
            'earn extra',
            'confidential',
            'winning',
            'congratulations',
            'deal',
            'trial',
            'fast cash',
            'exclusive deal',
            'lowest price',
            'bargain',
            'cheap',
            'work from home',
            'financial freedom',
            'as seen on',
            'best price',
            'apply online',
            'don’t miss out',
            'hurry',
            'get started today',
            'incredible deal',
            'guaranteed',
            'one time offer',
            'reminder',
            'urgent response needed',
            'no hidden costs',
            'free consultation',
            'secret',
            'easy money',
            'get paid',
            'instant approval',
            'save big'
        ];
        private $max_links = 3;

        public function submission_status($record_data, $existing_entries)
        {
            $log_messages = [];

            // Spam Detection
            foreach ($record_data as $key => $value) {
                if ($this->detect_spam([$key => $value])['is_spam']) {
                    return ['status' => 'error', 'code' => 'SPAM_DETECTED', 'message' => "Spam detected in field '$key' with value '$value'"];
                }
            }

            // Email Validation
            $email_validation = $this->validate_email($record_data['email'] ?? '');
            if (!$email_validation['is_valid']) {
                return ['status' => 'error', 'code' => 'INVALID_EMAIL', 'message' => "Invalid Email in field 'email' with value '{$record_data['email']}'"];
            }

            // Phone Validation
            $phone_validation = $this->validate_phone($record_data['phone'] ?? '');
            if (!$phone_validation['is_valid']) {
                return ['status' => 'error', 'code' => 'INVALID_PHONE', 'message' => "Invalid Phone Number in field 'phone' with value '{$record_data['phone']}'"];
            }

            // Business vs. Personal Email Detection
            $email_type = $this->detect_email_type($record_data['email'] ?? '');
            if ($email_type['type'] == 'personal') {
                $log_messages[] = "Personal email detected in field 'email' with value '{$record_data['email']}'";
            }

            // Duplicate Entry Detection
            $duplicate_check = $this->detect_duplicate_entry($record_data, $existing_entries);
            if ($duplicate_check['is_duplicate']) {
                return ['status' => 'error', 'code' => 'DUPLICATE_ENTRY', 'message' => "Duplicate entry detected for email '{$record_data['email']}'"];
            }

            return ['status' => 'success', 'code' => 'VALID_SUBMISSION', 'message' => 'Submission passed all checks', 'log' => $log_messages];
        }

        public function detect_spam($record_data)
        {
            foreach ($record_data as $key => $value) {
                if (empty($value)) {
                    continue;
                }
                if ($key === 'email' && $this->is_fake_email($value)) {
                    return ['is_spam' => true, 'message' => "Fake Email detected in field '$key' with value '$value'"];
                }
                if ($this->contains_spam_keywords($value)) {
                    return ['is_spam' => true, 'message' => "Spam Keywords detected in field '$key' with value '$value'"];
                }
                if ($this->has_too_many_links($value)) {
                    return ['is_spam' => true, 'message' => "Too Many Links detected in field '$key' with value '$value'"];
                }
            }
            return ['is_spam' => false, 'message' => 'Not spam'];
        }

        private function contains_spam_keywords($value)
        {
            foreach ($this->spam_keywords as $keyword) {
                if (stripos($value, $keyword) !== false) {
                    return true;
                }
            }
            return false;
        }

        private function has_too_many_links($value)
        {
            return substr_count($value, 'http') > $this->max_links;
        }

        private function is_fake_email($email)
        {
            return preg_match('/\b(test|fake|temp|123|abc)\b/i', $email);
        }

        public function detect_email_type($email)
        {
            $personal_domains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com'];
            $email_domain = substr(strrchr($email, "@"), 1);
            return ['type' => in_array($email_domain, $personal_domains) ? 'personal' : 'business'];
        }

        public function validate_email($email)
        {
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                return ['is_valid' => false, 'message' => 'Invalid Email Format'];
            }
            if (preg_match('/\b(test|fake|temp|123|abc)\b/i', $email)) {
                return ['is_valid' => false, 'message' => 'Fake or Disposable Email'];
            }
            return ['is_valid' => true, 'message' => 'Valid Email'];
        }

        public function validate_phone($phone)
        {
            if (!preg_match('/^[0-9]{10,15}$/', $phone)) {
                return ['is_valid' => false, 'message' => 'Invalid Phone Number'];
            }
            return ['is_valid' => true, 'message' => 'Valid Phone Number'];
        }

        public function detect_duplicate_entry($record_data, $existing_entries)
        {
            foreach ($existing_entries as $entry) {
                if (strcasecmp($entry['email'], $record_data['email']) === 0) {
                    return ['is_duplicate' => true, 'message' => 'Duplicate Entry Detected'];
                }
            }
            return ['is_duplicate' => false, 'message' => 'Unique Entry'];
        }
    }
}
