<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit; // Prevent direct access to the file.
}

if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

// Check if the class already exists to avoid redeclaration.
if (!class_exists('IAFWZCAI_Error_Log_Extend')) {
    class IAFWZCAI_Error_Log_Extend extends WP_List_Table
    {
        protected $cache_key = 'iafwzcai_all_error_log_data';

        public function __construct()
        {
            parent::__construct([
                'singular' => __('Error Log', 'integrate-with-zoho-campaigns'),
                'plural'   => __('Error Logs', 'integrate-with-zoho-campaigns'),
                'ajax'     => false,
            ]);
        }

        public function get_columns()
        {
            $columns = [
                'cb'              => '<input type="checkbox" />', // Checkbox column for bulk actions
                'status_icon'             => '',
                'sno'             => __('S.No', 'integrate-with-zoho-campaigns'),
                'integration_name' => __('Integration', 'integrate-with-zoho-campaigns'),
                'error_type'      => __('Status', 'integrate-with-zoho-campaigns'),
                'error_message'  => __('Message', 'integrate-with-zoho-campaigns'),
                'updated_at'      => __('Time', 'integrate-with-zoho-campaigns'),
                'action'          => __('Action', 'integrate-with-zoho-campaigns'),
            ];
            return $columns;
        }

        public function get_sortable_columns()
        {
            return [
                'updated_at' => ['updated_at', true],
                'resync_attempt' => ['resync_attempt', true],
            ];
        }


        public function prepare_items()
        {
            $IAFWZCAI_Error_LogDBInstance = new IAFWZCAI_Error_Log();

            // Security check: Verify the nonce if the form was submitted
            if (isset($_POST['iafwzcai_error_log_form_action_nonce'])) {
                // Sanitize the nonce input
                $nonce = sanitize_text_field(wp_unslash($_POST['iafwzcai_error_log_form_action_nonce']));

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'iafwzcai_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrate-with-zoho-campaigns'));
                }
            }

            $this->process_bulk_action(); // Process bulk actions
            $columns  = $this->get_columns();
            $hidden   = [];
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = [$columns, $hidden, $sortable];

            // Retrieve error log data
            $time_filter = isset($_POST['time_filter']) ? sanitize_text_field(wp_unslash($_POST['time_filter'])) : null;
            if ($time_filter) {
                $error_log_items = $IAFWZCAI_Error_LogDBInstance->get_all_error_logs_with_timefilter($time_filter);
            } else {
                $error_log_items = $IAFWZCAI_Error_LogDBInstance->get_all_error_logs();
            }


            if (!is_array($error_log_items) || empty($error_log_items)) {
                $error_log_items = [];
            }

            // Apply Filters
            $error_type_filter = isset($_POST['error_type_filter']) ? sanitize_text_field(wp_unslash($_POST['error_type_filter'])) : '';
            $integration_filter = isset($_POST['integration_filter']) ? intval(wp_unslash($_POST['integration_filter'])) : 0;

            if (!empty($error_type_filter)) {
                $error_log_items = array_filter($error_log_items, function ($item) use ($error_type_filter) {
                    return isset($item->error_type) && $item->error_type === $error_type_filter;
                });
            }

            if (!empty($integration_filter)) {
                $error_log_items = array_filter($error_log_items, function ($item) use ($integration_filter) {
                    return isset($item->integration_id) && intval($item->integration_id) === $integration_filter;
                });
            }

            // Sorting
            // Sanitize and unslash the `orderby` and `order` parameters
            $orderby = isset($_GET['orderby']) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : 'updated_at'; // Default order by `updated_at`
            $order = isset($_GET['order']) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'desc'; // Default order direction `asc`

            usort($error_log_items, function ($a, $b) use ($orderby, $order) {
                $value1 = $a->{$orderby} ?? '';
                $value2 = $b->{$orderby} ?? '';

                if ($value1 == $value2) {
                    return 0;
                }

                if ($order === 'asc') {
                    return ($value1 < $value2) ? -1 : 1;
                } else {
                    return ($value1 > $value2) ? -1 : 1;
                }
            });

            // Pagination parameters
            $per_page = 20;
            $current_page = $this->get_pagenum();
            $total_items = count($error_log_items);

            // Slice items for the current page
            $error_log_items = array_slice($error_log_items, (($current_page - 1) * $per_page), $per_page);
            $this->items = $error_log_items;

            $this->set_pagination_args([
                'total_items' => $total_items,
                'per_page'    => $per_page,
                'total_pages' => ceil($total_items / $per_page),
            ]);
        }



        // Checkbox column content
        protected function column_cb($item)
        {
            return sprintf(
                '<input type="checkbox" name="log_ids[]" value="%s" />',
                esc_attr($item->id)
            );
        }
        protected function column_status_icon($item)
        {
            $error_type = isset($item->error_type) ? esc_html($item->error_type) : __('Unknown', 'integrate-with-zoho-campaigns');

            if ($error_type === 'SUCCESS') {
                return '<div class="iafwzcai-log-tick"></div>';
            } else {
                return '<div class="iafwzcai-log-close"></div>';
            }
        }

        protected function column_sno($item)
        {
            $per_page = $this->get_pagination_arg('per_page');
            $current_page = $this->get_pagenum();
            static $count;

            if (!$count) {
                $count = ($current_page - 1) * $per_page + 1;
            }

            return sprintf('<span style="font-size:11px;">%d</span>', $count++);
        }


        protected function column_integration_name($item)
        {
            $IAFWZCAI_Field_MappingDBInstance = new IAFWZCAI_Field_Mapping();
            $integration_id = isset($item->integration_id) ? $item->integration_id : null;
            $integration_name = $integration_id ? $IAFWZCAI_Field_MappingDBInstance->get_integration_name($integration_id) : null;

            return sprintf(
                '<span style="font-size:11px;">%s</span>',
                esc_html($integration_name ? $integration_name : __('N/A', 'integrate-with-zoho-campaigns'))
            );
        }

        protected function column_error_type($item)
        {
            return sprintf(
                '<span style="font-size:11px;">%s</span>',
                esc_html(isset($item->error_type) ? $item->error_type : __('Unknown', 'integrate-with-zoho-campaigns'))
            );
        }

        protected function column_error_message($item)
        {
            if (!isset($item->error_type) || esc_html($item->error_type) === 'SUCCESS') {
                return '<span style="font-size:11px;">-</span>';
            }

            // Ensure $api_response is an array
            $api_response = is_string($item->api_response) ? json_decode($item->api_response, true) : $item->api_response;

            $error_message = (!empty($api_response['body']['message'])) ? esc_html($api_response['body']['message']) : "-";

            return sprintf('<span style="font-size:11px;">%s</span>', $error_message);
        }

        protected function column_updated_at($item)
        {
            return sprintf(
                '<span style="font-size:11px;">%s</span>',
                esc_html(isset($item->updated_at) ? $item->updated_at : __('Not available', 'integrate-with-zoho-campaigns'))
            );
        }


        protected function column_action($item)
        {
            $session = iafwzcai_is_valid_key();
            $resync_url = add_query_arg([
                'page'      => 'integrate-with-zoho-campaigns',
                'tab'       => 'errorlog',
                'action'    => 'iafwzcai_resync',
                'log_id'    => isset($item->id) ? intval($item->id) : '',
                '_wpnonce'  => wp_create_nonce('resync_error_log_' . $item->id),
            ], admin_url('admin.php'));

            $delete_url = add_query_arg([
                'page'      => 'integrate-with-zoho-campaigns',
                'tab'       => 'errorlog',
                'de_log_id' => isset($item->id) ? intval($item->id) : '',
                '_wpnonce'  => wp_create_nonce('delete_error_log_' . $item->id),
            ], admin_url('admin.php'));

            return sprintf(
                '<span style="font-size:11px;">
                    <a href="%s" onclick="%s" style="color: #2271b1;">%s</a> | 
                    <a href="%s" onclick="return confirm(\'Are you sure you want to delete this error log?\');" style="color: #b32d2e;">%s</a> |
                    <span class="dashicons dashicons-media-text" style="color: #a0a0a0; cursor: pointer;" title="View More Details" onclick="iafwzcai_showErrorDetails(%d)"></span>
                </span>',
                esc_url($resync_url),
                $session ? '' : 'alert(\'Upgrade to the premium version to use the resync option. This feature is not available in the free version.\'); return false;',
                __('Resync', 'integrate-with-zoho-campaigns'),
                esc_url($delete_url),
                __('Delete', 'integrate-with-zoho-campaigns'),
                intval($item->id)
            );
        }


        public function get_bulk_actions()
        {
            $actions = [
                'resync' => __('Resync', 'integrate-with-zoho-campaigns'),
                'delete' => __('Delete', 'integrate-with-zoho-campaigns'),
            ];
            return $actions;
        }

        public function process_bulk_action()
        {
            // Security check: Verify the nonce if the form was submitted
            if (isset($_POST['iafwzcai_error_log_form_action_nonce'])) {
                // Sanitize the nonce input
                $nonce = sanitize_text_field(wp_unslash($_POST['iafwzcai_error_log_form_action_nonce']));

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'iafwzcai_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrate-with-zoho-campaigns'));
                }
            }
            // Retrieve the current action
            $action = $this->current_action();

            // Ensure log IDs are retrieved and sanitized
            $log_ids = isset($_REQUEST['log_ids']) ? array_map('intval', (array) wp_unslash($_REQUEST['log_ids'])) : [];

            if ('delete' === $action) {
                $IAFWZCAI_Error_LogDBInstance = new IAFWZCAI_Error_Log();
                // Handle delete action
                if (!empty($log_ids)) {
                    foreach ($log_ids as $log_id) {
                        $IAFWZCAI_Error_LogDBInstance->delete_error_log($log_id); // Call the delete function
                    }
                }

                // Redirect to the current page after the action
                echo '<div class="notice notice-success is-dismissible">
                <p>' . esc_html('Selected logs deleted successfully') . '</p>
              </div>';

                return;
                //
            } elseif ('resync' === $action) {
                $session = iafwzcai_is_valid_key();
                if (!$session) {
                    echo '<div class="notice notice-error is-dismissible">
                    <p>' . esc_html('Upgrade to the premium version to use the bulk resync option. This feature is not available in the free version.') . '</p>
                  </div>';
                    return;
                }
                // Handle resync action
                iafwzcai_bulk_resync($log_ids); // Call the bulk resync function
                //
                $message = get_transient('iafwzcai_error_log_success');
                // If there is a message, display it as an admin notice.
                if ($message) {
                    echo '<div class="notice notice-success is-dismissible">
                <p>' . esc_html($message) . '</p>
              </div>';

                    // Delete the transient after displaying the message.
                    delete_transient('iafwzcai_error_log_success');
                }
                // Retrieve the transient.
                $message = get_transient('iafwzcai_error_log_fail');

                // If there is a message, display it as an admin notice.
                if ($message) {
                    echo '<div class="notice notice-error is-dismissible">
                  <p>' . esc_html($message) . '</p>
                </div>';

                    // Delete the transient after displaying the message.
                    delete_transient('iafwzcai_error_log_fail');
                }
                return;
            }

            return;
        }


        public function clear_cache()
        {
            wp_cache_delete($this->cache_key);
        }

        public function extra_tablenav($which)
        {
            if ($which == 'top') {
?>
                <div class="alignleft actions">


                    <!-- Delete All Button -->
                    <button type="submit" name="bulk_delete_all" value="delete_all" class="button action" onclick="return confirm('Are you sure you want to delete all logs? This action cannot be undone.');">
                        Delete All Logs
                    </button>
                    <!-- Delete Success Button -->
                    <button type="submit" name="bulk_delete_all_success" value="delete_all_success" class="button action" onclick="return confirm('Are you sure you want to delete all successfully added records? This action cannot be undone.');">
                        Delete All Success Logs
                    </button>


                </div>

            <?php
            }
        }


        public function no_items()
        {
            esc_html_e('No error logs found.', 'integrate-with-zoho-campaigns');
        }

        protected function display_tablenav($which)
        {
            $IAFWZCAI_Field_MappingDBInstance = new IAFWZCAI_Field_Mapping();
            $IAFWZCAI_Error_LogDBInstance = new IAFWZCAI_Error_Log();

            // Security check: Verify the nonce if the form was submitted
            if (isset($_POST['iafwzcai_error_log_form_action_nonce'])) {
                // Sanitize the nonce input
                $nonce = sanitize_text_field(wp_unslash($_POST['iafwzcai_error_log_form_action_nonce']));

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'iafwzcai_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrate-with-zoho-campaigns'));
                }
            }

            $integration_id_list = $IAFWZCAI_Error_LogDBInstance->get_unique_integration_ids(); // Get unique integration IDs
            $error_type_list = $IAFWZCAI_Error_LogDBInstance->get_unique_error_types();

            // $integration_list now contains the names of integrations with error logs.

            if ($which == 'top') {
            ?>

                <div class="alignright actions" style="padding-bottom:15px;">
                    <!-- Integration List Filter -->
                    <select name="integration_filter">
                        <option value=""><?php esc_html_e('All Integrations', 'integrate-with-zoho-campaigns'); ?></option>
                        <?php
                        $integration_filter = isset($_POST['integration_filter']) ? sanitize_text_field(wp_unslash($_POST['integration_filter'])) : '';
                        foreach ($integration_id_list as $integration_id) :
                            $integration_name = $IAFWZCAI_Field_MappingDBInstance->get_integration_name($integration_id); // Fetch integration name
                            if ($integration_name) : // Ensure the name is valid
                        ?>
                                <option value="<?php echo esc_attr($integration_id); ?>" <?php selected($integration_filter, $integration_id); ?>>
                                    <?php echo esc_html($integration_name); ?>
                                </option>
                        <?php endif;
                        endforeach; ?>
                    </select>

                    <!-- Error Type -->
                    <select name="error_type_filter">
                        <option value=""><?php esc_html_e('All Status', 'integrate-with-zoho-campaigns'); ?></option>
                        <?php
                        $error_type_filter = isset($_POST['error_type_filter']) ? sanitize_text_field(wp_unslash($_POST['error_type_filter'])) : '';
                        foreach ($error_type_list as $error_type) : ?>
                            <option value="<?php echo esc_attr($error_type); ?>" <?php selected($error_type_filter, $error_type); ?>>
                                <?php echo esc_html($error_type); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <!-- Time Filter -->
                    <?php
                    // Sanitize and unslash the input for time_filter
                    $time_filter = isset($_POST['time_filter']) ? sanitize_text_field(wp_unslash($_POST['time_filter'])) : '';
                    ?>

                    <select name="time_filter">
                        <option value=""><?php esc_html_e('All Time', 'integrate-with-zoho-campaigns'); ?></option>
                        <option value="today" <?php selected($time_filter, 'today'); ?>><?php esc_html_e('Today', 'integrate-with-zoho-campaigns'); ?></option>
                        <option value="yesterday" <?php selected($time_filter, 'yesterday'); ?>><?php esc_html_e('Yesterday', 'integrate-with-zoho-campaigns'); ?></option>
                        <option value="last_7_days" <?php selected($time_filter, 'last_7_days'); ?>><?php esc_html_e('Last 7 Days', 'integrate-with-zoho-campaigns'); ?></option>
                        <option value="last_30_days" <?php selected($time_filter, 'last_30_days'); ?>><?php esc_html_e('Last 30 Days', 'integrate-with-zoho-campaigns'); ?></option>
                    </select>

                    <!-- Submit Button -->
                    <button type="submit" class="button"><?php esc_html_e('Filter', 'integrate-with-zoho-campaigns'); ?></button>

                    <!-- Reset Button -->
                    <button type="button" class="button" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=errorlog')); ?>'">
                        <?php esc_html_e('Reset', 'integrate-with-zoho-campaigns'); ?>
                    </button>


                </div>
            <?php
            } ?>


            <div class="tablenav top <?php echo esc_attr($which); ?>">

                <div class="alignleft actions bulkactions">
                    <?php $this->bulk_actions($which); ?>
                </div>
                <?php if ($which == 'top') : ?>
                    <div class="alignleft actions">
                        <?php $this->extra_tablenav($which); ?>
                    </div>
                <?php endif; ?>
                <?php $this->pagination($which); ?>
                <br class="clear" />
            </div>

<?php
        }
    }
}
