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

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

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

        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_wczo_account_search')) {
                $search_term = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';
            } else {
                $search_term = '';
            }
            $integrazo_wczo_accountDBInstance = new INTEGRAZO_WCZO_Account_Model();
            $columns = $this->get_columns();
            $hidden = [];
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = [$columns, $hidden, $sortable];

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

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

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

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



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


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

        protected function column_action($item)
        {
            $edit_url = add_query_arg([
                'page'       => 'integrazo-wc-zoho-integration',
                'tab'        => 'settings',
                'subtab'     => 'accounts',
                'action'     => 'integrazo_wczo_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_wczo_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-wc-zoho-integration'),
                esc_url($delete_url),
                __('Delete', 'integrazo-wc-zoho-integration')
            );
        }

        public function no_items()
        {
            esc_html_e('No accounts 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_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-wc-zoho-integration'); ?>">
                        <?php wp_nonce_field('integrazo_wczo_account_search'); ?>
                        <?php submit_button(__('Search', 'integrazo-wc-zoho-integration'), '', '', false, ['id' => 'search-submit']); ?>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=settings&subtab=accounts')); ?>" class="button"><?php esc_html_e('Reset', 'integrazo-wc-zoho-integration'); ?></a>
                    </div>
                <?php endif; ?>
                <div class="alignleft actions bulkactions">
                    <?php $this->bulk_actions($which); ?>
                </div>
                <?php $this->pagination($which); ?>
                <br class="clear" />
            </div>
<?php
        }
    }
}

$accounts_table = new INTEGRAZO_WCZO_Accounts_Extend();
$accounts_table->prepare_items();
?>
<br>
<form method="get">
    <input type="hidden" name="page" value="integrazo-wc-zoho-integration">
    <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-wc-zoho-integration'); ?>
    </p>
    <?php $accounts_table->display(); ?>
</form>