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

    class IAFWZC_Setup_Extend extends WP_List_Table
    {
        public function __construct()
        {
            parent::__construct([
                'singular' => __('Form Integration', 'integrate-any-form-with-zoho-crm'),
                'plural'   => __('Form Integrations', 'integrate-any-form-with-zoho-crm'),
                'ajax'     => false,
            ]);
        }

        public function get_columns()
        {
            $columns = [
                'sno'               => __('S.No', 'integrate-any-form-with-zoho-crm'),
                'integration_name'           => __('Integration Name', 'integrate-any-form-with-zoho-crm'),
                'form_type'         => __('Form Type', 'integrate-any-form-with-zoho-crm'),
                'form_name'         => __('Form Name', 'integrate-any-form-with-zoho-crm'),
                'added_time' => __('Modified Time', 'integrate-any-form-with-zoho-crm'),
                'integration_status' => __('Integration Status', 'integrate-any-form-with-zoho-crm'),

                'action'            => __('Action', 'integrate-any-form-with-zoho-crm'),
            ];
            return $columns;
        }

        public function get_sortable_columns()
        {
            return [
                'integration_name' => ['integration_name', true],
                'form_type'        => ['form_type', true],
                'form_name'        => ['form_name', true],
                'added_time'       => ['added_time', true],
            ];
        }

        public function prepare_items()
        {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
            $IAFWZC_Id_MappingInstance = new IAFWZC_Id_Mapping();
            $IAFWZC_Form_NameInstance = new IAFWZC_Form_Name();

            // Define column headers
            $columns  = $this->get_columns();
            $hidden   = [];
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = [$columns, $hidden, $sortable];

            // Retrieve all mapping data
            $data = $IAFWZC_Field_MappingDBInstance->get_all_mappings();
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $orderby = isset($_GET['orderby']) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : 'form_name';
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $order = isset($_GET['order']) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'asc';

            // Sort the data if orderby is defined and sortable
            if ($orderby && in_array($orderby, array_keys($sortable), true)) {
                usort($data, function ($a, $b) use ($orderby, $order, $IAFWZC_Id_MappingInstance, $IAFWZC_Form_NameInstance) {
                    $valueA = $a->$orderby ?? ''; // Fallback to empty string if property not set
                    $valueB = $b->$orderby ?? ''; // Fallback to empty string if property not set

                    if ($orderby === 'added_time') {

                        // Convert updated_at to timestamps or fallback to 0 if invalid
                        $timestampA = strtotime($a->updated_at) ?: 0; // Convert to timestamp or fallback
                        $timestampB = strtotime($b->updated_at) ?: 0;

                        // Compare the timestamps
                        $result = $timestampA <=> $timestampB;
                    } elseif ($orderby === 'form_type') {
                        $valueA = $IAFWZC_Id_MappingInstance->get_plugin_name_by_id((int)$a->form_group_id);
                        $valueB = $IAFWZC_Id_MappingInstance->get_plugin_name_by_id((int)$b->form_group_id);
                        $result = strcmp((string)$valueA, (string)$valueB);
                    } elseif ($orderby === 'form_name') {
                        $valueA = $IAFWZC_Form_NameInstance->getFormName((int)$a->form_group_id, (int)$a->form_id);
                        $valueB = $IAFWZC_Form_NameInstance->getFormName((int)$b->form_group_id, (int)$b->form_id);
                        $result = strcmp((string)$valueA, (string)$valueB);
                    } else {
                        $result = strcmp((string)$valueA, (string)$valueB);
                    }

                    return $order === 'asc' ? $result : -$result;
                });
            }

            // Pagination setup
            $per_page = 7;
            $current_page = $this->get_pagenum();
            $total_items = count($data);

            // Slice data for pagination
            $this->items = array_slice($data, (($current_page - 1) * $per_page), $per_page);

            // Pagination arguments
            $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');
            $current_page = $this->get_pagenum();
            static $count;

            if (!$count) {
                $count = ($current_page - 1) * $per_page + 1;
            }

            return $count++;
        }


        protected function column_integration_name($item)
        {

            return esc_html($item->integration_name);
        }
        protected function column_added_time($item)
        {

            return isset($item->updated_at) ? esc_html($item->updated_at) : __('Not available', 'integrate-any-form-with-zoho-crm');
        }

        protected function column_form_type($item)
        {
            $IAFWZC_Id_MappingInstance = new IAFWZC_Id_Mapping();
            $form_type = $IAFWZC_Id_MappingInstance->get_plugin_name_by_id($item->form_group_id);
            // Define styles for each form type
            $color_styles = [
                'Contact Form 7'       => ['#f7fbfc', '#90caf985', '#e3f2fd', '#0d47a1'],  // Light blue, very dark blue text
                'WP Forms'             => ['#fbfdf9', '#aed58199', '#f1f8e9', '#33691e'],  // Light green, dark green text
                'Formidable Forms'     => ['#fff7f6', '#ffab9187', '#fbe9e7', '#bf360c'],  // Light coral, dark orange text
                'Gravity Forms'        => ['#f9f6fc', '#b39ddb6e', '#ede7f6', '#311b92'],  // Light lavender, dark purple text
                'Elementor Form'       => ['#fffbe6', '#ffcc8069', '#fff8e1', '#e65100'],  // Light amber, dark orange text
            ];

            // Default style for unrecognized form types
            $default_style = ['#fdfdfd', '#b0bec5', '#eceff1', '#263238']; // Subtle gray tones, dark gray text

            // Retrieve styles based on form type
            [$bg_color, $border_color, $shadow_color, $text_color] = $color_styles[$form_type] ?? $default_style;

            // Return formatted HTML with enhanced styling
            return sprintf(
                '<span style="background-color: %s; border: 0.5px solid %s; box-shadow: 0 1px 3px %s; padding: 5px 8px; border-radius: 4px; font-size: 12px; font-weight: 500; color: %s; display: inline-block; text-align: center;">%s</span>',
                esc_attr($bg_color),         // Background color
                esc_attr($border_color),     // Border color
                esc_attr($shadow_color),     // Shadow color
                esc_attr($text_color),       // Dark text color
                esc_html($form_type, 'integrate-any-form-with-zoho-crm') // Form type name
            );
        }

        protected function column_form_name($item)
        {
            $IAFWZC_Form_NameInstance = new IAFWZC_Form_Name();
            $form_group_id = intval($item->form_group_id);
            $form_id = $item->form_id;

            $form_name = $IAFWZC_Form_NameInstance->getFormName((int)$form_group_id, $form_id);
            return esc_html($form_name);
        }

        protected function column_integration_status($item)
        {
            // Set the checkbox to be checked only if integration_status is 1
            $status = ($item->integration_status == 1) ? 'checked' : '';
            return sprintf(
                '<label class="iafwzc-setup-toggle-switch">
                <input type="checkbox" class="iafwzc-setup-toggle-input" %s onclick="iafwzc_toggleIntegrationStatus(%d, this)">
                <span class="iafwzc-setup-toggle-slider"></span>
            </label>',
                $status,
                $item->integration_id
            );
        }

        protected function column_action($item)
        {
            $edit_url = add_query_arg(
                [
                    'page' => 'integrate-any-form-with-zoho-crm',
                    'tab' => 'setup',
                    'action' => 'edit',
                    'setup_id' => $item->integration_id,
                    '_wpnonce' => wp_create_nonce('edit_setup_nonce') // Add the nonce to the URL.
                ],
                admin_url('admin.php')
            );

            $delete_url = add_query_arg(
                [
                    'page' => 'integrate-any-form-with-zoho-crm',
                    'tab' => 'setup',
                    'action' => 'delete',
                    'setup_id' => $item->integration_id,
                    '_wpnonce' => wp_create_nonce('delete_setup_nonce') // Add the 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 integration?\\n\\nWarning: Deleting this integration will also remove any associated error logs. This action is irreversible. Do you want to continue?\');" 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_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
            $total_integration = $IAFWZC_Field_MappingDBInstance->getFieldMappingTotalCount();
            $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_integration >= 2 && !$session) ? 'alert(\'Upgrade to the premium version to add more integrations. The free version supports up to 2 integrations only.\');' : 'iafwzc_showIntegrationForm();'); ?>"
                        class="button">
                        <?php esc_html_e('Add Integration', 'integrate-any-form-with-zoho-crm'); ?>
                    </a>
                </div>
            <?php
            }
        }

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

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