<?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_WCZO_Error_Log_Extend')) {
    class INTEGRAZO_WCZO_Error_Log_Extend extends WP_List_Table
    {
        protected $cache_key = 'integrazo_wczo_all_error_log_data';
        public $integration_filter_override = 0;

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

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


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


        public function prepare_items()
        {
            $INTEGRAZO_WCZO_Error_LogDBInstance = new INTEGRAZO_WCZO_Logs_Model();

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

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'integrazo_wczo_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrazo-wc-zoho-integration'));
                }
            }
            if (! current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
            }
            $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_WCZO_Error_LogDBInstance->get_all_error_logs_with_timefilter($time_filter);
            } else {
                $error_log_items = $INTEGRAZO_WCZO_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-wc-zoho-integration');
            if ($error_type === 'SUCCESS') {
                return '<div class="integrazo-wczo-log-tick"></div>';
            } else {
                return '<div class="integrazo-wczo-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_WCZO_Field_MappingDBInstance = new INTEGRAZO_WCZO_Integration_Model();
            $integration_id = isset($item['integration_id']) ? $item['integration_id'] : null;
            $integration_name = $integration_id ? $INTEGRAZO_WCZO_Field_MappingDBInstance->get_integration_name($integration_id) : null;

            if ($integration_id && $integration_name) {
                $url = add_query_arg([
                    'page'            => 'integrazo-wc-zoho-integration',
                    '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-wc-zoho-integration'))
            );
        }



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

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

            $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-wc-zoho-integration'))
            );
        }

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

            $resync_url = add_query_arg([
                'page'     => 'integrazo-wc-zoho-integration',
                'tab'      => 'logs',
                'action'   => 'integrazo_wczo_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-wc-zoho-integration',
                '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-wc-zoho-integration')
            );

            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_wczo_showErrorDetails(%d)"></span>
        </span>',
                $resync_link,
                esc_url($delete_url),
                __('Delete', 'integrazo-wc-zoho-integration'),
                $log_id
            );
        }

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

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

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'integrazo_wczo_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrazo-wc-zoho-integration'));
                }
            }
            if (! current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
            }
            // 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_WCZO_Error_LogDBInstance = new INTEGRAZO_WCZO_Logs_Model();
                // Handle delete action
                if (!empty($log_ids)) {
                    foreach ($log_ids as $log_id) {
                        $INTEGRAZO_WCZO_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', 'integrazo-wc-zoho-integration') . '</p>
            </div>';

                return;
                //
            } elseif ('resync' === $action) {
                // Handle resync action directly
                integrazo_wczo_bulk_resync($log_ids); // Call the bulk resync function

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

                // Retrieve and display failure message
                $message = get_transient('integrazo_wczo_fail');
                if ($message) {
                    echo '<div class="notice notice-error is-dismissible">
            <p>' . esc_html($message) . '</p>
        </div>';
                    delete_transient('integrazo_wczo_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">
                   <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-wc-zoho-integration')); ?>');">
                        <?php esc_html_e('Delete All Logs', 'integrazo-wc-zoho-integration'); ?>
                    </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-wc-zoho-integration')); ?>');">
                        <?php esc_html_e('Delete All Success Logs', 'integrazo-wc-zoho-integration'); ?>
                    </button>
                </div>

            <?php
            }
        }


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

        protected function display_tablenav($which)
        {
            $INTEGRAZO_WCZO_Field_MappingDBInstance = new INTEGRAZO_WCZO_Integration_Model();
            $INTEGRAZO_WCZO_Error_LogDBInstance = new INTEGRAZO_WCZO_Logs_Model();

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

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'integrazo_wczo_error_log_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'integrazo-wc-zoho-integration'));
                }
            }
            if (! current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
            }
            $integration_id_list = $INTEGRAZO_WCZO_Error_LogDBInstance->get_unique_integration_ids(); // Get unique integration IDs
            $error_type_list = $INTEGRAZO_WCZO_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-wc-zoho-integration'); ?></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_WCZO_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-wc-zoho-integration'); ?></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-wc-zoho-integration'); ?></option>
                        <option value="today" <?php selected($time_filter, 'today'); ?>><?php esc_html_e('Today', 'integrazo-wc-zoho-integration'); ?></option>
                        <option value="yesterday" <?php selected($time_filter, 'yesterday'); ?>><?php esc_html_e('Yesterday', 'integrazo-wc-zoho-integration'); ?></option>
                        <option value="last_7_days" <?php selected($time_filter, 'last_7_days'); ?>><?php esc_html_e('Last 7 Days', 'integrazo-wc-zoho-integration'); ?></option>
                        <option value="last_30_days" <?php selected($time_filter, 'last_30_days'); ?>><?php esc_html_e('Last 30 Days', 'integrazo-wc-zoho-integration'); ?></option>
                    </select>

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

                    <!-- Reset Button -->
                    <button type="button" class="button" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=logs')); ?>'">
                        <?php esc_html_e('Reset', 'integrazo-wc-zoho-integration'); ?>
                    </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-wczo-setup-extend-span-header"><?php esc_html_e('Logs', 'integrazo-wc-zoho-integration'); ?></span>
        <div class="integrazo-wczo-helpicon-help-icon-wrapper">
            <span class="integrazo-wczo-helpicon-help-icon">?</span>
            <div class="integrazo-wczo-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-wc-zoho-integration'); ?></p>
            </div>
        </div>
    </h3>

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

</div>

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