<?php

namespace PWH_DCFH\App\Frontend\Controllers;

use PWH_DCFH\App\Frontend\Request\PWH_DCFH_Post_Repository;

if (!class_exists('PWH_DCFH_Email_Merge_Tags_Handler')) {
    class PWH_DCFH_Email_Merge_Tags_Handler
    {
        private static $_instance;

        /**
         * Keywords Array
         * @var string[]
         */
        public static $merg_data_tags = [
            '%%dcfh_site_name%%' => '',
            '%%dcfh_site_tagline%%' => '',
            '%%dcfh_site_url%%' => '',
            '%%dcfh_site_login_url%%' => '',
            '%%dcfh_post_id%%' => '',
            '%%dcfh_post_title%%' => '',
            '%%dcfh_post_url%%' => '',
            '%%dcfh_date%%' => '',
            '%%dcfh_time%%' => '',
            '%%dcfh_user_ip%%' => '',
            '%%dcfh_browser%%' => '',
            '%%dcfh_platform%%' => '',
        ];

        /**
         * Get Class Instance
         * @return PWH_DCFH_Email_Merge_Tags_Handler
         */
        public static function instance()
        {
            if (self::$_instance == null) {
                self::$_instance = new self();
            }

            return self::$_instance;
        }

        /**
         * Set Custom Tags
         */
        public static function fixed_tags_values()
        {
            self::$merg_data_tags['%%dcfh_site_name%%'] = get_bloginfo('name');
            self::$merg_data_tags['%%dcfh_site_tagline%%'] = get_bloginfo('description');
            self::$merg_data_tags['%%dcfh_site_url%%'] = get_bloginfo('url');
            self::$merg_data_tags['%%dcfh_site_login_url%%'] = wp_login_url();
            self::$merg_data_tags['%%dcfh_post_id%%'] = get_the_ID();
            self::$merg_data_tags['%%dcfh_post_title%%'] = get_the_title();
            self::$merg_data_tags['%%dcfh_post_url%%'] = get_the_permalink();
            self::$merg_data_tags['%%dcfh_date%%'] = date_i18n(pwh_dcfh_db()::get_setting('pwh_dcfh_mergetag_date_format', 'Y-m-d'));
            self::$merg_data_tags['%%dcfh_time%%'] = date_i18n(pwh_dcfh_db()::get_setting('pwh_dcfh_mergetag_time_format', 'h:i:sa'));
            self::$merg_data_tags['%%dcfh_user_ip%%'] = pwh_dcfh_helpers()::get_ip_address();
            self::$merg_data_tags['%%dcfh_browser%%'] = ucfirst((string)pwh_dcfh_helpers()::get_user_agent('browser'));
            self::$merg_data_tags['%%dcfh_platform%%'] = ucfirst((string)pwh_dcfh_helpers()::get_user_agent('platform'));
        }

        /**
         * Set Contact Form ID Tag Value
         *
         * @param $contact_form_id
         *
         * @return mixed
         */
        public static function get_contact_form_id_tag_value($contact_form_id)
        {
            return self::$merg_data_tags['%%dcfh_contact_form_id%%'] = $contact_form_id;
        }

        /**
         * Set Contact Entry Number Tag Value
         *
         * @param $entry_number
         *
         * @return mixed
         */
        public static function get_contact_entry_number_tag_value($entry_number)
        {
            return self::$merg_data_tags['%%dcfh_entry_number%%'] = $entry_number;
        }

        /**
         * Set Contact Form Title Tag Value
         *
         * @param $contact_form_title
         *
         * @return mixed
         */
        public static function get_contact_form_title_tag_value($contact_form_title)
        {
            return self::$merg_data_tags['%%dcfh_contact_form_title%%'] = $contact_form_title;
        }

        /**
         * Set Referer URL Tah
         *
         * @param $referer_url
         *
         * @return mixed
         */
        public static function get_referer_url_tag_value($referer_url)
        {
            return self::$merg_data_tags['%%dcfh_referer_url%%'] = $referer_url;
        }

        /**
         * Set Admin Tag Values
         *
         * @param $message
         *
         * @return void
         */
        public static function get_site_admin_tag_values($message)
        {
            static $is_tags_converted = false;
            if (!$is_tags_converted) {
                preg_match_all('/dcfh_site_admininfo([A-Za-z_][\w_]*)/', $message, $matches);
                if (isset($matches[0]) && !empty($matches[0])) {
                    $tags = $matches[0];
                    $tag_value = '-';
                    foreach ($tags as $tag) {
                        $tag_id = str_replace('dcfh_site_admininfo_', '', $tag);
                        $user_data = get_user_by('login', $tag_id);
                        if (false !== $user_data) {
                            $tag_value = $user_data->first_name.' '.$user_data->last_name;
                        }
                        self::$merg_data_tags['%%'.$tag.'%%'] = $tag_value;
                    }
                    $is_tags_converted = true;
                }
            }
        }

        /**
         * Get Submitter Info Tags Data
         *
         * @param $message
         *
         * @return void
         */
        public static function get_submitter_tags_values($message)
        {
            static $is_tags_converted = false;
            if (!$is_tags_converted) {
                preg_match_all('/dcfh_site_userinfo([A-Za-z_][\w_]*)/', $message, $matches);
                if (isset($matches[0]) && !empty($matches[0])) {
                    $tags = $matches[0];
                    $user_data = wp_get_current_user();
                    $tag_value = '-';
                    foreach ($tags as $tag) {
                        $tag_id = strtolower(str_replace('dcfh_site_userinfo_', '', $tag));
                        if (is_user_logged_in()) {
                            if ('id' === $tag_id) {
                                $tag_value = $user_data->data->ID;
                            }
                            if ('name' === $tag_id) {
                                $tag_value = $user_data->first_name.' '.$user_data->last_name;
                            }
                            if ('email' === $tag_id) {
                                $tag_value = $user_data->data->user_email;
                            }
                            if ('registered' === $tag_id) {
                                $tag_value = $user_data->data->user_registered;
                            }
                            if ('username' === $tag_id) {
                                $tag_value = $user_data->data->user_login;
                            }
                        }
                        if (strpos($message, $tag) !== false) {
                            self::$merg_data_tags['%%'.$tag.'%%'] = $tag_value;
                        }
                    }
                    $is_tags_converted = true;
                }
            }
        }

        /**
         * Replaced Tags Values
         *
         * @param $string
         * @param $post_request
         *
         * @return string
         */
        public static function get_merge_tags_values($string, $post_request)
        {
            self::get_site_admin_tag_values($string);
            self::get_submitter_tags_values($string);
            self::get_referer_url_tag_value($post_request->get_referer_url());
            $string = trim(stripslashes($string));
            $replace_pairs = self::$merg_data_tags;
            $fields_data_array = $post_request->get_contact_form_processed_fields();
            if (!PWH_DCFH_Post_Repository::instance()->save_queryparams_to_db) {
                $fields_data_array = wp_parse_args($post_request->get_query_params(), $fields_data_array);
            }
            foreach ($fields_data_array as $value) {
                $replace_pairs['%%'.$value['id'].'%%'] = $value['value'];
            }

            return str_ireplace(array_keys($replace_pairs), array_values($replace_pairs), $string);
        }

        /**
         * Get All Fields Tag Form Data
         *
         * @param $post_request
         * @param bool $is_richtext
         *
         * @return string
         * @since 1.3
         */
        public static function get_all_fields_data($post_request, $is_richtext = false)
        {
            $processed_fields_values = $post_request->get_contact_form_processed_fields();
            $line_break = $is_richtext ? "<br>" : "\r\n";
            $string = '';
            foreach ($processed_fields_values as $key => $value) {
                if ('file' !== $value['type']) {
                    $field_label = html_entity_decode($value['label']);
                    $field_value = !empty($value['value']) ? html_entity_decode($value['value']) : '-';
                    if (!$is_richtext) {
                        $string .= sprintf('%1$s: %2$s', $field_label, $field_value);
                    } else {
                        $string .= sprintf('<b>%1$s:</b> %2$s', $field_label, $field_value);
                    }
                    $string .= str_repeat($line_break, 2);
                }
            }

            return $string;
        }
    }
}