<?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_WZ_Setup_Extend')) {

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

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

        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_WZ_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_wz_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';
                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="' . esc_url(admin_url('admin.php?page=integrazo-integration-for-zoho-apps&tab=setup&integration_id=' . urlencode($integration_id) . '&step=' . $step_page)) . '">' . esc_html__('Edit', 'integrazo-integration-for-zoho-apps') . '</a> | ' .

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

                        // View Logs as POST using a form
                        '<a href="' . esc_url(admin_url('admin.php?page=integrazo-integration-for-zoho-apps&tab=logs&integration_filter=' . intval($integration_id))) . '" style="font-size:11px;">' .
                        esc_html__('View Logs', 'integrazo-integration-for-zoho-apps') .
                        '</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;">Saved as Draft</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-wz-setup-extend-toggle-switch">
                    <input type="checkbox" class="integrazo-wz-setup-extend-toggle-input" %s onclick="integrazo_wz_setup_extend_toggleIntegrationStatus(%d, this)">
                    <span class="integrazo-wz-setup-extend-toggle-slider"></span>
                </label>',
                $status,
                $integration_id
            );
        }




        protected function column_action($item)
        {
            return $item['action'];
        }

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

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

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

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

                <?php if ($which === 'top') : ?>
                    <div class="integrazo-wz-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-integration-for-zoho-apps'); ?>
                            </a>
                        </div>

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

                <?php if ($this->_pagination_args['total_pages'] > 1) : ?>
                    <div class="integrazo-wz-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-wz-setup-extend-span-header"><?php esc_html_e('Integrations', '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('Manage all your integrations. Add, edit, enable, or delete integrations as needed.', 'integrazo-integration-for-zoho-apps'); ?></p>
            </div>
        </div>
    </h3>

    <?php integrazo_wz_render_pending_notices(); ?>

    <?php
    $integrazo_wz_table = new INTEGRAZO_WZ_Setup_Extend();
    $integrazo_wz_table->prepare_items();
    $integrazo_wz_table->display();
    ?>
</div>