<?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('IAFWZCAI_AI_Settings')) {
    class IAFWZCAI_AI_Settings
    {
        protected $email_validation_keywords;
        protected $email_detection_keywords;
        protected $spam_detection_keywords;
        protected $email_validation_handling;
        protected $email_detection_handling;
        protected $spam_detection_handling;

        public function __construct()
        {
            // Load keywords and handling settings from options
            $this->email_validation_keywords = array_map('strtolower', explode(',', get_option("iafwzcai_email_validation_keywords", '')));
            $this->email_detection_keywords = array_map('strtolower', explode(',', get_option("iafwzcai_email_detection_keywords", '')));
            $this->spam_detection_keywords = array_map('strtolower', explode(',', get_option("iafwzcai_spam_detection_keywords", '')));

            $this->email_validation_handling = get_option("iafwzcai_email_validation_handling", 'send_mailchimp');
            $this->email_detection_handling = get_option("iafwzcai_email_detection_handling", 'send_mailchimp');
            $this->spam_detection_handling = get_option("iafwzcai_spam_detection_handling", 'send_mailchimp');
        }

        /**
         * Main function to process form data validation.
         */
        public function validate_form($formsData)
        {
            if (!is_array($formsData)) {
                return "Valid";
            }

            // Get email field from form data (assuming field name contains 'email')
            $email = isset($formsData['Contact Email']) ? strtolower($formsData['Contact Email']) : '';
            // Step 1: Check Email Validation
            $emailValidationResult = $this->check_email_validation($email);
            if ($emailValidationResult !== "Valid") {
                return $emailValidationResult;
            }

            // Step 2: Check Email Detection
            $emailDetectionResult = $this->check_email_detection($email);
            if ($emailDetectionResult !== "Valid") {
                return $emailDetectionResult;
            }

            // Step 3: Check Spam Detection
            $spamDetectionResult = $this->check_spam_detection($formsData);
            if ($spamDetectionResult !== "Valid") {
                return $spamDetectionResult;
            }

            return "Valid"; // No issues found
        }
        private function create_error_response($error_code, $body)
        {
            return [
                'status' => 'error',
                'category' => $error_code,
                'body' => $body
            ];
        }

        /**
         * Step 1: Check Email Validation Handling
         */
        protected function check_email_validation($email)
        {
            if ($this->email_validation_handling == "send_mailchimp") {
                return "Valid";
            }

            $detected_keyword = $this->contains_keyword($email, $this->email_validation_keywords);

            if ($detected_keyword) {
                return $this->create_error_response("AI_DETECTION", [
                    "title" => "Email Validation",
                    "message" => "Email contains restricted keyword: '$detected_keyword'"
                ]);
            }

            return "Valid";
        }


        /**
         * Step 2: Check Email Detection Handling
         */
        protected function check_email_detection($email)
        {
            if ($this->email_detection_handling == "send_mailchimp") {
                return "Valid";
            }

            $detected_keyword = $this->contains_keyword($email, $this->email_detection_keywords);

            if ($detected_keyword) {
                return $this->create_error_response("AI_DETECTION", [
                    "title" => "Email Detection",
                    "message" => "Email contains restricted keyword: '$detected_keyword'"
                ]);
            }

            return "Valid";
        }


        /**
         * Step 3: Check Spam Detection Handling (All Form Fields)
         */
        protected function check_spam_detection($formsData)
        {
            if ($this->spam_detection_handling == "send_mailchimp") {
                return "Valid";
            }
            foreach ($formsData as $field => $value) {
                $detected_keyword = $this->contains_keyword(strtolower($value), $this->spam_detection_keywords);

                if ($detected_keyword) {
                    return $this->create_error_response("AI_DETECTION", [
                        "title" => "Spam Detection",
                        "message" => "Spam detected in field '$field' due to keyword: '$detected_keyword'"
                    ]);
                }
            }

            return "Valid";
        }


        /**
         * Helper function to check if a string contains any keyword from a list
         */
        private function contains_keyword($input, $keywords)
        {
            if (empty($keywords) || empty($input)) {
                return false;
            }

            foreach ($keywords as $keyword) {
                $trimmedKeyword = trim($keyword);
                if (!empty($trimmedKeyword) && strpos($input, $trimmedKeyword) !== false) {
                    return $trimmedKeyword; // Return the matched keyword instead of true
                }
            }
            return false;
        }
    }
}
