<?php

namespace PWH_DCFH\App\Frontend\Controllers;

use PWH_DCFH\App\Frontend\Request\PWH_DCFH_Post_Repository;

if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('PWH_DCFH_Email_Handler')) {
    class PWH_DCFH_Email_Handler
    {
        private static $_instance;

        public $admin_email_routing = [];

        /**
         * Returns the singleton instance of the class.
         * @return self
         */
        public static function instance()
        {
            if (self::$_instance === null) {
                self::$_instance = new self();
            }

            return self::$_instance;
        }

        /**
         * Filter From Email
         *
         * @param $custom_mail_from
         *
         * @return void
         */
        public function set_mail_from($custom_mail_from)
        {
            if (!empty($custom_mail_from)) {
                add_filter('wp_mail_from', function () use ($custom_mail_from) {
                    return $custom_mail_from;
                }, 10);
            }
        }

        /**
         * Filter From Name
         *
         * @param $custom_mail_from_name
         *
         * @return void
         */
        public function set_mail_from_name($custom_mail_from_name)
        {
            if (!empty($custom_mail_from_name)) {
                add_filter('wp_mail_from_name', function () use ($custom_mail_from_name) {
                    return $custom_mail_from_name;
                }, 10);
            }

        }

        /**
         * Check blocklist Email
         * @return false
         */
        public function is_blacklisted_email()
        {
            $is_blacklisted_email = false;
            $post_repository = PWH_DCFH_Post_Repository::instance();
            $sender_email = $post_repository->sender_email;
            if (!empty($sender_email)) {
                $sender_email = strtolower($sender_email);
                // Blocklisted Email Addresses
                $blacklisted_emails = array_map('trim', explode(',', et_get_option('pwh_dcfh_blacklisted_emails')));
                if (!empty($blacklisted_emails) && in_array($sender_email, $blacklisted_emails, true)) {
                    $is_blacklisted_email = true;
                }
                // Blocklisted Email Address Domains
                $blacklisted_email_domains = array_map('trim', explode(',', et_get_option('pwh_dcfh_blacklisted_email_domains')));
                if (!empty($blacklisted_email_domains)) {
                    $email_domain = substr(strrchr($sender_email, '@'), 1);
                    if (in_array($email_domain, $blacklisted_email_domains, true)) {
                        $is_blacklisted_email = true;
                    }
                }
                // Blocklisted Keywords
                $blacklisted_keywords = array_filter(array_map('trim', explode(',', strtolower(et_get_option('pwh_dcfh_blacklisted_keywords')))));
                if (!empty($blacklisted_keywords)) {
                    foreach ($blacklisted_keywords as $keyword) {
                        if (stripos($sender_email, $keyword) !== false) {
                            $is_blacklisted_email = true;
                            break;
                        }
                    }
                }
            }

            return $is_blacklisted_email;

        }

        /**
         * Set Routing Emails
         *
         * @param $email_pattern
         *
         * @return void
         */
        public function set_admin_emails_routing($email_pattern)
        {
            if (!empty($email_pattern)) {
                $routes = explode(',', wp_strip_all_tags(htmlspecialchars_decode($email_pattern)));
                if (is_array($routes)) {
                    $routes = array_filter(array_map('trim', $routes));
                    foreach ($routes as $route) {
                        $outer_arr = explode('::', $route);
                        if (isset($outer_arr[0], $outer_arr[1])) {
                            $field_id = pwh_dcfh_helpers()::sanitize_key($outer_arr[0]);
                            $inner_arr = explode('|', $outer_arr[1]);
                            foreach ($inner_arr as $inner_val) {
                                $data_arr = explode(':', $inner_val);
                                if (!empty($data_arr[0]) && !empty($data_arr[1])) {
                                    $index = pwh_dcfh_helpers()::sanitize_key($data_arr[0]);
                                    $email = sanitize_email($data_arr[1]);
                                    $this->admin_email_routing[$field_id][$index] = $email;
                                }
                            }
                        }
                    }
                }
            }

        }

        /**
         * Get Routing Emails
         * @return array
         */
        public function get_admin_emails_routing()
        {
            $admin_emails = [];
            $emails_routing = $this->admin_email_routing;
            if (!empty($emails_routing)) {
                $post_repository = PWH_DCFH_Post_Repository::instance();
                $processed_fields_values = $post_repository->contact_form_data;
                foreach ($processed_fields_values as $value) {
                    if (isset($value['id'], $value['value'])) {
                        $field_id = pwh_dcfh_helpers()::sanitize_key($value['id']);
                        $field_data = explode(',', $value['value']);
                        if (!empty($field_data)) {
                            foreach ($field_data as $field_value) {
                                $field_value = pwh_dcfh_helpers()::sanitize_key($field_value);
                                if (isset($emails_routing[$field_id][$field_value])) {
                                    $admin_emails[] = $emails_routing[$field_id][$field_value];
                                }
                            }
                        }
                    }
                }
            }

            return $admin_emails;
        }
    }
}