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

    class IAFWZCAI_Accounts_Extend extends WP_List_Table
    {
        protected $cache_key;

        public function __construct()
        {
            global $blog_id;

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

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

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

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

            $account_items = $iafwzcai_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-campaigns');
        }

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

            // Map data center codes to friendly names
            switch ($data_center) {
                case 'com':
                    return __('zoho.com (Global - USA)', 'integrate-with-zoho-campaigns');
                case 'eu':
                    return __('zoho.eu (Europe)', 'integrate-with-zoho-campaigns');
                case 'in':
                    return __('zoho.in (India)', 'integrate-with-zoho-campaigns');
                case 'com.cn':
                    return __('zoho.com.cn (China)', 'integrate-with-zoho-campaigns');
                case 'com.au':
                    return __('zoho.com.au (Australia)', 'integrate-with-zoho-campaigns');
                case 'jp':
                    return __('zoho.jp (Japan)', 'integrate-with-zoho-campaigns');
                case 'uk':
                    return __('zoho.uk (United Kingdom)', 'integrate-with-zoho-campaigns');
                case 'ca':
                    return __('zohocloud.ca (Canada)', 'integrate-with-zoho-campaigns');
                case 'sa':
                    return __('zoho.sa (KSA)', 'integrate-with-zoho-campaigns');
                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-campaigns');
        }

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

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



            $delete_url = add_query_arg([
                'page'      => 'integrate-with-zoho-campaigns',
                '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-campaigns'),
                esc_url($delete_url),
                __('Delete', 'integrate-with-zoho-campaigns')
            );
        }

        public function extra_tablenav($which)
        {
            $iafwzcai_accountDBInstance = new IAFWZCAI_Account_Table();
            $total_account = $iafwzcai_accountDBInstance->get_total_accounts();
            $session = iafwzcai_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.\');' : 'iafwzcai_showAccount();'; ?>"
                        class="button">
                        <?php esc_html_e('Add Account', 'integrate-with-zoho-campaigns'); ?>
                    </a>
                </div>
            <?php
            }
        }

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

        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
        }
    }
}
