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

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

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


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

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

            $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 = $integrazo_fwcrm_form_errorLogDBInstance->get_all_error_logs_with_timefilter($time_filter);
            } else {
                $error_log_items = $integrazo_fwcrm_form_errorLogDBInstance->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 = 15;
            $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)
        {
            return '<div class="integrazo_fwcrm_form-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)
        {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
            $integration_id = isset($item->integration_id) ? $item->integration_id : null;
            $integration_name = $integration_id ? $integrazo_fwcrm_form_fieldMappingDBInstance->get_integration_name($integration_id) : null;
            return $integration_name ? esc_html($integration_name) : __('N/A', 'crm-integration-freshworks-any-form');
        }

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

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

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

        protected function column_action($item)
        {
            $session = integrazo_fwcrm_form_is_valid_key();
            $resync_url = add_query_arg([
                'page'      => 'crm-integration-freshworks-any-form',
                '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'      => 'crm-integration-freshworks-any-form',
                '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="%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="showErrorDetails(%d)"></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', 'crm-integration-freshworks-any-form'),
                esc_url($delete_url),
                __('Delete', 'crm-integration-freshworks-any-form'),
                intval($item->id)
            );
        }



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

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

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'integrazo_fwcrm_form_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'crm-integration-freshworks-any-form'));
                }
            }
            // 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) {
                $integrazo_fwcrm_form_errorLogDBInstance = new integrazo_fwcrm_form_ErrorLog();
                // Handle delete action
                if (!empty($log_ids)) {
                    foreach ($log_ids as $log_id) {
                        $integrazo_fwcrm_form_errorLogDBInstance->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 = integrazo_fwcrm_form_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
                integrazo_fwcrm_form_bulk_resync($log_ids); // Call the bulk resync function
                // Redirect to the current page after the action
                $message = get_transient('integrazo_fwcrm_form_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('integrazo_fwcrm_form_error_log_success');
                }
                // Retrieve the transient.
                $message = get_transient('integrazo_fwcrm_form_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('integrazo_fwcrm_form_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.', 'crm-integration-freshworks-any-form');
        }

        protected function display_tablenav($which)
        {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
            $integrazo_fwcrm_form_errorLogDBInstance = new integrazo_fwcrm_form_ErrorLog();

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

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

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

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

                    <!-- Reset Button -->
                    <button type="button" class="button" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=errorlog')); ?>'">
                        <?php esc_html_e('Reset', 'crm-integration-freshworks-any-form'); ?>
                    </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
        }
    }
}
