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

    class IAFWZDESK_Accounts_Extend extends WP_List_Table
    {
        public function __construct()
        {
            global $blog_id;

            // Initialize parent class with the required arguments
            parent::__construct([
                'singular' => __('Account', 'integrate-with-zoho-desk'),
                'plural'   => __('Accounts', 'integrate-with-zoho-desk'),
                'ajax'     => false,
            ]);
        }

        public function get_columns()
        {
            $columns = [
                'sno'           => __('S.No', 'integrate-with-zoho-desk'),
                'account_name'  => __('Account', 'integrate-with-zoho-desk'),
                'data_center'   => __('Data Center', 'integrate-with-zoho-desk'),
                'added_time'  => __('Added Time', 'integrate-with-zoho-desk'),
                'modified_time'   => __('Modified Time', 'integrate-with-zoho-desk'),
                'action'        => __('Action', 'integrate-with-zoho-desk'),
            ];
            return $columns;
        }

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

        public function prepare_items()
        {
            $iafwzdesk_accountDBInstance = new IAFWZDESK_Account_Table();
            $columns  = $this->get_columns();
            $hidden   = [];
            $sortable = [];
            $this->_column_headers = [$columns, $hidden, $sortable];

            $account_items = $iafwzdesk_accountDBInstance->get_account_data();

            // Check if $account_items is an array with data
            if (!is_array($account_items) || empty($account_items)) {
                $account_items = [];
            }

            // Pagination parameters
            $per_page = 10;
            $current_page = $this->get_pagenum();
            $total_items = count($account_items);

            // Slice account items for the current page
            $account_items = array_slice($account_items, (($current_page - 1) * $per_page), $per_page);
            $this->items = $account_items; // Assign paginated data to items

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

        protected function column_sno($item)
        {
            $per_page = $this->get_pagination_arg('per_page'); // Number of items per page
            $current_page = $this->get_pagenum(); // Current page number
            static $count;

            if (!$count) {
                $count = ($current_page - 1) * $per_page + 1; // Calculate starting count for each page
            }

            return $count++; // Increment count for each row
        }


        protected function column_account_name($item)
        {
            return isset($item['account_name']) ? esc_html($item['account_name']) : __('No name', 'integrate-with-zoho-desk');
        }

        protected function column_data_center($item)
        {
            $data_center = isset($item['data_center']) ? $item['data_center'] : __('N/A', 'integrate-with-zoho-desk');

            // Map data center codes to friendly names
            switch ($data_center) {
                case 'com':
                    return __('zoho.com (Global - USA)', 'integrate-with-zoho-desk');
                case 'eu':
                    return __('zoho.eu (Europe)', 'integrate-with-zoho-desk');
                case 'in':
                    return __('zoho.in (India)', 'integrate-with-zoho-desk');
                case 'com.cn':
                    return __('zoho.com.cn (China)', 'integrate-with-zoho-desk');
                case 'com.au':
                    return __('zoho.com.au (Australia)', 'integrate-with-zoho-desk');
                case 'jp':
                    return __('zoho.jp (Japan)', 'integrate-with-zoho-desk');
                case 'uk':
                    return __('zoho.uk (United Kingdom)', 'integrate-with-zoho-desk');
                case 'ca':
                    return __('zohocloud.ca (Canada)', 'integrate-with-zoho-desk');
                case 'sa':
                    return __('zoho.sa (KSA)', 'integrate-with-zoho-desk');
                default:
                    return esc_html($data_center); // Display as-is for other or unknown values
            }
        }

        protected function column_added_time($item)
        {
            return isset($item['added_time']) ? esc_html($item['added_time']) : __('Not available', 'integrate-with-zoho-desk');
        }

        protected function column_modified_time($item)
        {
            return isset($item['modified_time']) ? esc_html($item['modified_time']) : __('Not available', 'integrate-with-zoho-desk');
        }

        protected function column_action($item)
        {
            $edit_url = add_query_arg([
                'page'      => 'integrate-with-zoho-desk',
                'tab'       => 'accounts',
                'ac_action' => 'edit',
                'ac_id'     => isset($item['account_id']) ? sanitize_text_field($item['account_id']) : '',
                '_wpnonce'  => wp_create_nonce('iafwzdesk_edit_account_nonce') // Add a nonce for security.
            ], admin_url('admin.php'));



            $delete_url = add_query_arg([
                'page'      => 'integrate-with-zoho-desk',
                'tab'       => 'accounts',
                'de_ac_id'     => $item['account_id'],
                '_wpnonce'  => wp_create_nonce('delete_account_' . $item['account_id']) // Add nonce for security
            ], 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', 'integrate-with-zoho-desk'),
                esc_url($delete_url),
                __('Delete', 'integrate-with-zoho-desk')
            );
        }

        public function extra_tablenav($which)
        {
            $iafwzdesk_accountDBInstance = new IAFWZDESK_Account_Table();
            $total_account = $iafwzdesk_accountDBInstance->get_total_accounts();
            $session = iafwzdesk_is_valid_key();
            if ($which == "top") {
?>
                <div class="alignleft actions" style="margin-bottom: 15px;">
                    <a href="javascript:void(0);"
                        onclick="<?php echo ($total_account >= 2 && !$session) ? 'alert(\'Upgrade to the premium version to add more accounts. The free version supports up to 2 accounts only.\');' : 'iafwzdesk_showAccount();'; ?>"
                        class="button">
                        <?php esc_html_e('Add Account', 'integrate-with-zoho-desk'); ?>
                    </a>
                </div>
            <?php
            }
        }

        public function no_items()
        {
            esc_html_e('No accounts found.', 'integrate-with-zoho-desk');
        }

        protected function display_tablenav($which)
        {
            ?>
            <div class="tablenav <?php echo esc_attr($which); ?>">
                <?php if ($which == 'top') : ?>
                    <div class="alignleft actions">
                        <?php $this->extra_tablenav($which); ?>
                    </div>
                <?php endif; ?>
                <div class="alignleft actions bulkactions">
                    <?php $this->bulk_actions($which); ?>
                </div>
                <?php $this->pagination($which); ?>
                <br class="clear" />
            </div>
<?php
        }
    }
}
