<?php

namespace PWH_DCFH\App\Frontend\Controllers;

use PWH_DCFH\App\Frontend\Request\PWH_DCFH_Post_Repository;
use PWH_DCFH\App\Frontend\Request\PWH_DCFH_Post_Request;

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%%' => '',
        ];

        /**
         * Returns the singleton instance of the class.
         * @return self
         */
        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)
        {
            $key = 'dcfh_site_admininfo_';
            preg_match_all("/$key([A-Za-z_][\w_]*)/", $message, $matches);
            if (!empty($matches[1][0])) {
                $tag = $matches[1][0];
                $user = get_user_by('login', $tag);
                if ($user && $user->exists()) {
                    self::$merg_data_tags['%%'.$key.$tag.'%%'] = $user->first_name.' '.$user->last_name;
                }
            }
        }

        /**
         * Get Submitter Info Tags Data
         *
         * @param $message
         *
         * @return void
         */
        public static function get_submitter_tags_values($message)
        {
            $key = 'dcfh_site_userinfo_';
            if (is_user_logged_in()) {
                preg_match_all("/$key([A-Za-z_][\w_]*)/", $message, $matches);
                if (!empty($matches[0])) {
                    $tags = array_map(static function ($item) use ($key) {
                        return str_replace($key, '', $item);
                    }, $matches[0]);
                    if (!empty($tags)) {
                        $current_user = wp_get_current_user();
                        foreach ($tags as $tag) {
                            switch ($tag) {
                                case 'id';
                                    $value = $current_user->data->ID;
                                    break;
                                case 'name';
                                    $value = $current_user->first_name.' '.$current_user->last_name;
                                    break;
                                case 'email';
                                    $value = $current_user->data->user_email;
                                    break;
                                case 'registered';
                                    $value = $current_user->data->user_registered;
                                    break;
                                case 'username';
                                    $value = $current_user->data->user_login;
                                    break;
                                default;
                                    $value = '-';
                                    break;
                            }
                            self::$merg_data_tags['%%'.$key.$tag.'%%'] = $value;
                        }
                    }
                }
            }
        }

        /**
         * Replaced Tags Values
         *
         * @param $string
         *
         * @return string
         */
        public static function get_merge_tags_values($string)
        {
            $post_request = new PWH_DCFH_Post_Request();
            $post_repository = PWH_DCFH_Post_Repository::instance();
            self::get_site_admin_tag_values($string);
            self::get_submitter_tags_values($string);
            self::get_contact_form_id_tag_value($post_repository->contact_form_id);
            self::get_contact_entry_number_tag_value($post_repository->entry_number);
            self::get_contact_form_title_tag_value($post_repository->contact_form_title);
            self::get_referer_url_tag_value($post_request->get_referer_url());
            $string = trim(stripslashes($string));
            $replace_pairs = self::$merg_data_tags;
            $processed_fields_values = $post_repository->contact_form_data;
            if (!$post_repository->save_queryparams_to_db) {
                $processed_fields_values = array_merge($processed_fields_values, $post_request->get_query_params());
            }
            foreach ($processed_fields_values as $value) {
                $replace_pairs['%%'.$value['id'].'%%'] = $value['value'];
            }
            // Replace matched placeholders
            $string = str_ireplace(array_keys($replace_pairs), array_values($replace_pairs), $string);
            // List of placeholders to keep
            $placeholders_to_keep = ['%%dcfh_all_fields%%'];

            // Remove any remaining placeholders except those to keep
            return preg_replace_callback('/%%[^%]+%%/', static function ($matches) use ($placeholders_to_keep) {
                return in_array($matches[0], $placeholders_to_keep, true) ? $matches[0] : '';
            }, $string);
        }

        /**
         * Get All Fields Tag Form Data
         *
         * @param bool $is_richtext
         *
         * @return string
         * @since 1.3
         */
        public static function get_all_fields_data($is_richtext = false)
        {
            $post_request = new PWH_DCFH_Post_Request();
            $post_repository = PWH_DCFH_Post_Repository::instance();
            $processed_fields_values = $post_repository->contact_form_data;
            if (!$post_repository->save_queryparams_to_db) {
                $processed_fields_values = array_merge($processed_fields_values, $post_request->get_query_params());
            }
            $line_break = $is_richtext ? "<br>" : "\r\n";
            $output = '';
            foreach ($processed_fields_values as $value) {
                $field_label = html_entity_decode($value['label']);
                $field_value = html_entity_decode($value['value']);
                if (empty($field_value)) {
                    continue;
                }
                if (strpos($field_label, '_') !== false) {
                    $field_label = ucwords(str_replace('_', ' ', $field_label));
                }
                $formatted_line = !$is_richtext ? sprintf('%1$s: %2$s', $field_label, $field_value)
                    : sprintf('<b>%1$s:</b> %2$s', $field_label, $field_value);
                $output .= $formatted_line.$line_break;
            }

            return $output;
        }
    }
}