<?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('IAFWZC_Error_Log_Extend')) {
    class IAFWZC_Error_Log_Extend extends WP_List_Table
    {
        public function __construct()
        {
            parent::__construct([
                'singular' => __('Error Log', 'integrate-any-form-with-zoho-crm'),
                'plural'   => __('Error Logs', 'integrate-any-form-with-zoho-crm'),
                'ajax'     => false,
            ]);
        }

        public function get_columns()
        {
            $columns = [
                'cb'              => '<input type="checkbox" />', // Checkbox column for bulk actions
                'status_icon'             => '',
                'sno'             => __('S.No', 'integrate-any-form-with-zoho-crm'),
                'integration_name' => __('Integration Name', 'integrate-any-form-with-zoho-crm'),
                'error_type'      => __('Error Type', 'integrate-any-form-with-zoho-crm'),
                'resync_attempt'  => __('Resync Attempt', 'integrate-any-form-with-zoho-crm'),
                'created_at'      => __('Created At', 'integrate-any-form-with-zoho-crm'),
                'action'          => __('Action', 'integrate-any-form-with-zoho-crm'),
            ];
            return $columns;
        }

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


        public function prepare_items()
        {
            $IAFWZC_Error_LogDBInstance = new IAFWZC_Error_Log();

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

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

            $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 = $IAFWZC_Error_LogDBInstance->get_all_error_logs_with_timefilter($time_filter);
            } else {
                $error_log_items = $IAFWZC_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'])) : 'created_at'; // Default order by `created_at`
            $order = isset($_GET['order']) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'asc'; // 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 = 10;
            $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="iafwzc-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 $count++;
        }

        protected function column_integration_name($item)
        {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
            $integration_id = isset($item->integration_id) ? $item->integration_id : null;
            $integration_name = $integration_id ? $IAFWZC_Field_MappingDBInstance->get_integration_name($integration_id) : null;
            return $integration_name ? esc_html($integration_name) : __('N/A', 'integrate-any-form-with-zoho-crm');
        }

        protected function column_error_type($item)
        {
            return isset($item->error_type) ? esc_html($item->error_type) : __('Unknown', 'integrate-any-form-with-zoho-crm');
        }

        protected function column_resync_attempt($item)
        {
            return isset($item->retry_count) ? esc_html($item->retry_count) : __('0', 'integrate-any-form-with-zoho-crm');
        }

        protected function column_created_at($item)
        {
            return isset($item->created_at) ? esc_html($item->created_at) : __('Not available', 'integrate-any-form-with-zoho-crm');
        }

        protected function column_action($item)
        {
            $session = iafwzc_is_valid_key();
            $resync_url = add_query_arg([
                'page'      => 'integrate-any-form-with-zoho-crm',
                'tab'       => 'errorlog',
                'action'    => '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-any-form-with-zoho-crm',
                '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(
            //     '<a href="#" onclick="alert(\'Upgrade to the premium version to use the resync option. This feature is not available in the free version.\'); return false;" 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="iafwzc_showErrorDetails(%d)"></span>',
            //     __('Resync', 'integrate-any-form-with-zoho-crm'),
            //     esc_url($delete_url),
            //     __('Delete', 'integrate-any-form-with-zoho-crm'),
            //     intval($item->id)
            // );
            return sprintf(
                '<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="iafwzc_showErrorDetails(%d)"></span>',
                esc_url($resync_url),
                esc_attr($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-any-form-with-zoho-crm'),
                esc_url($delete_url),
                __('Delete', 'integrate-any-form-with-zoho-crm'),
                intval($item->id)
            );
        }

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

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

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'iafwzc_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrate-any-form-with-zoho-crm'));
                }
            }
            // 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) {
                $IAFWZC_Error_LogDBInstance = new IAFWZC_Error_Log();
                // Handle delete action
                if (!empty($log_ids)) {
                    foreach ($log_ids as $log_id) {
                        $IAFWZC_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 = iafwzc_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
                iafwzc_bulk_resync($log_ids); // Call the bulk resync function
                //
                $message = get_transient('iafwzc_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('iafwzc_error_log_success');
                }
                // Retrieve the transient.
                $message = get_transient('iafwzc_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('iafwzc_error_log_fail');
                }
                return;
            }

            return;
        }


        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 error logs? This action cannot be undone.');">
                        Delete All Error Logs
                    </button>



                </div>

            <?php
            }
        }


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

        protected function display_tablenav($which)
        {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
            $IAFWZC_Error_LogDBInstance = new IAFWZC_Error_Log();

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

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

            $integration_id_list = $IAFWZC_Error_LogDBInstance->get_unique_integration_ids(); // Get unique integration IDs
            $error_type_list = $IAFWZC_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-any-form-with-zoho-crm'); ?></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 = $IAFWZC_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 Error Types', 'integrate-any-form-with-zoho-crm'); ?></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-any-form-with-zoho-crm'); ?></option>
                        <option value="today" <?php selected($time_filter, 'today'); ?>><?php esc_html_e('Today', 'integrate-any-form-with-zoho-crm'); ?></option>
                        <option value="yesterday" <?php selected($time_filter, 'yesterday'); ?>><?php esc_html_e('Yesterday', 'integrate-any-form-with-zoho-crm'); ?></option>
                        <option value="last_7_days" <?php selected($time_filter, 'last_7_days'); ?>><?php esc_html_e('Last 7 Days', 'integrate-any-form-with-zoho-crm'); ?></option>
                        <option value="last_30_days" <?php selected($time_filter, 'last_30_days'); ?>><?php esc_html_e('Last 30 Days', 'integrate-any-form-with-zoho-crm'); ?></option>
                    </select>

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

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


                </div>
            <?php
            } ?>


            <div class="tablenav <?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
        }
    }
}
