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

    class IAFWZC_Accounts_Extend extends WP_List_Table
    {

        public function __construct()
        {
            global $blog_id;

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

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

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

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

            $account_items = $iafwzc_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-any-form-with-zoho-crm');
        }

        protected function column_service_name($item)
        {
            $service_name = isset($item['service_name']) ? $item['service_name'] : __('N/A', 'integrate-any-form-with-zoho-crm');

            // Map specific service names to user-friendly text with light background colors
            switch ($service_name) {
                case 'zoho_crm':
                    return '<span style="background-color: #e0f7fa; padding: 3px 6px; border-radius: 3px; color: #00796b;">' . __('Zoho CRM', 'integrate-any-form-with-zoho-crm') . '</span>';
                case 'zoho_bigin':
                    return '<span style="background-color: #f1f8e9; padding: 3px 6px; border-radius: 3px; color: #33691e;">' . __('Zoho Bigin', 'integrate-any-form-with-zoho-crm') . '</span>';
                default:
                    return '<span>' . esc_html($service_name) . '</span>'; // Display as-is for other values
            }
        }
        protected function column_data_center($item)
        {
            $data_center = isset($item['data_center']) ? $item['data_center'] : __('N/A', 'integrate-any-form-with-zoho-crm');

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

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



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

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

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

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