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

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

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

                'action'            => __('Action', 'integrate-with-zoho-desk'),
            ];
            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()
        {
            $IAFWZDESK_Field_MappingDBInstance = new IAFWZDESK_Field_Mapping();
            $IAFWZDESK_Id_MappingInstance = new IAFWZDESK_Id_Mapping();
            $IAFWZDESK_Form_NameInstance = new IAFWZDESK_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 = $IAFWZDESK_Field_MappingDBInstance->get_all_mappings();
            $iafwzdesk_allowed_orderby = array_keys($sortable);
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $iafwzdesk_raw_orderby = isset($_GET['orderby']) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : '';
            $orderby = in_array($iafwzdesk_raw_orderby, $iafwzdesk_allowed_orderby, true) ? $iafwzdesk_raw_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, $IAFWZDESK_Id_MappingInstance, $IAFWZDESK_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 = $IAFWZDESK_Id_MappingInstance->get_plugin_name_by_id((int)$a->form_group_id);
                        $valueB = $IAFWZDESK_Id_MappingInstance->get_plugin_name_by_id((int)$b->form_group_id);
                        $result = strcmp((string)$valueA, (string)$valueB);
                    } elseif ($orderby === 'form_name') {
                        $valueA = $IAFWZDESK_Form_NameInstance->getFormName((int)$a->form_group_id, (int)$a->form_id);
                        $valueB = $IAFWZDESK_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-with-zoho-desk');
        }

        protected function column_form_type($item)
        {
            $IAFWZDESK_Id_MappingInstance = new IAFWZDESK_Id_Mapping();
            $form_type = $IAFWZDESK_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-with-zoho-desk') // Form type name
            );
        }

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

            $form_name = $IAFWZDESK_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="iafwzdesk-setup-toggle-switch">
                <input type="checkbox" class="iafwzdesk-setup-toggle-input" %s onclick="iafwzdesk_toggleIntegrationStatus(%d, this)">
                <span class="iafwzdesk-setup-toggle-slider"></span>
            </label>',
                $status,
                $item->integration_id
            );
        }

        protected function column_action($item)
        {
            $edit_url = add_query_arg(
                [
                    'page' => 'integrate-with-zoho-desk',
                    '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-with-zoho-desk',
                    '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-with-zoho-desk'),
                esc_url($delete_url),
                __('Delete', 'integrate-with-zoho-desk')
            );
        }

        public function extra_tablenav($which)
        {
            $IAFWZDESK_Field_MappingDBInstance = new IAFWZDESK_Field_Mapping();
            $total_integration = $IAFWZDESK_Field_MappingDBInstance->getFieldMappingTotalCount();
            $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_integration >= 2 && !$session) ? 'alert(\'Upgrade to the premium version to add more integrations. The free version supports up to 2 integrations only.\');' : 'iafwzdesk_showIntegrationForm();'; ?>"
                        class="button">
                        <?php esc_html_e('Add Integration', 'integrate-with-zoho-desk'); ?>
                    </a>
                </div>
            <?php
            }
        }

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

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