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

    class integrazo_fwcrm_form_Accounts extends WP_List_Table
    {

        public function __construct()
        {
            global $blog_id;

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

        public function get_columns()
        {
            $columns = [
                'sno'           => __('S.No', 'crm-integration-freshworks-any-form'),
                'account_name'  => __('Account', 'crm-integration-freshworks-any-form'),
                'instance_url'  => __('Instance URL', 'crm-integration-freshworks-any-form'),
                'added_time'    => __('Added Time', 'crm-integration-freshworks-any-form'),
                'action'        => __('Action', 'crm-integration-freshworks-any-form'),
            ];
            return $columns;
        }

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

        public function prepare_items()
        {
            $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();
            // Security check: Verify the nonce if the form was submitted
            if (isset($_POST['integrazo_fwcrm_form_account_form_action_nonce'])) {
                // Sanitize the nonce input
                $nonce = sanitize_text_field(wp_unslash($_POST['integrazo_fwcrm_form_account_form_action_nonce']));

                // Verify the nonce
                if (!wp_verify_nonce($nonce, 'integrazo_fwcrm_form_account_form_action')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'crm-integration-freshworks-any-form'));
                }
            }
            $columns  = $this->get_columns();
            $hidden   = [];
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = [$columns, $hidden, $sortable];

            // Retrieve account data from database
            $account_items = $integrazo_fwcrm_form_accountDBInstance->get_account_data();

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

            // Handle sorting
            $orderby = (!empty($_GET['orderby'])) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : 'account_name'; // Default column
            $order = (!empty($_GET['order'])) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'asc'; // Default order            

            usort($account_items, function ($a, $b) use ($orderby, $order) {
                $value1 = isset($a[$orderby]) ? $a[$orderby] : '';
                $value2 = isset($b[$orderby]) ? $b[$orderby] : '';

                if ($order === 'asc') {
                    return strcmp($value1, $value2);
                }

                return strcmp($value2, $value1);
            });

            // 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', 'crm-integration-freshworks-any-form');
        }

        protected function column_instance_url($item)
        {
            return $service_name = isset($item['instance_url']) ? $item['instance_url'] : __('N/A', 'crm-integration-freshworks-any-form');
        }

        protected function column_added_time($item)
        {
            return isset($item['added_time']) ? esc_html($item['added_time']) : __('Not available', 'crm-integration-freshworks-any-form');
        }

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



            $delete_url = add_query_arg([
                'page'      => 'crm-integration-freshworks-any-form',
                'tab'       => 'accounts',
                'ac_action' => 'delete',
                'ac_id'     => $item['account_id'],
                '_wpnonce'  => wp_create_nonce('integrazo_fwcrm_form_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', 'crm-integration-freshworks-any-form'),
                esc_url($delete_url),
                __('Delete', 'crm-integration-freshworks-any-form')
            );
        }

        public function delete_account($account_id)
        {
            $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();
            $integrazo_fwcrm_form_accountDBInstance->delete_account($account_id);
        }

        public function edit_account($account_id, $data)
        {
            $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();
            $integrazo_fwcrm_form_accountDBInstance->edit_account($account_id, $data);
        }

        public function extra_tablenav($which)
        {
            $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();
            $session = integrazo_fwcrm_form_is_valid_key();
            $total_account = $integrazo_fwcrm_form_accountDBInstance->get_total_accounts();

            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.\');' : 'showAccount();'; ?>"
                        class="button">
                        <?php esc_html_e('Add Account', 'crm-integration-freshworks-any-form'); ?>
                    </a>
                </div>
            <?php
            }
        }



        public function no_items()
        {
            esc_html_e('No accounts found.', 'crm-integration-freshworks-any-form');
        }

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