<?php

namespace PWH_DCFH\App\Admin\CPT;

use DateTime;
use WP_Query;

if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('PWH_DCFH_Contact_Form_Metaboxes')) {
    class PWH_DCFH_Contact_Form_Metaboxes
    {
        private $_post_type;

        /**
         * Initializer Of The Class
         * Add/Remove Necessary Actions/Filters
         */
        public function init()
        {
            $post = isset($_GET['post']) ? sanitize_text_field($_GET['post']) : null;  // phpcs:ignore WordPress.Security.NonceVerification
            $this->_post_type = 'pwh_dcfh';
            add_action('add_meta_boxes', [$this, 'register_meta_boxes']);
            if (get_post_type($post) === $this->_post_type) {
                add_action('edit_form_top', [$this, 'register_quick_action_buttons']);
                add_action('admin_init', [$this, 'mark_as_spam']);
                add_action('admin_notices', [$this, 'register_admin_notice']);
            }
        }

        /**
         * Quick Actions
         *
         * @param $post
         */
        public function register_quick_action_buttons($post)
        {
            if ('pwh_dcfh' === $post->post_type) {
                $post_id = $post->ID;
                echo '<div class="quick-actions">';
                if (current_user_can('perform_entry_actions_pwh_dcfh')) {
                    if ('spam' === $post->post_status) {
                        printf(
                            '<a href="%s" class="button button-primary spam" onclick="return confirm(\'%s\');">%s</a>',
                            esc_url(add_query_arg('mark_as_not_spam', '1', get_edit_post_link($post_id))),
                            esc_html__('Are you sure you want to mark this entry as not a spam?', 'pwh-dcfh'),
                            esc_html__('Mark As Not Spam', 'pwh-dcfh')
                        );
                    }
                    if ('spam' !== $post->post_status) {
                        printf(
                            '<a href="%s" class="button button-primary spam" onclick="return confirm(\'%s\');">%s</a>',
                            esc_url(add_query_arg('mark_as_spam', '1', get_edit_post_link($post_id))),
                            esc_html__('Are you sure you want to mark this entry as spam?', 'pwh-dcfh'),
                            esc_html__('Mark As Spam', 'pwh-dcfh')
                        );
                    }

                }
                if (current_user_can('delete_pwh_dcfhs')) {
                    printf(
                        '<a href="%s" class="button button-primary trash" onclick="return confirm(\'%s\');">%s</a>',
                        esc_url(get_delete_post_link($post_id)),
                        esc_html__('Are you sure you want to move this entry to trash?', 'pwh-dcfh'),
                        esc_html__('Trash', 'pwh-dcfh')
                    );
                    printf(
                        '<a href="%s" class="button button-primary delete" onclick="return confirm(\'%s\');">%s</a>',
                        esc_url(get_delete_post_link($post_id, '', true)),
                        esc_html__('Are you sure you want to delete this entry permanently?', 'pwh-dcfh'),
                        esc_html__('Delete', 'pwh-dcfh')
                    );
                }
                echo '</div>';
            }
        }

        /**
         * Register Custom Post Type Meta Boxes
         */
        public function register_meta_boxes()
        {
            $mb_titles = [
                'mb_entry_detail' => __('Entry Details', 'pwh-dcfh'),
                'mb_actions' => __('Actions', 'pwh-dcfh'),
                'mb_user_entries' => __('Same User Entries', 'pwh-dcfh'),
                'mb_email_logs' => __('Sent Email Logs', 'pwh-dcfh'),
                'mb_clone_logs' => __('Entry Clone Logs', 'pwh-dcfh'),
                'mb_meta_details' => __('Meta Details', 'pwh-dcfh'),
                'mb_user_agent' => __('User-Agent Details', 'pwh-dcfh'),
            ];
            $mb_titles = apply_filters('pwh_dcfh_f_metabox_titles', $mb_titles);
            add_meta_box('pwh-dcfh-contact-form-entry-metabox', $mb_titles['mb_entry_detail'], [$this, 'maybe_contact_form_entry'], $this->_post_type, 'normal', 'core');
            if (current_user_can('perform_entry_actions_pwh_dcfh')) {
                add_meta_box('pwh-dcfh-action-buttons-metabox', $mb_titles['mb_actions'], [$this, 'maybe_action_buttons'], $this->_post_type, 'side', 'core');
            }
            add_meta_box('pwh-dcfh-user-other-entry-metabox', $mb_titles['mb_user_entries'], [$this, 'maybe_user_entries'], $this->_post_type, 'normal', 'core');
            if (pwh_dcfh_db()::is_setting_enabled('pwh_dcfh_enable_sent_email_log')) {
                add_meta_box('pwh-dcfh-email-logs-metabox', $mb_titles['mb_email_logs'], [$this, 'maybe_email_logs'], $this->_post_type, 'normal', 'core');
            }
            if (pwh_dcfh_db()::is_setting_enabled('pwh_dcfh_enable_clone_log')) {
                add_meta_box('pwh-dcfh-clone-logs-metabox', $mb_titles['mb_clone_logs'], [$this, 'maybe_clone_logs'], $this->_post_type, 'normal', 'core');
            }
            add_meta_box('pwh-dcfh-meta-details-metabox', $mb_titles['mb_meta_details'], [$this, 'maybe_form_meta'], $this->_post_type, 'side', 'core');
            add_meta_box('pwh-dcfh-user-agent-metabox', $mb_titles['mb_user_agent'], [$this, 'maybe_user_agent'], $this->_post_type, 'side', 'core');
        }

        /**
         * Register Display Contact Form Entry Meta-Box
         *
         * @param $post
         */
        public function maybe_contact_form_entry($post)
        {
            $post_id = $post->ID;
            $post_excerpt = get_post_field('post_excerpt', $post_id);
            $output = '';
            if (is_serialized($post_excerpt)) {
                $form_entries = pwh_dcfh_helpers()::maybe_unserialize($post_excerpt);
                if (!empty($form_entries) && is_array($form_entries)) {
                    $output .= '<table><tbody>';
                    $contact_form_id = pwh_dcfh_post_meta_handler()::get_contact_form_id_meta_value($post_id);
                    $wp_upload_dir = wp_upload_dir();
                    foreach ($form_entries as $form_entry) {
                        $field_type = $form_entry['type'];
                        $field_label = esc_html($form_entry['label']);
                        $field_value = !empty($form_entry['value']) ? $form_entry['value'] : '-';
                        $wp_subdir = $form_entry['subdir'] ?? '';
                        $wp_basedir = rtrim($wp_upload_dir['basedir'], '/').'/'.$wp_subdir;
                        $wp_baseurl = rtrim($wp_upload_dir['baseurl'], '/').'/'.$wp_subdir;
                        $output .= '<tr>';
                        $output .= sprintf('<th>%s:</th>', esc_html($field_label));
                        $inner_output = '';
                        if ($field_type === 'text') {
                            $inner_output = wpautop($field_value);
                        } elseif ($field_type === 'email' || is_email($field_value)) {
                            $inner_output = make_clickable(esc_html($field_value));
                        } elseif ($field_type === 'file') {
                            $attachments = !empty($form_entry['value']) ? explode(',', $form_entry['value']) : [];
                            $images_list = '';
                            $files_list = '';
                            foreach ($attachments as $attachment) {
                                if (isset($form_entry['is_media_library']) && $form_entry['is_media_library']) {
                                    $upload_dir = path_join($wp_basedir, $attachment);
                                    $upload_url = path_join($wp_baseurl, $attachment);
                                } else {
                                    $upload_dir = pwh_dcfh_file_helpers()::get_form_upload_dir($contact_form_id, $wp_subdir, $attachment);
                                    $upload_url = pwh_dcfh_file_helpers()::get_form_upload_url($contact_form_id, $wp_subdir, $attachment);
                                }
                                if (et_()->WPFS()->is_file($upload_dir) && et_()->WPFS()->exists($upload_dir)) {
                                    $file_size = esc_html(size_format(filesize($upload_dir)));
                                    $wp_check_filetype = wp_check_filetype($upload_dir);
                                    $file_mimetype = $wp_check_filetype['type'];
                                    if (in_array($file_mimetype, pwh_dcfh_wp_helpers()::get_image_mimes(), true)) {
                                        $images_list .= '<li>';
                                        $images_list .= sprintf(
                                            '<a href="%s" target="_blank"><img src="%s" alt="%s" /></a>',
                                            esc_url($upload_url),
                                            esc_url($upload_url),
                                            esc_attr($attachment)
                                        );
                                        $images_list .= sprintf('<span>%1$s: %2$s</span>', __('Size', 'pwh-dcfh'), $file_size);
                                        $images_list .= '</li>';
                                    } else {
                                        $files_list .= '<li>';
                                        $files_list .= sprintf('<a href="%s" target="_blank">%s</a>', esc_url($upload_url), esc_html($attachment));
                                        $files_list .= sprintf('<span>%1$s: %2$s</span>', __('Size', 'pwh-dcfh'), $file_size);
                                        $files_list .= '</li>';
                                    }
                                }
                            }
                            $inner_output .= !empty($images_list) ? '<ul class="images-list">'.$images_list.'</ul>' : '';
                            $inner_output .= !empty($files_list) ? '<ul class="files-list">'.$files_list.'</ul>' : '';
                        } elseif ($field_type === 'signature_pad') {
                            if (isset($form_entry['is_media_library']) && $form_entry['is_media_library']) {
                                $upload_dir = path_join($wp_basedir, $field_value);
                                $upload_url = path_join($wp_baseurl, $field_value);
                            } else {
                                $upload_dir = pwh_dcfh_file_helpers()::get_form_upload_dir($contact_form_id, $wp_subdir, $field_value);
                                $upload_url = pwh_dcfh_file_helpers()::get_form_upload_url($contact_form_id, $wp_subdir, $field_value);
                            }
                            if (et_()->WPFS()->is_file($upload_dir) && et_()->WPFS()->exists($upload_dir)) {
                                $file_size = esc_html(size_format(filesize($upload_dir)));
                                $inner_output .= '<div class="digital-signature">';
                                $inner_output .= sprintf(
                                    '<a href="%s" target="_blank"><img src="%s" alt="%s"/></a>',
                                    esc_url($upload_url),
                                    esc_url($upload_url),
                                    esc_attr(wp_basename($upload_url))
                                );
                                $inner_output .= sprintf('<span>%1$s: %2$s</span>', __('Size', 'pwh-dcfh'), $file_size);
                                $inner_output .= '</div>';
                            }
                        } else {
                            $inner_output = esc_html($field_value);
                        }
                        $output .= sprintf('<td>%s</td>', $inner_output);
                        $output .= '</tr>';
                    }
                    $output .= '</tbody></table>';
                }
            }
            echo force_balance_tags($output); // phpcs:ignore WordPress.Security.EscapeOutput
        }

        /**
         * Register Display Entry Actions Meta-Box
         *
         * @param $post
         */
        public function maybe_action_buttons($post)
        {

            $post_id = $post->ID;
            $output = "";
            $menu_page = admin_url('edit.php?post_type=pwh_dcfh');
            $post_url = esc_url(add_query_arg(['post_id' => $post_id, 'page' => 'create_post'], $menu_page));
            $template_url = esc_url(add_query_arg(['post_id' => $post_id, 'page' => 'create_email_template'], $menu_page));
            $send_email_url = esc_url(add_query_arg(['post_id' => $post_id, 'page' => 'send_email'], $menu_page));
            $link_disabled = '';
            $link_target = '_blank';
            if (!pwh_dcfh_user_handler()::is_user_email_exist($post_id)) {
                $link_disabled = 'disabled';
                $link_target = '';
                $template_url = 'javascript:void(0)';
                $send_email_url = 'javascript:void(0)';
            }
            $output .= sprintf(
                '<a href="%1$s" class="button button-large %3$s">%2$s</a>',
                $send_email_url,
                __('Reply/Send Email', 'pwh-dcfh'),
                esc_attr($link_disabled)
            );
            $output .= sprintf(
                '<a href="%1$s" class="button button-large" target="%3$s" %4$s>%2$s</a>',
                $template_url,
                __('Create Email Template', 'pwh-dcfh'),
                esc_attr($link_target),
                esc_attr($link_disabled)
            );
            $output .= sprintf(
                '<a href="%1$s" class="button button-large">%2$s</a>',
                $post_url,
                __('Create Post', 'pwh-dcfh')
            );
            echo force_balance_tags($output); // phpcs:ignore WordPress.Security.EscapeOutput
        }

        /**
         * Register Display Cloned Meta Box
         *
         * @param $post
         */
        public function maybe_clone_logs($post)
        {
            $post_id = $post->ID;
            $clones = pwh_dcfh_post_meta_handler()::get_clones_meta_value($post_id);
            $output = "";
            if (!empty($clones)) {
                $output .= "<table>";
                $output .= "<thead>";
                $output .= "<tr>";
                $output .= "<th class='text-center'>#</th>";
                $output .= "<th>".__('Title', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Created by', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Created at', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Type', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Staus', 'pwh-dcfh')."</th>";
                $output .= "</tr>";
                $output .= "</thead>";
                $output .= "<tbody>";
                usort($clones, static function ($a, $b) {
                    $date_a = DateTime::createFromFormat('d/m/Y H:i:s', $a['date']);
                    $date_b = DateTime::createFromFormat('d/m/Y H:i:s', $b['date']);

                    return $date_a >= $date_b;
                });
                $serial_number = 0;
                foreach ($clones as $clone) {
                    $serial_number++;
                    $created_by = pwh_dcfh_wp_helpers()::get_author_name($clone['author']);
                    $post_title = sprintf('<a href="%1$s">%2$s</a>', get_edit_post_link($clone['post_id']), get_the_title($clone['post_id']));
                    if (empty(get_the_title($clone['post_id']))) {
                        $post_title = __('May be deleted.', 'pwh-dcfh');
                    }
                    $post_date = pwh_dcfh_wp_helpers()::datetime($clone['date']);
                    $post_type = ucfirst(get_post_type($clone['post_id']));
                    $post_status = ucfirst(get_post_status($clone['post_id']));
                    $output .= "<tr>";
                    $output .= "<td class='text-center'>".$serial_number."</td>";
                    $output .= "<td>".$post_title."</td>";
                    $output .= "<td>".$created_by."</td>";
                    $output .= "<td>".$post_date."</td>";
                    $output .= "<td>".$post_type."</td>";
                    $output .= "<td>".$post_status."</td>";
                    $output .= "</tr>";
                }
                $output .= "</tbody>";
                $output .= "</table>";
            }
            if (empty($clones)) {
                $output .= "<div class='text-center'>".__('No record found.', 'pwh-dcfh')."</div>";
            }
            echo force_balance_tags($output);  // phpcs:ignore WordPress.Security.EscapeOutput
        }

        /**
         * Register Display Email Replies to Meta Box
         *
         * @param $post
         */
        public function maybe_email_logs($post)
        {
            $post_id = $post->ID;
            $logs = pwh_dcfh_logger()->get_logs('sent_email_log', $post_id);
            $output = "";
            if (!empty($logs)) {
                $output .= "<table>";
                $output .= "<thead>";
                $output .= "<tr>";
                $output .= "<th class='text-center'>#</th>";
                $output .= "<th>".__('Reply by', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Reply at', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Reply from', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Reply to', 'pwh-dcfh')."</th>";
                $output .= "</tr>";
                $output .= "</thead>";
                $output .= "<tbody>";
                $serial_number = 0;
                foreach ($logs as $log) {
                    if (is_serialized($log->post_content)) {
                        $post_content = maybe_unserialize($log->post_content);
                        if (!empty($post_content) && is_array($post_content)) {
                            $serial_number++;
                            $email_by = pwh_dcfh_wp_helpers()::get_author_name($log->post_author);
                            $email_at = pwh_dcfh_wp_helpers()::datetime($log->post_date);
                            $email_from = $post_content['email_from'];
                            $email_to = $post_content['email_to'];
                            $email_body = $post_content['email_body'];
                            $output .= "<tr>";
                            $output .= "<td class='text-center'>".$serial_number."</td>";
                            $output .= "<td>".$email_by."</td>";
                            $output .= "<td>".$email_at."</td>";
                            $output .= "<td>".$email_from."</td>";
                            $output .= "<td>".$email_to."</td>";
                            $output .= "</tr>";
                        }
                    }
                }
                $output .= "</tbody>";
                $output .= "</table>";
            }
            if (empty($logs)) {
                $output .= "<div class='text-center'>".__('No record found.', 'pwh-dcfh')."</div>";
            }
            echo force_balance_tags($output);  // phpcs:ignore WordPress.Security.EscapeOutput
        }

        /**
         * Register Display User Meta Box
         *
         * @param $post
         *
         * @return void|null
         */
        public function maybe_user_entries($post)
        {
            $post_id = $post->ID;
            $user_email = pwh_dcfh_post_meta_handler()::get_contact_email_meta_value($post_id);
            $ip_address = pwh_dcfh_post_meta_handler()::get_ip_address_meta_value($post_id);
            if (!pwh_dcfh_user_handler()::is_user_other_entry_exist($post_id, $user_email, $ip_address)) {
                echo "<div class='text-center'>".esc_html__('No record found.', 'pwh-dcfh')."</div>";

                return null;
            }
            $paged = isset($_GET['paged']) ? sanitize_key($_GET['paged']) : 1; // phpcs:ignore WordPress.Security.NonceVerification
            $per_page = (int)apply_filters('pwh_dcfh_f_user_entries_per_page', 10);
            $args = [
                'post_type' => $this->_post_type,
                'post__not_in' => [$post_id],
                'posts_per_page' => $per_page,
                'paged' => $paged,
                'post_status' => ['draft', 'private'],
                'orderby' => 'date',
                'order' => 'DESC',
                'no_found_rows' => false,
                'cache_results' => false,
                'update_post_meta_cache' => false,
                'update_post_term_cache' => false,
                // phpcs:ignore
                'meta_query' => [
                    'relation' => 'OR',
                    [
                        'key' => '_pwh_dcfh_contact_email',
                        'compare' => 'LIKE',
                        'value' => $user_email
                    ],
                    [
                        'key' => '_pwh_dcfh_ip_address',
                        'compare' => 'LIKE',
                        'value' => $ip_address
                    ]
                ],
            ];
            if ($post->post_author > 0) {
                $args['author__in'] = $post->post_author;
            }
            $user_query = new WP_Query($args);
            $output = "";
            if (!empty($user_query->posts)) {
                if (1 !== $paged) {
                    $serial_number = ($per_page * ($paged - 1));
                } else {
                    $serial_number = 0;
                }
                $output .= "<table>";
                $output .= "<tbody>";
                $output .= "<thead>";
                $output .= "<tr>";
                $output .= "<th class='text-center'>".__('Sr#', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Entry', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Read', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Read By', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Read at', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Contact Form', 'pwh-dcfh')."</th>";
                $output .= "<th>".__('Date', 'pwh-dcfh')."</th>";
                $output .= "</tr>";
                $output .= "</thead>";
                foreach ($user_query->posts as $user_post) {
                    $serial_number++;
                    $contact_form = pwh_dcfh_db()::get_contact_form_title(pwh_dcfh_post_meta_handler()::get_contact_form_id_meta_value($user_post->ID));
                    $post_title = sprintf(__('<a href="%s">Entry# %d</a>', 'pwh-dcfh'), esc_url(get_edit_post_link($user_post->ID)), $user_post->ID);
                    $post_date = pwh_dcfh_wp_helpers()::datetime($user_post->post_date);
                    $post_read = __('No', 'pwh-dcfh');
                    $post_read_at = $user_post->post_modified;
                    $post_read_by = '-';
                    if ($post_read_at !== '0000-00-00 00:00:00') {
                        $post_read_at = pwh_dcfh_wp_helpers()::datetime($post_read_at);
                        $post_read_by = pwh_dcfh_wp_helpers()::get_author_name(pwh_dcfh_post_meta_handler()::get_read_by_meta_value($user_post->ID));
                        $post_read = __('Yes', 'pwh-dcfh');
                    }
                    if ($post_read_at === '0000-00-00 00:00:00') {
                        $post_read_at = '-';
                    }
                    $output .= "<tr>";
                    $output .= "<td class='text-center'>".esc_html($serial_number)."</td>";
                    $output .= "<td>".$post_title."</td>";
                    $output .= "<td>".esc_html($post_read)."</td>";
                    $output .= "<td>".esc_html($post_read_by)."</td>";
                    $output .= "<td>".esc_html($post_read_at)."</td>";
                    $output .= "<td>".esc_html($contact_form)."</td>";
                    $output .= "<td>".esc_html($post_date)."</td>";
                    $output .= "</tr>";
                }
                $output .= "</tbody>";
                $output .= "</table>";
                $big = PHP_INT_MAX;
                $output .= '<div class="pagination">';
                $output .= paginate_links([
                    'base' => str_replace([$big, '#038;'], ['%#%', ''], esc_url(get_pagenum_link($big)).'#pwh-dcfh-user-other-entry-metabox'),
                    'total' => $user_query->max_num_pages,
                    'current' => max(1, $paged),
                    'format' => '?paged=%#%',
                    'show_all' => false,
                    'type' => 'plain',
                    'end_size' => 2,
                    'mid_size' => 1,
                    'prev_next' => true,
                    'screen_reader_text' => '&nbsp;',
                    'prev_text' => __('Previous', 'pwh-dcfh'),
                    'next_text' => __('Next', 'pwh-dcfh'),
                    'add_args' => false,
                    'add_fragment' => '',
                ]);
                $output .= '</div>';
            }
            if (empty($user_query->posts)) {
                $output .= "<div class='text-center'>".__('No record found.', 'pwh-dcfh')."</div>";
            }
            echo force_balance_tags($output);  // phpcs:ignore WordPress.Security.EscapeOutput
        }

        /**
         * Register Display Form Meta Detail Meta Box
         *
         * @param $post
         */
        public function maybe_form_meta($post)
        {
            $post_id = $post->ID;
            $submitter_name = apply_filters('pwh_dcfh_f_submitter_label', __('Visitor', 'pwh-dcfh'));
            $submitter_id = '';
            if ($post->post_author > 0) {
                $user_data = get_user_by('ID', $post->post_author);
            } else {
                $user_data = get_user_by('email', pwh_dcfh_post_meta_handler()::get_contact_email_meta_value($post_id));
            }
            if (isset($user_data->ID)) {
                $submitter_id = $user_data->ID;
                $submitter_name = sprintf('<a target="_blank" href="%1$s">%2$s</a>', get_edit_user_link($user_data->ID), pwh_dcfh_wp_helpers()::get_author_name($user_data->ID));
            }
            $contact_form_id = pwh_dcfh_post_meta_handler()::get_contact_form_id_meta_value($post_id);
            $contact_form_title = pwh_dcfh_db()::get_contact_form_title($contact_form_id);
            $page_id = pwh_dcfh_post_meta_handler()::get_page_id_meta_value($post_id);
            $referer_url = pwh_dcfh_post_meta_handler()::get_referer_url_meta_value($post_id);
            $post_date = pwh_dcfh_wp_helpers()::datetime($post->post_date);
            $output = "<table>";
            $output .= "<tbody>";
            if (!empty($submitter_id)) {
                $output .= "<tr>";
                $output .= "<th>".__('Submitter ID:', 'pwh-dcfh')."</th>";
                $output .= "<td>".$submitter_id."</td>";
                $output .= "</tr>";
            }
            $output .= "<tr>";
            $output .= "<th>".__('Submitter:', 'pwh-dcfh')."</th>";
            $output .= "<td>$submitter_name</td>";
            $output .= "</tr>";
            $output .= "<tr>";
            $output .= "<th>".__('Contact Form:', 'pwh-dcfh')."</th>";
            $output .= "<td>$contact_form_title</td>";
            $output .= "</tr>";
            $output .= "<tr>";
            $output .= "<th>".__('Page:', 'pwh-dcfh')."</th>";
            $output .= "<td>".sprintf('<a href="%1$s" target="_blank">%2$s</a>', get_the_permalink($page_id), get_the_title($page_id))."</td>";
            $output .= "</tr>";
            $output .= "<tr>";
            $output .= "<th>".__('Referer URL:', 'pwh-dcfh')."</th>";
            $output .= "<td>".make_clickable($referer_url)."</td>";
            $output .= "</tr>";
            $output .= "<tr>";
            $output .= "<th>".__('Date:', 'pwh-dcfh')."</th>";
            $output .= "<td>$post_date</td>";
            $output .= "</tr>";
            $output .= "</tbody>";
            $output .= "</table>";
            echo force_balance_tags($output);  // phpcs:ignore WordPress.Security.EscapeOutput
        }

        /**
         * Register Display User Agent Meta Box
         *
         * @param $post
         */
        public function maybe_user_agent($post)
        {
            $post_id = $post->ID;
            // IP Address
            $ip_address = pwh_dcfh_post_meta_handler()::get_ip_address_meta_value($post_id);
            // User Browser
            $user_agent = pwh_dcfh_post_meta_handler()::get_user_agent_meta_value($post_id);
            $user_browser = !empty($user_agent['browser']) ? $user_agent['browser'].'-'.$user_agent['version'] : '';
            // User OS
            $user_os = !empty($user_agent['platform']) ? ucfirst($user_agent['platform']) : '';
            if (!empty($ip_address) || !empty($user_browser) || !empty($user_os)) {
                $output = "<table>";
                $output .= "<tbody>";
                $output .= "<th>".__('IP Address:', 'pwh-dcfh')."</th>";
                $output .= "<td>$ip_address</td>";
                $output .= "</tr>";
                $output .= "<tr>";
                $output .= "<th>".__('Browser', 'pwh-dcfh')."</th>";
                $output .= "<td>$user_browser</td>";
                $output .= "</tr>";
                $output .= "<tr>";
                $output .= "<th>".__('OS', 'pwh-dcfh')."</th>";
                $output .= "<td>$user_os</td>";
                $output .= "</tr>";
                $output .= "</tbody>";
                $output .= "</table>";
            } else {
                $output = "<div class='text-center'>".__('No record found.', 'pwh-dcfh')."</div>";
            }
            echo force_balance_tags($output);  // phpcs:ignore WordPress.Security.EscapeOutput
        }

        /**
         * Mark As Spam
         * @return void
         */
        public function mark_as_spam()
        {
            if (current_user_can('perform_entry_actions_pwh_dcfh') && isset($_GET['post'])) { // phpcs:ignore WordPress.Security.NonceVerification
                $post_id = sanitize_text_field($_GET['post']);// phpcs:ignore WordPress.Security.NonceVerification
                $url = add_query_arg(
                    [
                        'post' => $post_id,
                        'action' => 'edit'
                    ],
                    admin_url('post.php')
                );
                if (isset($_GET['mark_as_spam'])) { // phpcs:ignore WordPress.Security.NonceVerification
                    // Add Email In Spamming List
                    $blacklisted_emails = trim(et_get_option('pwh_dcfh_blacklisted_emails'));
                    $sender_email = get_post_meta($post_id, '_pwh_dcfh_contact_email', true);
                    if (!empty($sender_email)) {
                        $blacklisted_emails_array = array_filter(array_map('trim', explode(',', $blacklisted_emails)));
                        if (!in_array($sender_email, $blacklisted_emails_array, true)) {
                            $blacklisted_emails_array[] = $sender_email;
                        }
                        $blacklisted_emails = implode(',', $blacklisted_emails_array);
                        et_update_option('pwh_dcfh_blacklisted_emails', $blacklisted_emails);
                    }
                    // Mark Entry As Spam
                    if ('0000-00-00 00:00:00' === get_post_field('post_modified', $post_id) && '0000-00-00 00:00:00' === get_post_field('post_modified_gmt', $post_id)) {
                        pwh_dcfh_db()::set_post_status_and_modified($post_id, 'spam');
                    } else {
                        pwh_dcfh_db()::set_post_status_and_modified($post_id, 'spam', current_time('mysql'), current_time('mysql', 1));
                    }
                    wp_safe_redirect($url);
                    exit;

                }
                if (isset($_GET['mark_as_not_spam'])) { // phpcs:ignore WordPress.Security.NonceVerification
                    // Remove Email From Spamming List
                    $blacklisted_emails = trim(et_get_option('pwh_dcfh_blacklisted_emails'));
                    $sender_email = get_post_meta($post_id, '_pwh_dcfh_contact_email', true);
                    if (!empty($sender_email)) {
                        $blacklisted_emails_array = array_filter(explode(',', $blacklisted_emails));
                        if (($key = array_search($sender_email, $blacklisted_emails_array, true)) !== false) {
                            unset($blacklisted_emails_array[$key]);
                        }
                        $blacklisted_emails = implode(',', $blacklisted_emails_array);
                    }
                    et_update_option('pwh_dcfh_blacklisted_emails', $blacklisted_emails);
                    // Mark Entry As Not Spam
                    if ('0000-00-00 00:00:00' === get_post_field('post_modified', $post_id) && '0000-00-00 00:00:00' === get_post_field('post_modified_gmt', $post_id)) {
                        pwh_dcfh_db()::set_post_status_and_modified($post_id);
                    } else {
                        pwh_dcfh_db()::set_post_status_and_modified($post_id, 'private', current_time('mysql'), current_time('mysql', 1));
                    }
                    wp_safe_redirect($url);
                    exit;
                }

            }
        }

        /**
         * Register Display Admin Notice
         * @return void|null
         */
        public function register_admin_notice()
        {
            if (!empty($_GET['_wpnonce'])) {
                $is_error = false;
                $_wpnonce = sanitize_text_field($_GET['_wpnonce']);
                if (wp_verify_nonce($_wpnonce, 'entry_action')) {
                    $success = isset($_GET['success']) && sanitize_text_field($_GET['success']);
                    $cloned_post_id = isset($_GET['cloned_post_id']) ? sanitize_text_field($_GET['cloned_post_id']) : null;
                    $email_to = isset($_GET['email_sent_to']) ? sanitize_text_field($_GET['email_sent_to']) : null;
                    //$class = $success ? 'notice notice-success is-dismissible' : 'notice notice-error is-dismissible';
                    $message = '';
                    if ($success && !empty($cloned_post_id)) {
                        $message .= __('The post is created successfully.', 'pwh-dcfh');
                        $message .= sprintf(' <a href="%1$s" target="_blank">%2$s</a>', esc_url(get_edit_post_link($cloned_post_id)), __('Click here to edit', 'pwh-dcfh'));
                        if ('publish' === get_post_status($cloned_post_id)) {
                            $message .= sprintf(' &#124; <a href="%1$s" target="_blank">%2$s</a>', esc_url(get_the_permalink($cloned_post_id)), __('Click here to view', 'pwh-dcfh'));
                        }
                    }
                    if (is_email($email_to)) {
                        if ($success) {
                            $message .= __('The email sent successfully to ', 'pwh-dcfh');
                            $message .= make_clickable($email_to);
                        } else {
                            $is_error = true;
                            $reason = get_transient('pwh_dcfh_email_failed');
                            $message .= __('The email does not sent at '.make_clickable($email_to), 'pwh-dcfh');  // phpcs:ignore WordPress.Security.EscapeOutput
                            if (!empty($reason)) {
                                $message .= sprintf(' <b>Reason:</b> %s', esc_html($reason));
                                delete_transient('pwh_dcfh_email_failed');
                            }
                        }
                    }
                    if ($is_error) {
                        pwh_dcfh_admin_notice()::add_error_message($message);
                    } else {
                        pwh_dcfh_admin_notice()::add_success_message($message);
                    }
                    pwh_dcfh_admin_notice()::show_admin_notice();
                }
            }
        }

    }
}