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

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

        public function get_columns()
        {
            return [
                'sno'          => __('S.No', 'integrazo-integration-for-zoho-apps'),
                'account_name' => __('Account Name', 'integrazo-integration-for-zoho-apps'),
                'product_name' => __('Service 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'),
                'action'       => __('Action', 'integrazo-integration-for-zoho-apps'),
            ];
        }

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

        public function prepare_items()
        {
            $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';

            if (!empty($nonce) && wp_verify_nonce($nonce, 'integrazo_wz_account_search')) {
                $search_term = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';
            } else {
                $search_term = '';
            }
            $integrazo_wz_accountDBInstance = new INTEGRAZO_WZ_Account_Model();
            $columns = $this->get_columns();
            $hidden = [];
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = [$columns, $hidden, $sortable];

            $data = $integrazo_wz_accountDBInstance->get_account_data();
            if (!is_array($data)) {
                $data = [];
            }

            // Search filter
            if (!empty($search_term)) {
                $data = array_filter($data, function ($item) use ($search_term) {
                    return stripos($item['account_name'], $search_term) !== false ||
                        stripos($item['product_name'], $search_term) !== false;
                });
            }

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

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

            usort($data, function ($a, $b) use ($orderby, $order) {
                $valA = $a[$orderby] ?? '';
                $valB = $b[$orderby] ?? '';

                if (in_array($orderby, ['created_at', 'updated_at'])) {
                    $valA = strtotime($valA);
                    $valB = strtotime($valB);
                }

                if ($valA == $valB) {
                    return 0;
                }

                $result = ($valA < $valB) ? -1 : 1;

                return ($order === 'asc') ? $result : -$result;
            });

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

            $this->items = array_slice($data, ($current_page - 1) * $per_page, $per_page);

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

        protected function column_sno($item)
        {
            static $count;
            $per_page = $this->get_pagination_arg('per_page');
            $current_page = $this->get_pagenum();
            if (!$count) {
                $count = ($current_page - 1) * $per_page + 1;
            }
            return $count++;
        }

        protected function column_account_name($item)
        {
            return esc_html($item['account_name'] ?? __('No name', 'integrazo-integration-for-zoho-apps'));
        }

        protected function column_product_name($item)
        {
            global $integrazo_wz_integration_sources;

            $value = $item['product_name'] ?? '';
            foreach ($integrazo_wz_integration_sources['products'] as $product) {
                if ($product['id'] === $value || $product['name'] === $value) {
                    return esc_html($product['name']);
                }
            }

            return esc_html(__('No name', 'integrazo-integration-for-zoho-apps'));
        }



        protected function column_created_by($item)
        {
            $user_id = $item['created_by'] ?? null;

            if ($user_id && $user = get_userdata($user_id)) {
                return esc_html($user->user_login);
            }

            return esc_html(__('Not available', 'integrazo-integration-for-zoho-apps'));
        }


        protected function column_updated_at($item)
        {
            return esc_html($item['updated_at'] ?? __('Not available', 'integrazo-integration-for-zoho-apps'));
        }

        protected function column_action($item)
        {
            $edit_url = add_query_arg([
                'page'       => 'integrazo-integration-for-zoho-apps',
                'tab'        => 'settings',
                'subtab'     => 'accounts',
                'action'     => 'integrazo_wz_edit_account',
                'edit_ac_id' => $item['id'],
                '_wpnonce'   => wp_create_nonce('edit_account_' . $item['id'])
            ], admin_url('admin.php'));

            $delete_url = add_query_arg([
                'action'    => 'integrazo_wz_delete_account', // ✅ use admin_action hook
                'de_ac_id'  => $item['id'],
                '_wpnonce'  => wp_create_nonce('delete_account_' . $item['id'])
            ], admin_url('admin.php'));

            return sprintf(
                '<a href="%s" style="color: #2271b1;">%s</a> | <a href="%s" onclick="return confirm(\'Are you sure you want to delete this account?\\n\\nNote: Deleting this account will also remove any associated integrations and error logs. This action cannot be undone. Do you want to proceed?\');" style="color: #b32d2e;">%s</a>',
                esc_url($edit_url),
                __('Edit', 'integrazo-integration-for-zoho-apps'),
                esc_url($delete_url),
                __('Delete', 'integrazo-integration-for-zoho-apps')
            );
        }

        public function no_items()
        {
            esc_html_e('No accounts 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_account_search')
            ) {
                $search_value = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';
            }
?>
            <div class="tablenav <?php echo esc_attr($which); ?>">
                <?php if ($which === 'top') : ?>
                    <div class="alignleft actions">
                        <input type="search" name="s" value="<?php echo esc_attr($search_value); ?>" placeholder="<?php esc_attr_e('Search accounts...', 'integrazo-integration-for-zoho-apps'); ?>">
                        <?php wp_nonce_field('integrazo_wz_account_search'); ?>
                        <?php submit_button(__('Search', 'integrazo-integration-for-zoho-apps'), '', '', false, ['id' => 'search-submit']); ?>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=integrazo-integration-for-zoho-apps&tab=settings&subtab=accounts')); ?>" class="button"><?php esc_html_e('Reset', 'integrazo-integration-for-zoho-apps'); ?></a>
                    </div>
                <?php endif; ?>
                <div class="alignleft actions bulkactions">
                    <?php $this->bulk_actions($which); ?>
                </div>
                <?php $this->pagination($which); ?>
                <br class="clear" />
            </div>
<?php
        }
    }
}

$integrazo_wz_accounts_table = new INTEGRAZO_WZ_Accounts_Extend();
$integrazo_wz_accounts_table->prepare_items();
?>
<br>
<form method="get">
    <input type="hidden" name="page" value="integrazo-integration-for-zoho-apps">
    <input type="hidden" name="tab" value="settings">
    <input type="hidden" name="subtab" value="accounts">
    <p style="margin: 10px 0; font-style: italic; color: #555;">
        <?php esc_html_e('All connected accounts for integrations are listed here. You can modify details, reauthorize access, or remove entries.', 'integrazo-integration-for-zoho-apps'); ?>
    </p>
    <?php $integrazo_wz_accounts_table->display(); ?>
</form>