<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

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

if (!class_exists('INTEGRAZO_WCZO_Setup_Extend')) {

    class INTEGRAZO_WCZO_Setup_Extend extends WP_List_Table
    {
        public function __construct()
        {
            parent::__construct([
                'singular' => __('Feeds', 'integrazo-wc-zoho-integration'),
                'plural'   => __('Feeds', 'integrazo-wc-zoho-integration'),
                'ajax'     => false,
            ]);
        }

        public function get_columns()
        {
            return [
                'sno'                => __('S.No', 'integrazo-wc-zoho-integration'),
                'integration_name'   => __('Integration Name', 'integrazo-wc-zoho-integration'),
                'created_by'   => __('Created by', 'integrazo-wc-zoho-integration'),
                'updated_at'   => __('Last Modified On', 'integrazo-wc-zoho-integration'),
                'integration_status' => __('Integration Status', 'integrazo-wc-zoho-integration'),
                'action'             => __('Action', 'integrazo-wc-zoho-integration'),
            ];
        }

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

        public function prepare_items()
        {
            $model = new INTEGRAZO_WCZO_Integration_Model();
            $data = $model->get_all_integrations();
            $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])) : '';
            if (!empty($nonce) && wp_verify_nonce($nonce, 'integrazo_wczo_setup_search')) {
                $search = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';
            } else {
                $search = '';
            }
            if (!empty($search)) {
                $data = array_filter($data, function ($item) use ($search) {
                    return stripos($item['integration_name'], $search) !== false;
                });
            }

            $orderby = isset($_GET['orderby']) ? sanitize_key(wp_unslash($_GET['orderby'])) : '';
            $order   = isset($_GET['order']) ? sanitize_key(wp_unslash($_GET['order'])) : 'asc';

            if (in_array($orderby, ['added_time', 'created_time'], true)) {
                $sort_key = $orderby === 'added_time' ? 'updated_at' : 'created_at';
                usort($data, function ($a, $b) use ($sort_key, $order) {
                    $valA = strtotime($a[$sort_key]);
                    $valB = strtotime($b[$sort_key]);
                    if ($valA === $valB) return 0;
                    return ($order === 'asc') ? ($valA <=> $valB) : ($valB <=> $valA);
                });
            }

            $items = [];
            $count = 1;
            $setp_page = 1;
            foreach ($data as $row) {
                $integration_id = $row['id'];

                if ($row['account_id'] === null) {
                    $step_page = 2;
                } else {
                    $step_page = 3;
                }

                $user_name = __('Not available', 'integrazo-wc-zoho-integration');
                if (!empty($row['created_by']) && $user = get_userdata($row['created_by'])) {
                    $user_name = $user->user_login;
                }
                $items[] = [
                    'id'                 => $integration_id,
                    'sno'                => $count++,
                    'integration_name'   => esc_html($row['integration_name']),
                    'created_by'         => esc_html($user_name),
                    'updated_at'         => esc_html($row['updated_at']),
                    'integration_status' => $row['integration_status'],
                    'action'             =>
                    '<a href="' . admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=setup&integration_id=' . urlencode($integration_id) . '&step=' . $step_page) . '">' . __('Edit', 'integrazo-wc-zoho-integration') . '</a> | ' .

                        '<a href="' . wp_nonce_url(
                            admin_url('admin.php?page=integrazo-wc-zoho-integration&action=delete&tab=setup&integration_id=' . $integration_id),
                            'integrazo_wczo_delete_integration_' . $integration_id
                        ) . '" style="color: #b32d2e;" onclick="return confirm(\'' . esc_js(__('Are you sure you want to delete this integration?', 'integrazo-wc-zoho-integration')) . '\')">' .
                        __('Delete', 'integrazo-wc-zoho-integration') . '</a> | ' .

                        // View Logs as POST using a form
                        '<a href="' . esc_url(admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=logs&integration_filter=' . intval($integration_id))) . '" style="font-size:11px;">' .
                        esc_html__('View Logs', 'integrazo-wc-zoho-integration') .
                        '</a>',


                ];
            }

            $per_page     = 10;
            $current_page = $this->get_pagenum();
            $total_items  = count($items);

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

            $columns  = $this->get_columns();
            $hidden   = [];
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = [$columns, $hidden, $sortable];

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

        protected function column_integration_status($item)
        {

            switch ((int) $item['integration_status']) {
                case 1: // Draft
                    return '<span style="color: #b32d2e;">' . esc_html__('Saved as Draft', 'integrazo-wc-zoho-integration') . '</span>';

                case 2: // Active
                    $status = 'checked';
                    break;

                default: // Inactive
                    $status = '';
                    break;
            }

            $integration_id = isset($item['integration_id']) ? (int) $item['integration_id'] : (int) $item['id'];

            return sprintf(
                '<label class="integrazo-wczo-setup-extend-toggle-switch">
                    <input type="checkbox" class="integrazo-wczo-setup-extend-toggle-input" %s onclick="integrazo_wczo_setup_extend_toggleIntegrationStatus(%d, this)">
                    <span class="integrazo-wczo-setup-extend-toggle-slider"></span>
                </label>',
                $status,
                $integration_id
            );
        }




        protected function column_default($item, $column_name)
        {
            return isset($item[$column_name]) ? $item[$column_name] : '';
        }

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

        protected function display_tablenav($which)
        {
            $search_value = '';
            if (
                isset($_GET['_wpnonce']) &&
                wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'integrazo_wczo_setup_search')
            ) {
                $search_value = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';
            }

            $integration_model = new INTEGRAZO_WCZO_Integration_Model();
            $total_integration = $integration_model->get_total_integrations_count();
            $add_integration_url = esc_url(
                wp_nonce_url(
                    admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=setup&action=addnew'),
                    'integrazo_wczo_setup_add'
                )
            );
?>
            <div class="tablenav <?php echo esc_attr($which); ?>">

                <?php if ($which === 'top') : ?>
                    <div class="integrazo-wczo-top-controls" style="margin-bottom: 10px;">
                        <div class="alignleft actions" style="margin-bottom: 10px;">
                            <a href="<?php echo esc_url($add_integration_url); ?>"
                                class="button">
                                <?php esc_html_e('Add Integration', 'integrazo-wc-zoho-integration'); ?>
                            </a>
                        </div>

                        <div class="alignright actions" style="margin-bottom: 10px;">
                            <form method="get" style="display: inline;">
                                <?php wp_nonce_field('integrazo_wczo_setup_search'); ?>
                                <input type="hidden" name="page" value="integrazo-wc-zoho-integration">
                                <input type="hidden" name="tab" value="setup">
                                <label for="integrazo-wczo-integration-search" class="screen-reader-text">
                                    <?php esc_html_e('Search Integrations', 'integrazo-wc-zoho-integration'); ?>
                                </label>
                                <input type="search" id="integrazo-wczo-integration-search" name="s"
                                    value="<?php echo isset($_REQUEST['s']) ? esc_attr(sanitize_text_field(wp_unslash($_REQUEST['s']))) : ''; ?>"
                                    placeholder="<?php esc_attr_e('Search Integrations...', 'integrazo-wc-zoho-integration'); ?>">
                                <?php submit_button(__('Search', 'integrazo-wc-zoho-integration'), '', '', false); ?>
                            </form>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=setup')); ?>"
                                class="button" style="margin-left: 5px;">
                                <?php esc_html_e('Reset', 'integrazo-wc-zoho-integration'); ?>
                            </a>
                        </div>
                        <div style="clear: both;"></div>
                    </div>
                <?php endif; ?>

                <?php if ($this->_pagination_args['total_pages'] > 1) : ?>
                    <div class="integrazo-wczo-pagination-controls">
                        <?php $this->pagination($which); ?>
                    </div>
                <?php endif; ?>

                <br class="clear" />
            </div>
        <?php
        }

        public function display()
        {
            $this->display_tablenav('top');
        ?>
            <table class="wp-list-table <?php echo esc_attr(implode(' ', $this->get_table_classes())); ?>">
                <thead>
                    <tr><?php $this->print_column_headers(); ?></tr>
                </thead>
                <tbody id="the-list"
                    <?php
                    if ($this->_args['singular']) {
                        echo " data-wp-lists='list:" . esc_attr($this->_args['singular']) . "'";
                    }
                    ?>>
                    <?php $this->display_rows_or_placeholder(); ?>
                </tbody>
                <tfoot>
                    <tr><?php $this->print_column_headers(); ?></tr>
                </tfoot>
            </table>
<?php
            $this->display_tablenav('bottom');
        }
    }
}
?>

<div class="wrap">
    <h3>
        <span class="integrazo-wczo-setup-extend-span-header"><?php esc_html_e('Integrations', '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('Manage all your integrations. Add, edit, enable, or delete integrations as needed.', 'integrazo-wc-zoho-integration'); ?></p>
            </div>
        </div>
    </h3>

    <?php
    $table = new INTEGRAZO_WCZO_Setup_Extend();
    $table->prepare_items();
    $table->display();
    ?>
</div>