<?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_WZ_Error_Log_Extend')) {
    class INTEGRAZO_WZ_Error_Log_Extend extends WP_List_Table
    {
        protected $cache_key = 'integrazo_wz_all_error_log_data';
        public $integration_filter_override = 0;

        public function __construct()
        {
            parent::__construct([
                'singular' => __('Error Log', 'integrazo-integration-for-zoho-apps'),
                'plural'   => __('Error Logs', 'integrazo-integration-for-zoho-apps'),
                'ajax'     => false,
            ]);
        }

        public function get_columns()
        {
            $columns = [
                'cb'                 => '<input type="checkbox" />', // <-- important
                'status_icon'        => '',
                'sno'                => __('S.No', 'integrazo-integration-for-zoho-apps'),
                'integration_name'   => __('Integration', 'integrazo-integration-for-zoho-apps'),
                'error_type'         => __('Status', 'integrazo-integration-for-zoho-apps'),
                'error_message'      => __('Message', 'integrazo-integration-for-zoho-apps'),
                'updated_at'         => __('Time', 'integrazo-integration-for-zoho-apps'),
                'action'             => __('Action', 'integrazo-integration-for-zoho-apps'),
            ];
            return $columns;
        }


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


        public function prepare_items()
        {
            $INTEGRAZO_WZ_Error_LogDBInstance = new INTEGRAZO_WZ_Logs_Model();

            if (! current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'integrazo-integration-for-zoho-apps'));
            }
            $nonce = sanitize_text_field(wp_unslash($_REQUEST['integrazo_wz_error_log_form_action_nonce'] ?? ''));
            if ($this->current_action() || !empty($_POST)) {
                if (!wp_verify_nonce($nonce, 'integrazo_wz_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrazo-integration-for-zoho-apps'));
                }
            }
            $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_WZ_Error_LogDBInstance->get_all_error_logs_with_timefilter($time_filter);
                // $error_log_items = $INTEGRAZO_WZ_Error_LogDBInstance->get_all_error_logs($time_filter);
            } else {
                $error_log_items = $INTEGRAZO_WZ_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($integration_filter) && !empty($this->integration_filter_override)) {
                $integration_filter = $this->integration_filter_override;
            }

            if (!empty($error_type_filter)) {
                $error_log_items = array_filter($error_log_items, function ($item) use ($error_type_filter) {
                    return isset($item['category']) && $item['category'] === $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;
                });
            }

           $orderby = isset($_GET['orderby']) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : 'updated_at';
            $order = isset($_GET['order']) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'desc';

            $allowed_orderby = ['updated_at', 'resync_attempt'];
            if (!in_array($orderby, $allowed_orderby, true)) {
                $orderby = 'updated_at';
            }
            if (!in_array($order, ['asc', 'desc'], true)) {
                $order = 'desc';
            }

            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['category']) ? esc_html($item['category']) : __('Unknown', 'integrazo-integration-for-zoho-apps');
            if ($error_type === 'SUCCESS') {
                return '<div class="integrazo-wz-log-tick"></div>';
            } else {
                return '<div class="integrazo-wz-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)
        {
            $INTEGRAZO_WZ_Field_MappingDBInstance = new INTEGRAZO_WZ_Integration_Model();
            $integration_id = isset($item['integration_id']) ? $item['integration_id'] : null;
            $integration_name = $integration_id ? $INTEGRAZO_WZ_Field_MappingDBInstance->get_integration_name($integration_id) : null;

            if ($integration_id && $integration_name) {
                $url = add_query_arg([
                    'page'            => 'integrazo-integration-for-zoho-apps',
                    'tab'             => 'setup',
                    'integration_id'  => $integration_id,
                    'step'            => 3,
                ], admin_url('admin.php'));

                return sprintf(
                    '<a href="%s" style="font-size:11px;">%s</a>',
                    esc_url($url),
                    esc_html($integration_name)
                );
            }

            return sprintf(
                '<span style="font-size:11px;">%s</span>',
                esc_html(__('N/A', 'integrazo-integration-for-zoho-apps'))
            );
        }



        protected function column_error_type($item)
        {
            return sprintf(
                '<span style="font-size:11px;">%s</span>',
                esc_html(isset($item['category']) ? $item['category'] : __('Unknown', 'integrazo-integration-for-zoho-apps'))
            );
        }

        protected function column_error_message($item)
        {
            $error_type = isset($item['category']) ? esc_html($item['category']) : __('Unknown', 'integrazo-integration-for-zoho-apps');

            $error_message = isset($item['message']) ? esc_html($item['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', 'integrazo-integration-for-zoho-apps'))
            );
        }

        protected function column_action($item)
        {
            $log_id = isset($item['id']) ? intval($item['id']) : 0;

            $resync_url = add_query_arg([
                'page'     => 'integrazo-integration-for-zoho-apps',
                'tab'      => 'logs',
                'action'   => 'integrazo_wz_resync',
                'log_id'   => $log_id,
                '_wpnonce' => wp_create_nonce('resync_error_log_' . $log_id),
            ], admin_url('admin.php'));

            $delete_url = add_query_arg([
                'page'      => 'integrazo-integration-for-zoho-apps',
                'tab'       => 'logs',
                'de_log_id' => $log_id,
                '_wpnonce'  => wp_create_nonce('delete_error_log_' . $log_id),
            ], admin_url('admin.php'));

            $resync_link = sprintf(
                '<a href="%s" style="color: #2271b1;">%s</a>',
                esc_url($resync_url),
                __('Resync', 'integrazo-integration-for-zoho-apps')
            );

            return sprintf(
                '<span style="font-size:11px;">
            %s | 
            <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="integrazo_wz_showErrorDetails(%d)"></span>
        </span>',
                $resync_link,
                esc_url($delete_url),
                __('Delete', 'integrazo-integration-for-zoho-apps'),
                $log_id
            );
        }

        public function get_bulk_actions()
        {
            $actions = [
                'resync' => __('Resync', 'integrazo-integration-for-zoho-apps'),
                'delete' => __('Delete', 'integrazo-integration-for-zoho-apps'),
            ];
            return $actions;
        }

        public function process_bulk_action()
        {
            if (! current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'integrazo-integration-for-zoho-apps'));
            }
            $nonce = sanitize_text_field(wp_unslash($_REQUEST['integrazo_wz_error_log_form_action_nonce'] ?? ''));
            if ($this->current_action() || !empty($_POST)) {
                if (!wp_verify_nonce($nonce, 'integrazo_wz_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrazo-integration-for-zoho-apps'));
                }
            }
            // 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_WZ_Error_LogDBInstance = new INTEGRAZO_WZ_Logs_Model();
                // Handle delete action
                if (!empty($log_ids)) {
                    foreach ($log_ids as $log_id) {
                        $INTEGRAZO_WZ_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) {
                // Handle resync action directly
                integrazo_wz_bulk_resync($log_ids); // Call the bulk resync function

                // Retrieve and display success message
                $message = get_transient('integrazo_wz_success');
                if ($message) {
                    echo '<div class="notice notice-success is-dismissible">
            <p>' . esc_html($message) . '</p>
        </div>';
                    delete_transient('integrazo_wz_success');
                }

                // Retrieve and display failure message
                $message = get_transient('integrazo_wz_fail');
                if ($message) {
                    echo '<div class="notice notice-warning is-dismissible">
            <p>' . wp_kses_post($message) . '</p>
        </div>';
                    delete_transient('integrazo_wz_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('<?php echo esc_js(__('Are you sure you want to delete all logs? This action cannot be undone.', 'integrazo-integration-for-zoho-apps')); ?>');">
                    <?php esc_html_e('Delete All Logs', 'integrazo-integration-for-zoho-apps'); ?>
                </button>
                    <!-- Delete Success Button -->
                   <button type="submit" name="bulk_delete_all_success" value="delete_all_success" class="button action" onclick="return confirm('<?php echo esc_js(__('Are you sure you want to delete all successfully added records? This action cannot be undone.', 'integrazo-integration-for-zoho-apps')); ?>');">
                        <?php esc_html_e('Delete All Success Logs', 'integrazo-integration-for-zoho-apps'); ?>
                    </button>


                </div>

            <?php
            }
        }


        public function no_items()
        {
            esc_html_e('No error logs found.', 'integrazo-integration-for-zoho-apps');
        }

        protected function display_tablenav($which)
        {
            $INTEGRAZO_WZ_Field_MappingDBInstance = new INTEGRAZO_WZ_Integration_Model();
            $INTEGRAZO_WZ_Error_LogDBInstance = new INTEGRAZO_WZ_Logs_Model();

            if (! current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'integrazo-integration-for-zoho-apps'));
            }
            $nonce = sanitize_text_field(wp_unslash($_REQUEST['integrazo_wz_error_log_form_action_nonce'] ?? ''));
            if ($this->current_action() || !empty($_POST)) {
                if (!wp_verify_nonce($nonce, 'integrazo_wz_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrazo-integration-for-zoho-apps'));
                }
            }
            $integration_id_list = $INTEGRAZO_WZ_Error_LogDBInstance->get_unique_integration_ids(); // Get unique integration IDs
            $error_type_list = $INTEGRAZO_WZ_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', 'integrazo-integration-for-zoho-apps'); ?></option>
                        <?php
                        $integration_filter = isset($_POST['integration_filter']) ? intval(wp_unslash($_POST['integration_filter'])) : 0;
                        foreach ($integration_id_list as $integration_id) :
                            $integration_name = $INTEGRAZO_WZ_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', 'integrazo-integration-for-zoho-apps'); ?></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', 'integrazo-integration-for-zoho-apps'); ?></option>
                        <option value="today" <?php selected($time_filter, 'today'); ?>><?php esc_html_e('Today', 'integrazo-integration-for-zoho-apps'); ?></option>
                        <option value="yesterday" <?php selected($time_filter, 'yesterday'); ?>><?php esc_html_e('Yesterday', 'integrazo-integration-for-zoho-apps'); ?></option>
                        <option value="last_7_days" <?php selected($time_filter, 'last_7_days'); ?>><?php esc_html_e('Last 7 Days', 'integrazo-integration-for-zoho-apps'); ?></option>
                        <option value="last_30_days" <?php selected($time_filter, 'last_30_days'); ?>><?php esc_html_e('Last 30 Days', 'integrazo-integration-for-zoho-apps'); ?></option>
                    </select>

                    <!-- Submit Button -->
                    <button type="submit" class="button"><?php esc_html_e('Filter', 'integrazo-integration-for-zoho-apps'); ?></button>

                    <!-- Reset Button -->
                    <button type="button" class="button" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=integrazo-integration-for-zoho-apps&tab=logs')); ?>'">
                        <?php esc_html_e('Reset', 'integrazo-integration-for-zoho-apps'); ?>
                    </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
        }
    }
}
?>
<div class="wrap">
    <h3>
        <span class="integrazo-wz-setup-extend-span-header"><?php esc_html_e('Logs', 'integrazo-integration-for-zoho-apps'); ?></span>
        <div class="integrazo-wz-helpicon-help-icon-wrapper">
            <span class="integrazo-wz-helpicon-help-icon">?</span>
            <div class="integrazo-wz-helpicon-help-tooltip">
                <p><?php esc_html_e('Tracks all integration logs, shows whether data was sent successfully or failed, and allows manual resync if data failed.', 'integrazo-integration-for-zoho-apps'); ?></p>
            </div>
        </div>
    </h3>

    <?php integrazo_wz_render_pending_notices(); ?>

    <form method="post">
        <?php wp_nonce_field('integrazo_wz_error_log_form_action', 'integrazo_wz_error_log_form_action_nonce'); ?>
        <?php
        $integrazo_wz_error_log_table = new INTEGRAZO_WZ_Error_Log_Extend();
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $integrazo_wz_error_log_table->integration_filter_override = isset($_GET['integration_filter']) ? intval($_GET['integration_filter']) : 0;
        $integrazo_wz_error_log_table->prepare_items();
        $integrazo_wz_error_log_table->display();
        ?>
    </form>

</div>

<div id="integrazo-wz-error-overlay" class="integrazo-wz-error-overlay">
    <div class="integrazo-wz-error-modal">
        <span class="integrazo-wz-error-close" onclick="integrazo_wz_closeErrorOverlay()">&times;</span>
        <div id="integrazo-wz-error-content"></div>
    </div>
</div>