<?php

namespace PWH_DCFH\App\Admin\CPT;

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

        private $_post_type_singular;

        private $_post_type_plural;

        private $_pagenow;

        /**
         * Initializer Of The Class
         * Add/Remove Necessary Actions/Filters
         */
        public function init()
        {
            global $pagenow;
            $this->_pagenow = $pagenow;
            $this->_post_type = 'pwh_dcfh';
            $this->_post_type_singular = _x('Entry', 'post type singular name', 'pwh-dcfh');
            $this->_post_type_plural = _x('Entries', 'post type plural name', 'pwh-dcfh');
            add_action('init', [$this, 'register_post_type'], 999);
            // Columns
            add_filter("manage_{$this->_post_type}_posts_columns", [$this, 'maybe_column_header']);
            add_action("manage_{$this->_post_type}_posts_custom_column", [$this, 'maybe_column_content'], 10, 2);
            // Change Post Status Label
            add_filter("views_edit-$this->_post_type", [$this, 'maybe_change_status_label'], 10, 1);
            // Update Status When View
            add_action('load-post.php', [$this, 'maybe_update_entry_read_by']);
            // Register Bulk Action
            add_filter("bulk_actions-edit-$this->_post_type", [$this, 'maybe_bulk_action']);
            add_action("handle_bulk_actions-edit-$this->_post_type", [$this, 'maybe_process_bulk_actions'], 10, 3);
            // Post-Row Actions
            add_filter('post_row_actions', [$this, 'maybe_post_row_actions'], 10, 2);
            add_action('admin_init', [$this, 'maybe_process_row_action']);
            // Action Messages
            add_action('admin_notices', [$this, 'maybe_custom_bulk_action_message']);
            add_filter('bulk_post_updated_messages', [$this, 'maybe_bulk_update_message'], 10, 2);
            // Page Title
            add_filter('admin_title', [$this, 'maye_change_admin_title'], 10, 2);
            add_action('admin_head', [$this, 'maye_change_post_title']);
            // Admin Modifications Hooks
            add_action('admin_init', [$this, 'maybe_deregister_script']);
            // Pending Label
            add_action('admin_menu', [$this, 'maybe_menu_hooks']);
            // Register Sortable & Filter
            add_filter("manage_edit-{$this->_post_type}_sortable_columns", [$this, 'maybe_sortable_columns']);
            add_filter('parse_query', [$this, 'maybe_parse_query']);
            add_action('restrict_manage_posts', [$this, 'maybe_manage_posts'], 10, 2);
            // Extra Tab Nav
            add_action('manage_posts_extra_tablenav', [$this, 'maybe_extra_table_nav'], 20, 1);
            // Remove Screen Options
            add_filter('screen_options_show_screen', [$this, 'maybe_remove_screen_options'], 10, 2);
            // Before Delete
            add_action('before_delete_post', [$this, 'maybe_before_delete']);

        }

        /**
         * Register Custom Post Type
         */
        public function register_post_type()
        {
            $post_arguments = [
                'public' => false,
                'publicly_queryable' => false,
                'show_ui' => true,
                'show_in_menu' => true,
                'query_var' => true,
                'rewrite' => false,
                'capability_type' => 'pwh_dcfh',
                'capabilities' => ['create_posts' => 'do_not_allow'],
                'map_meta_cap' => true,
                'has_archive' => false,
                'hierarchical' => false,
                'can_export' => true,
                'show_in_rest' => false,
                'show_in_admin_bar' => true,
                'show_in_nav_menus' => true,
                'menu_position' => 20,
                'menu_icon' => 'dashicons-email',
                'supports' => ['author'],
                'labels' => [
                    'name' => $this->_post_type_plural,
                    'singular_name' => $this->_post_type_singular,
                    'edit_item' => __('Entry Details', 'pwh-dcfh'),
                    'all_items' => sprintf('%s', $this->_post_type_plural),
                    'items_list' => sprintf(__('%s list', 'pwh-dcfh'), $this->_post_type_plural),
                    'not_found' => sprintf(__('No %s found.', 'pwh-dcfh'), $this->_post_type_plural),
                    'not_found_in_trash' => sprintf(__('No %s found in Trash.', 'pwh-dcfh'), $this->_post_type_plural),
                    'search_items' => sprintf(__('Search %s', 'pwh-dcfh'), $this->_post_type_plural),
                    'view_item' => sprintf(__('View %s', 'pwh-dcfh'), $this->_post_type_singular),
                    'view_items' => sprintf(__('View %s', 'pwh-dcfh'), $this->_post_type_plural),
                    'menu_name' => apply_filters('pwh_dcfh_f_cf_menu_name', __('Contact Form', 'pwh-dcfh')),
                ]
            ];
            register_post_type('pwh_dcfh', $post_arguments);
            register_post_status('spam', [
                'label' => _x('Spam', 'post', 'pwh-dcfh'),
                'public' => true,
                'exclude_from_search' => false,
                'show_in_admin_all_list' => true,
                'show_in_admin_status_list' => true,
                'label_count' => _n_noop('Spam <span class="count">(%s)</span>', 'Spam <span class="count">(%s)</span>', 'pwh-dcfh'),
            ]);
            add_post_type_support('pwh_dcfh', 'custom-status');
        }

        /**
         * Register Custom Post-Type Header Columns
         *
         * @param array $columns
         *
         * @return array
         */
        public function maybe_column_header(array $columns)
        {
            unset($columns['date'], $columns['title'], $columns['author']);
            $columns['pwh_dcfh_entry_id'] = __('Entry No.', 'pwh-dcfh');
            // Get dynamic columns
            $dynamic_columns = pwh_dcfh_db()::dynamic_entry_columns();
            if (!empty($dynamic_columns)) {
                foreach ($dynamic_columns as $dynamic_column) {
                    if ($dynamic_column === 'ip') {
                        continue;
                    }
                    $columns["pwh_dcfh_$dynamic_column"] = ucwords($dynamic_column);
                }
            }
            // Add fixed columns
            $columns['pwh_dcfh_user_email'] = __('Email', 'pwh-dcfh');
            $columns['pwh_dcfh_entry_date'] = __('Date', 'pwh-dcfh');
            $columns['pwh_dcfh_entry_read'] = __('Read', 'pwh-dcfh');
            $columns['pwh_dcfh_contact_form_id'] = __('Contact Form', 'pwh-dcfh');
            // Initialize new columns array
            $new_columns = [];
            $beforeColumn = 'pwh_dcfh_entry_date';
            // Reorder columns
            foreach ($columns as $key => $value) {
                if ($key === $beforeColumn) {
                    $new_columns['pwh_dcfh_entry_read'] = '';
                    $new_columns['pwh_dcfh_contact_form_id'] = '';
                }
                $new_columns[$key] = $value;
            }
            if (in_array('ip', $dynamic_columns, true)) {
                $new_columns['pwh_dcfh_entry_ip'] = __('IP', 'pwh-dcfh');
            }

            return $new_columns;
        }

        /**
         * Register Custom Post-Type Header Columns Content
         *
         * @param $column_name
         * @param $post_id
         */
        public function maybe_column_content($column_name, $post_id)
        {
            $post_status = get_post_status($post_id);
            $dynamic_columns = pwh_dcfh_db()::dynamic_entry_columns();
            $contact_email = pwh_dcfh_post_meta_handler()::get_contact_email_meta_value($post_id);
            $post_date = get_post_field('post_date', $post_id);
            $post_author = get_post_field('post_author', $post_id);
            if (!empty($contact_email)) {
                $contact_email = make_clickable($contact_email);
            } elseif ($post_author > 0) {
                $user_data = get_user_by('ID', $post_author);
                if (isset($user_data->data->user_email)) {
                    $contact_email = make_clickable($user_data->data->user_email);
                }
            } else {
                $contact_email = __('No Email', 'pwh-dcfh');
            }
            $contact_form_id = pwh_dcfh_post_meta_handler()::get_contact_form_id_meta_value($post_id);
            $ip_address = pwh_dcfh_post_meta_handler()::get_ip_address_meta_value($post_id);
            $ip_address = !empty($ip_address) ? $ip_address : '-';
            switch ($column_name) {
                case 'pwh_dcfh_entry_id':
                    echo sprintf(__('<a href="%s">Entry# %d</a>', 'pwh-dcfh'), esc_url(get_edit_post_link($post_id)), $post_id); // phpcs:ignore
                    break;
                case 'pwh_dcfh_user_email':
                    echo '<span class="entry__status '.esc_attr($post_status).'">';
                    echo $contact_email; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo '</span>';
                    break;
                case 'pwh_dcfh_contact_form_id':
                    echo esc_html(pwh_dcfh_db()::get_contact_form_title($contact_form_id));
                    break;
                case 'pwh_dcfh_entry_date':
                    echo esc_html(pwh_dcfh_wp_helpers()::datetime($post_date));
                    break;
                case 'pwh_dcfh_entry_read':
                    echo wp_kses_post(self::is_read($post_id));
                    break;
                case 'pwh_dcfh_entry_ip':
                    echo esc_html($ip_address);
                    break;
                default:
                    break;
            }
            if (!empty($dynamic_columns)) {
                $post_excerpt = get_post_field('post_excerpt', $post_id);
                if (is_serialized($post_excerpt)) {
                    $form_entries = pwh_dcfh_helpers()::maybe_unserialize($post_excerpt);
                    if (!empty($form_entries) && is_array($form_entries)) {
                        $wp_upload_dir = wp_upload_dir();
                        $plucked_entries = [];
                        foreach ($form_entries as $form_entry) {
                            $plucked_entries[$form_entry['id']] = $form_entry;
                        }
                        foreach ($dynamic_columns as $dynamic_column) {
                            if ($column_name === "pwh_dcfh_$dynamic_column") {
                                $field_type = $plucked_entries[$dynamic_column]['type'] ?? 'input';
                                $field_value = isset($plucked_entries[$dynamic_column]) ? $plucked_entries[$dynamic_column]['value'] : '';
                                $wp_subdir = $plucked_entries[$dynamic_column]['subdir'] ?? '';
                                $wp_basedir = rtrim($wp_upload_dir['basedir'], '/').'/'.$wp_subdir;
                                $wp_baseurl = rtrim($wp_upload_dir['baseurl'], '/').'/'.$wp_subdir;
                                if ('file' === $field_type || 'signature_pad' === $field_type) {
                                    $attachments = explode(',', $field_value);
                                    if (!empty($attachments)) {
                                        $attachments_list = '<ul>';
                                        foreach ($attachments as $attachment) {
                                            $fielname = pathinfo($attachment, PATHINFO_FILENAME);
                                            if (isset($plucked_entries[$dynamic_column]['is_media_library']) && $plucked_entries[$dynamic_column]['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)) {
                                                $attachments_list .= sprintf('<li><a href="%1$s" target="_blank">%2$s</a></li>', $upload_url, $fielname);
                                            }
                                        }
                                        $attachments_list .= '</ul>';
                                        echo $attachments_list; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                    }

                                } else {
                                    echo $field_value; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                }
                            }
                        }
                    }
                }
            }
        }

        /**
         * Change Custom Post-Type Status Text
         *
         * @param $views
         *
         * @return mixed
         */
        public function maybe_change_status_label($views)
        {
            unset($views['mine']);
            $replacements = [
                'private' => __('Read', 'pwh-dcfh'),
                'draft' => __('Unread', 'pwh-dcfh')
            ];
            foreach ($replacements as $key => $label) {
                if (isset($views[$key])) {
                    $views[$key] = str_replace(ucfirst($key), $label, $views[$key]);
                }
            }

            return $views;
        }

        /**
         * Update Custom Post-Type Read By When Post-View
         */
        public function maybe_update_entry_read_by()
        {
            global $current_screen;
            if ($this->_post_type === $current_screen->post_type) {
                $post_id = isset($_GET['post']) ? (int)sanitize_text_field($_GET['post']) : null; // phpcs:ignore WordPress.Security.NonceVerification
                $post_current_status = get_post_status($post_id);
                $post_new_status = 'spam' === $post_current_status ? 'spam' : 'private';
                if (!is_null($post_id) && ('draft' === $post_current_status || 'spam' === $post_current_status)) {
                    $post = get_post($post_id);
                    if ('0000-00-00 00:00:00' === $post->post_modified) {
                        wp_update_post([
                            'ID' => $post_id,
                            'post_status' => $post_new_status,
                            'post_modified' => current_time('mysql'),
                            'post_modified_gmt' => current_time('mysql', 1),
                            'meta_input' => ['_pwh_dcfh_read_by' => get_current_user_id()],
                        ]);
                    }
                }
            }
        }

        /**
         * Register Custom Post Typee Bulk Actions
         *
         * @param $bulk_actions
         *
         * @return mixed
         */
        public function maybe_bulk_action($bulk_actions)
        {
            if (isset($_GET['post_status']) && 'trash' === sanitize_text_field($_GET['post_status'])) {  // phpcs:ignore WordPress.Security.NonceVerification
                return $bulk_actions;
            }
            unset($bulk_actions['edit']);
            if (current_user_can('perform_entry_actions_pwh_dcfh')) {
                $bulk_actions['mark_as_read'] = __('Mark as Read', 'pwh-dcfh');
                $bulk_actions['mark_as_unread'] = __('Mark as Unread', 'pwh-dcfh');
                $bulk_actions['mark_as_spam'] = __('Mark As Spam', 'pwh-dcfh');
            }
            if (current_user_can('delete_pwh_dcfhs')) {
                $bulk_actions['delete_permanently'] = __('Delete Permanently', 'pwh-dcfh');
            }

            return $bulk_actions;
        }

        /**
         * Register Custom Post-Type Bulk Actions Process
         *
         * @param $redirect_url
         * @param $doaction
         * @param $post_ids
         *
         * @return false|string
         */
        public function maybe_process_bulk_actions($redirect_url, $doaction, $post_ids)
        {
            $redirect = remove_query_arg(['mark_as_read', 'mark_as_unread', 'mark_as_spam', 'mark_as_not_spam', 'delete_permanently'], $redirect_url);
            if (current_user_can('perform_entry_actions_pwh_dcfh')) {
                if ('mark_as_read' === $doaction) {
                    foreach ($post_ids as $post_id) {
                        if (get_post_status($post_id) === 'draft') {
                            pwh_dcfh_db()::set_post_status_and_modified($post_id, 'private', current_time('mysql'), current_time('mysql', 1));
                        }
                    }
                    $redirect = add_query_arg('mark_as_read', count($post_ids), $redirect);
                }
                if ('mark_as_unread' === $doaction) {
                    foreach ($post_ids as $post_id) {
                        if (get_post_status($post_id) === 'private') {
                            pwh_dcfh_db()::set_post_status_and_modified($post_id);
                        }
                    }
                    $redirect = add_query_arg('mark_as_unread', count($post_ids), $redirect);
                }
                if ('mark_as_spam' === $doaction) {
                    foreach ($post_ids as $post_id) {
                        $sender_email = get_post_meta($post_id, '_pwh_dcfh_contact_email', true);
                        $modified_date = get_post_field('post_modified', $post_id);
                        $post_modified_gmt = get_post_field('post_modified_gmt', $post_id);
                        // 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', $modified_date, $post_modified_gmt);
                        }
                        pwh_dcfh_db()::update_posts_status_to_spam($sender_email);
                    }
                    $redirect = add_query_arg('mark_as_spam', count($post_ids), $redirect);
                }

            }
            if ('delete_permanently' === $doaction && current_user_can('delete_pwh_dcfhs')) {
                foreach ($post_ids as $post_id) {
                    wp_delete_post($post_id, true);
                }
                $redirect = add_query_arg('delete_permanently', count($post_ids), $redirect);
            }

            return $redirect;
        }

        /**
         * Register Custom Post-Type Single Action Process
         */
        public function maybe_process_row_action()
        {
            if (isset($_GET['_wpnonce'], $_GET['delete_entry']) && current_user_can('delete_pwh_dcfhs') && wp_verify_nonce(sanitize_text_field($_GET['_wpnonce']), 'delete_entry')) {
                $post_id = sanitize_text_field($_GET['delete_entry']);
                $post_obj = get_post($post_id);
                if (!is_wp_error($post_obj)) {
                    wp_delete_post($post_id, true);
                    wp_safe_redirect(admin_url('edit.php?post_type='.$this->_post_type));
                    exit;
                }
            }
            if (current_user_can('perform_entry_actions_pwh_dcfh')) {
                if (isset($_GET['_wpnonce'], $_GET['mark_as_spam']) && wp_verify_nonce(sanitize_text_field($_GET['_wpnonce']), 'mark_as_spam')) {
                    $post_id = sanitize_text_field($_GET['mark_as_spam']);
                    $post_obj = get_post($post_id);
                    if (!is_wp_error($post_obj)) {
                        $sender_email = get_post_meta($post_id, '_pwh_dcfh_contact_email', true);
                        $modified_date = get_post_field('post_modified', $post_id);
                        $post_modified_gmt = get_post_field('post_modified_gmt', $post_id);
                        // Mark Entry As Spam
                        if ('0000-00-00 00:00:00' === $modified_date && '0000-00-00 00:00:00' === $post_modified_gmt) {
                            pwh_dcfh_db()::set_post_status_and_modified($post_id, 'spam');
                        } else {
                            pwh_dcfh_db()::set_post_status_and_modified($post_id, 'spam', $modified_date, $post_modified_gmt);
                        }
                        pwh_dcfh_db()::update_posts_status_to_spam($sender_email);
                        $url = add_query_arg(
                            [
                                'post_type' => $this->_post_type,
                                'mark_as_spam' => $post_id,
                                'is_row_action' => true
                            ],
                            admin_url('edit.php')
                        );
                        wp_safe_redirect($url);
                        exit;
                    }
                }
                if (isset($_GET['_wpnonce'], $_GET['mark_as_not_spam']) && wp_verify_nonce(sanitize_text_field($_GET['_wpnonce']), 'mark_as_not_spam')) {
                    $post_id = sanitize_text_field($_GET['mark_as_not_spam']);
                    $post_obj = get_post($post_id);
                    if (!is_wp_error($post_obj)) {
                        $sender_email = get_post_meta($post_id, '_pwh_dcfh_contact_email', true);
                        $modified_date = get_post_field('post_modified', $post_id);
                        $post_modified_gmt = get_post_field('post_modified_gmt', $post_id);
                        // Mark Entry As Not Spam
                        if ('0000-00-00 00:00:00' === $modified_date && '0000-00-00 00:00:00' === $post_modified_gmt) {
                            $post_status = 'draft';
                            pwh_dcfh_db()::set_post_status_and_modified($post_id);
                        } else {
                            pwh_dcfh_db()::set_post_status_and_modified($post_id, 'private', $modified_date, $post_modified_gmt);
                            $post_status = 'private';
                        }
                        pwh_dcfh_db()::update_spam_posts_status($sender_email, $post_status);
                        $url = add_query_arg(
                            [
                                'post_type' => $this->_post_type,
                                'mark_as_not_spam' => $post_id,
                                'is_row_action' => true
                            ],
                            admin_url('edit.php')
                        );
                        wp_safe_redirect($url);
                        exit;
                    }
                }
            }

        }

        /**
         * Register Custom Post Type Bulk Action Messages
         */
        public function maybe_custom_bulk_action_message()
        {
            $singular = strtolower($this->_post_type_singular);
            $plural = strtolower($this->_post_type_plural);
            // phpcs:disable
            if (isset($_GET['mark_as_read'])) {
                $post_id = sanitize_text_field($_GET['mark_as_read']);
                $message = sprintf(_n("%s $singular marked as read.", "%s $plural marked as reads", $post_id, 'pwh-dcfh'), number_format_i18n($post_id));
                echo "<div class='updated'><p>".esc_html($message)."</p></div>";
            }
            if (isset($_GET['mark_as_unread'])) {
                $post_id = sanitize_text_field($_GET['mark_as_unread']);
                $message = sprintf(_n("%s $singular marked as unread.", "%s $plural marked as unreads", $post_id, 'pwh-dcfh'), number_format_i18n($post_id));
                echo "<div class='updated'><p>".esc_html($message)."</p></div>";
            }
            if (isset($_GET['mark_as_spam'])) {
                $post_id = sanitize_text_field($_GET['mark_as_spam']);
                if (empty(get_post_status($post_id))) {
                    $message = sprintf(_n("%s $singular marked as spam.", "%s $plural marked as spams", $post_id, 'pwh-dcfh'), number_format_i18n($post_id));
                } else {
                    $message = sprintf(ucfirst($singular).__(" #%s marked as spam.", 'pwh-dcfh'), $post_id);
                }
                echo "<div class='updated error'><p>".esc_html($message)."</p></div>";
            }
            if (isset($_GET['mark_as_not_spam'])) {
                $post_id = sanitize_text_field($_GET['mark_as_not_spam']);
                $message = sprintf(ucfirst($singular).__(" #%s marked as not a spam.", 'pwh-dcfh'), $post_id);
                echo "<div class='updated'><p>".esc_html($message)."</p></div>";
            }
            if (isset($_GET['delete_permanently'])) {
                $post_id = sanitize_text_field($_GET['delete_permanently']);
                $message = sprintf(_n("%s $singular permanently deleted.", "%s $plural permanently deleted.", $post_id, 'pwh-dcfh'), number_format_i18n($post_id));
                echo "<div class='updated'><p>".esc_html($message)."</p></div>";
            }
            // phpcs:enable
        }

        /**
         * Resgiter Custom Post-Type Bulk Action Update Messages
         *
         * @param $bulk_messages
         * @param $bulk_counts
         *
         * @return mixed
         */
        public function maybe_bulk_update_message($bulk_messages, $bulk_counts)
        {
            $singular = strtolower($this->_post_type_singular);
            $plural = strtolower($this->_post_type_plural);
            $bulk_messages[$this->_post_type] = [
                'updated' => _n("%s $singular updated.", "%s $plural updated.", $bulk_counts["updated"], 'pwh-dcfh'),
                'locked' => _n("%s $singular not updated, somebody is editing it.", "%s $plural not updated, somebody is editing them.", $bulk_counts["locked"], 'pwh-dcfh'),
                'deleted' => _n("%s $singular permanently deleted.", "%s $plural permanently deleted.", $bulk_counts["deleted"], 'pwh-dcfh'),
                'trashed' => _n("%s $singular moved to the Trash.", "%s $plural moved to the Trash.", $bulk_counts["trashed"], 'pwh-dcfh'),
                'untrashed' => _n("%s $singular restored from the Trash.", "%s $plural restored from the Trash.", $bulk_counts["untrashed"], 'pwh-dcfh'),
            ];

            return $bulk_messages;
        }

        /**
         * Register Custom Post-Type Row Action
         *
         * @param $actions
         * @param $post
         *
         * @return mixed
         */
        public function maybe_post_row_actions($actions, $post)
        {
            if (isset($_GET['post_status']) && 'trash' === sanitize_text_field($_GET['post_status'])) {   // phpcs:ignore WordPress.Security.NonceVerification
                return $actions;
            }
            if ($this->_post_type === get_post_type()) {
                unset($actions['inline hide-if-no-js']);
                if (isset($actions['edit'])) {
                    $actions['edit'] = str_replace('Edit', esc_html__('View', 'pwh-dcfh'), $actions['edit']);
                }
                if (current_user_can('perform_entry_actions_pwh_dcfh')) {
                    if ('spam' === $post->post_status) {
                        $url = esc_url(wp_nonce_url(add_query_arg('mark_as_not_spam', $post->ID), 'mark_as_not_spam'));
                        $actions['not-spam-entry'] = sprintf('<a href="%1$s" onclick="return confirm(\'%2$s\')">%3$s</a>', $url, __('Are you sure want to mark this entry not spam?', 'pwh-dcfh'), __('Not Spam', 'pwh-dcfh'));
                    }
                    if ('spam' !== $post->post_status) {
                        $url = esc_url(wp_nonce_url(add_query_arg(['mark_as_spam' => $post->ID, 'is_row_action' => true]), 'mark_as_spam'));
                        $actions['spam-entry'] = sprintf('<a href="%1$s" onclick="return confirm(\'%2$s\')">%3$s</a>', $url, __('Are you sure want to mark this entry spam?', 'pwh-dcfh'), __('Spam', 'pwh-dcfh'));
                    }
                }
                if (current_user_can('delete_pwh_dcfhs')) {
                    $url = esc_url(wp_nonce_url(add_query_arg('delete_entry', $post->ID), 'delete_entry'));
                    $actions['delete-entry'] = sprintf('<a href="%1$s" onclick="return confirm(\'%2$s\')">%3$s</a>', $url, __('Are you sure want to delete this entry permanently?', 'pwh-dcfh'), __('Delete', 'pwh-dcfh'));
                }
                if (isset($actions['trash']) && !current_user_can('delete_pwh_dcfhs')) {
                    unset($actions['trash']);
                }
            }

            return $actions;
        }

        /**
         * Register Admin Title
         * @return array|mixed|string|string[]|void
         */
        public function maye_change_admin_title($admin_title, $title)
        {
            global $post, $action, $current_screen;
            if (isset($current_screen->post_type) && $current_screen->post_type === 'pwh_dcfh' && $action === 'edit') {
                $admin_title = self::clean_title($post->post_title); // phpcs:ignore
            }

            return $admin_title;
        }

        /**
         * Register Custom Post-Type Admin Hooks
         */
        public function maye_change_post_title()
        {
            global $post, $title, $action, $current_screen;
            if (isset($current_screen->post_type) && $current_screen->post_type === $this->_post_type && $action === 'edit') {
                $title = self::clean_title($post->post_title); // phpcs:ignore
            }
        }

        /**
         * Deregister Custom Post Type Scripts Dragdrop
         */
        public function maybe_deregister_script()
        {
            if ('post.php' === $this->_pagenow && (isset($_GET['post']) && $this->_post_type === get_post_type(sanitize_text_field($_GET['post'])))) {  // phpcs:ignore WordPress.Security.NonceVerification
                remove_meta_box('submitdiv', $this->_post_type, 'side');
                remove_meta_box('authordiv', $this->_post_type, 'normal');
                wp_deregister_script('postbox');
                wp_dequeue_script('autosave');
            }
        }

        /**
         * Register Custom Post-Type Menu New Entry Count
         */
        public function maybe_menu_hooks()
        {
            global $menu;
            $drafts = wp_count_posts('pwh_dcfh')->draft;
            if ($drafts > 0) {
                $menu_index = 0;
                array_walk($menu, function ($val, $key) use (&$menu_index) {
                    if (array_key_exists("edit.php?post_type=".$this->_post_type, array_flip($val))) {
                        $menu_index = $key;
                    }
                });
                if (isset($menu[$menu_index][0])) {
                    $menu[$menu_index][0] = sprintf('%s<span class="awaiting-mod">%s</span>', $menu[$menu_index][0], $drafts);  // phpcs:ignore
                }
            }
        }

        /**
         * Making Custom Post-Type Columns Sortable
         *
         * @param $columns
         *
         * @return mixed
         */
        public function maybe_sortable_columns($columns)
        {
            $columns['pwh_dcfh_entry_id'] = 'pwh_dcfh_entry_id';
            $columns['pwh_dcfh_entry_date'] = 'pwh_dcfh_entry_date';
            $columns['pwh_dcfh_contact_form_id'] = 'pwh_dcfh_contact_form_id';
            $columns['pwh_dcfh_user_email'] = 'pwh_dcfh_user_email';

            return $columns;
        }

        /**
         * Filter Data From Custom Post-Type Columns
         *
         * @param $query
         *
         * @return mixed
         */
        public function maybe_parse_query($query)
        {
            if (!is_admin()) {
                return $query;
            }
            $q_post_type = $query->query['post_type'] ?? '';
            if ($this->_post_type === $q_post_type) {
                $contact_form_id = isset($_GET['contact_form_id']) ? sanitize_text_field($_GET['contact_form_id']) : null;  // phpcs:ignore WordPress.Security.NonceVerification
                if (!empty($contact_form_id)) {
                    $query->set('meta_key', '_pwh_dcfh_contact_form_id');
                    $query->set('meta_value', $contact_form_id);
                    $query->set('meta_type', 'meta_value');
                }
                if ('pwh_dcfh_contact_form_id' === $query->get('orderby')) {
                    $query->set('orderby', 'meta_value');
                    $query->set('meta_key', '_pwh_dcfh_contact_form_id');
                    $query->set('meta_type', 'meta_value');
                }
                if ('pwh_dcfh_user_email' === $query->get('orderby')) {
                    $query->set('orderby', 'meta_value');
                    $query->set('meta_key', '_pwh_dcfh_contact_email');
                }
            }

            return $query;
        }

        /**
         * Register Custom Post Type Filters
         *
         * @param $post_type
         * @param $which
         */
        public function maybe_manage_posts($post_type, $which)
        {
            if ('pwh_dcfh' === $post_type) {
                $contact_forms = pwh_dcfh_db()::get_contact_forms_list();
                $selected_contact_form_id = isset($_GET['contact_form_id']) ? sanitize_text_field($_GET['contact_form_id']) : null; // phpcs:ignore WordPress.Security.NonceVerification
                echo "<select name='contact_form_id' id='contact_form_id' class='postform'>";
                echo "<option value=''>".esc_html__('Contact Forms', 'pwh-dcfh')."</option>";
                if (!empty($contact_forms)) {
                    foreach ($contact_forms as $contact_form) {
                        $contact_form_id = $contact_form['unique_id'];
                        $contact_form_title = $contact_form['title'];
                        echo '<option value="'.esc_attr($contact_form_id).'" '.selected($selected_contact_form_id, esc_html($contact_form_id), false).'>'.esc_html($contact_form_title).'</option>';
                    }
                }
                echo "</select>";
            }
        }

        /**
         * Register Export CSV Button On Custom Post Type
         *
         * @param $which
         *
         * @return mixed|string
         */
        public function maybe_extra_table_nav($which)
        {
            global $current_screen;
            if (('top' === $which) && $this->_post_type === $current_screen->post_type && current_user_can('export_csv_pwh_dcfh')) {
                $wp_count_posts = wp_count_posts($this->_post_type);
                $total_posts = (int)($wp_count_posts->draft + $wp_count_posts->private);
                if (0 === $total_posts) {
                    return $which;
                }
                $contact_form_id = isset($_GET['contact_form_id']) ? sanitize_text_field($_GET['contact_form_id']) : ''; // phpcs:ignore WordPress.Security.NonceVerification
                $query_args = ['post_type' => $this->_post_type, 'page' => 'export_as_csv'];
                if (!empty($contact_form_id)) {
                    $query_args['contact_form_id'] = $contact_form_id;
                }
                $csv_export_url = add_query_arg($query_args, admin_url('edit.php'));
                printf(
                    '<a href="%1$s" class="button button-primary export-csv-btn">%2$s</a>',
                    esc_url($csv_export_url),
                    esc_html__('Export CSV', 'pwh-dcfh')
                );
            }

            return $which;
        }

        /**
         * Get Custom Post-Type Read Meta-Key
         *
         * @param int $post_id
         *
         * @return string
         */
        private static function is_read($post_id)
        {
            $post_modified = get_post_field('post_modified', $post_id);
            $output = '';
            if ($post_modified === '0000-00-00 00:00:00') {
                $output .= "<span class='dashicons dashicons-email'></span>";
            } else {
                $post_read_by = pwh_dcfh_wp_helpers()::get_author_name(
                    pwh_dcfh_post_meta_handler()::get_read_by_meta_value($post_id)
                );
                $post_modified = pwh_dcfh_wp_helpers()::datetime($post_modified);
                $output .= sprintf(
                    '<div><span>%1$s</span><span>%2$s</span></div>',
                    esc_html__("Read By: $post_read_by", 'pwh-dcfh'),
                    esc_html($post_modified)
                );
            }

            return $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }

        /**
         * Remove Screen Option
         *
         * @param $show_screen
         * @param $screen
         *
         * @return bool
         */
        public function maybe_remove_screen_options($show_screen, $screen)
        {
            if ($this->_post_type === $screen->id) {  // phpcs:ignore WordPress.Security.NonceVerification
                return false;
            }

            return $show_screen;
        }

        /**
         * Delete records when post delete
         *
         * @param $post_id
         *
         * @return mixed
         */
        public function maybe_before_delete($post_id)
        {
            if ('pwh_dcfh' !== get_post_type($post_id)) {
                return $post_id;
            }
            $post_excerpt = get_post_field('post_excerpt', $post_id);
            $contact_form_id = pwh_dcfh_post_meta_handler()::get_contact_form_id_meta_value($post_id);
            if (is_serialized($post_excerpt)) {
                $form_entries = pwh_dcfh_helpers()::maybe_unserialize($post_excerpt);
                if (!empty($form_entries) && is_array($form_entries)) {
                    foreach ($form_entries as $form_entry) {
                        $form_value = $form_entry['value'];
                        $wp_subdir = isset($form_entry['subdir']) ? esc_html($form_entry['subdir']) : '';
                        if ('file' === $form_entry['type']) {
                            $attachments = explode(',', $form_value);
                            if (!empty($attachments) && !empty($wp_subdir)) {
                                foreach ($attachments as $attachment) {
                                    $this->delete_file($attachment, $contact_form_id, $wp_subdir);
                                }
                            }
                        }
                        if ('signature_pad' === $form_entry['type'] && !empty($wp_subdir)) {
                            $this->delete_file($form_value, $contact_form_id, $wp_subdir);
                        }
                        if (isset($form_entry['is_media_library']) && $form_entry['is_media_library']) {
                            $attachments = get_attached_media('', $post_id);
                            foreach ($attachments as $attachment) {
                                wp_delete_attachment($attachment->ID, 'true');
                            }
                        }
                    }
                    // Delete Sent Email Logs
                    pwh_dcfh_logger()->delete_logs('sent_email_log', $post_id);
                }
            }
            // Update Contact Form Entries
            $contact_form_id = pwh_dcfh_post_meta_handler()::get_contact_form_id_meta_value($post_id);
            $contact_form_entries = pwh_dcfh_db()::get_contact_form_total_entries($contact_form_id);
            $contact_form_entries = $contact_form_entries - 1;
            pwh_dcfh_db()::update_contact_form_total_entries($contact_form_id, $contact_form_entries);

            return $post_id;
        }

        /**
         * Clean Post Title
         *
         * @param $title
         *
         * @return string
         */
        private static function clean_title($title)
        {
            $title = str_replace('-', '# ', $title);

            return sprintf(__("%s Details", 'pwh-dcfh'), ucfirst($title));
        }

        /**
         * Delete Files
         *
         * @param $form_value
         * @param $contact_form_id
         * @param  $wp_subdir
         *
         * @return void
         */
        private function delete_file($form_value, $contact_form_id, $wp_subdir)
        {
            $upload_dir = pwh_dcfh_file_helpers()::get_form_upload_dir($contact_form_id, $wp_subdir, $form_value);
            if (et_()->WPFS()->is_file($upload_dir) && et_()->WPFS()->exists($upload_dir)) {
                wp_delete_file($upload_dir);
            }
            $upload_tmp_dir = path_join(pwh_dcfh_file_helpers()::get_tmp_upload_dir(), $form_value);
            if (et_()->WPFS()->is_file($upload_tmp_dir) && et_()->WPFS()->exists($upload_tmp_dir)) {
                wp_delete_file($upload_tmp_dir);
            }
        }
    }
}