<?php
if (!defined('ABSPATH'))
    exit;

if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

class WPSSLC_Forms_List_Table extends WP_List_Table
{

    public function __construct()
    {
        parent::__construct([
            'singular' => 'form',
            'plural' => 'forms',
            'ajax' => false
        ]);
    }

    /* --------------------------
     * COLUMNS
     * -------------------------- */
    public function get_columns()
    {
        return [
            'cb' => '<input type="checkbox" />',
            'status' => 'Save to DB',
            'title' => 'Title',
            'entries' => 'Entries',
            'wpsscsheet' => 'Save to Googlesheet',
        ];
    }

    public function column_wpsscsheet($item)
    {

        $form_id = (int)$item->ID;

        $all_settings = get_post_meta($form_id, 'wpssc_all_settings', true);
        $cf_settings = get_post_meta($form_id, 'wpssc_cf_settings', true);

        // If CF settings not configured
        if (empty($cf_settings)) {

            $configure_link = add_query_arg(
            [
                'page' => 'wpcf7',
                'post' => $form_id,
                'active-tab' => 'google-sheets',
            ],
                admin_url('admin.php')
            );

            return sprintf(
                '<a href="%s" class="button button-secondary">Configure</a>',
                esc_url($configure_link)
            );
        }

        // Otherwise show toggle
        $checked = ('yes' === $all_settings) ? 'checked' : '';

        return sprintf(
            '<label class="wpssc-switch">
                <input type="checkbox" 
                       class="wpssc-toggle-status" 
                       data-id="%d" 
                       %s>
                <span class="wpssc-slider"></span>
            </label>',
            $form_id,
            $checked
        );
    }

    protected function get_sortable_columns()
    {
        return [
            'title' => ['title', true],
        ];
    }

    protected function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="form_ids[]" value="%d" />',
            $item->ID
        );
    }

    /* --------------------------
     * PREPARE ITEMS (Pagination + Search)
     * -------------------------- */
    public function prepare_items()
    {

        $per_page = 10;
        $current_page = $this->get_pagenum();
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only search/sort params, no data mutation.
        $search = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only sort params.
        $orderby = isset($_GET['orderby']) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : 'title';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only sort params.
        $order = isset($_GET['order']) ? strtoupper(sanitize_text_field(wp_unslash($_GET['order']))) : 'ASC';

        $order = ('DESC' === $order) ? 'DESC' : 'ASC';

        // Whitelist sortable fields
        $allowed_sort = ['title'];

        if (!in_array($orderby, $allowed_sort, true)) {
            $orderby = 'title';
        }

        $args = [
            'post_type' => 'wpcf7_contact_form',
            'posts_per_page' => $per_page,
            'paged' => $current_page,
            's' => $search,
            'orderby' => $orderby,
            'order' => $order,
        ];

        if (!empty($search)) {
            $args['s'] = $search;
        }

        $query = new WP_Query($args);

        // IMPORTANT — Required in many cases
        $columns = $this->get_columns();
        $hidden = [];
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = [$columns, $hidden, $sortable];

        $this->items = $query->posts;

        $this->set_pagination_args([
            'total_items' => $query->found_posts,
            'per_page' => $per_page,
        ]);
    }

    /* --------------------------
     * BULK ACTIONS
     * -------------------------- */
    protected function get_bulk_actions()
    {
        return [
            'activate' => 'Activate',
            'deactivate' => 'Deactivate',
        ];
    }

    public function process_bulk_action()
    {

        // Get action
        $action = $this->current_action();

        if (!$action) {
            return;
        }

        // Check selected forms
        if (empty($_POST['form_ids']) || !is_array($_POST['form_ids'])) {
            return;
        }

        // Verify nonce
        if (
        !isset($_POST['_wpnonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'bulk-' . $this->_args['plural'])
        ) {
            return;
        }

        $form_ids = array_map('intval', $_POST['form_ids']);

        foreach ($form_ids as $form_id) {

            $value = ('activate' === $action) ? 'yes' : '';

            update_post_meta($form_id, 'wpssc_enable_db_save', $value);
        }

        // Redirect back
        $page = isset($_REQUEST['page']) ? sanitize_key($_REQUEST['page']) : '';

        wp_safe_redirect(
            add_query_arg(
        [
            'page' => $page,
            'view' => 'forms',
        ],
            admin_url('admin.php')
        )
        );
        exit;
    }

    /* --------------------------
     * STATUS TOGGLE SWITCH (DB SAVE)
     * -------------------------- */
    public function column_status($item)
    {

        $form_id = (int)$item->ID;

        $db_enabled = get_post_meta($form_id, 'wpssc_enable_db_save', true);
        $checked = '';
        $text = 'Inactive';
        $checked_class = 'wpssc-toggle-db-status-inactive';

        if ('yes' === $db_enabled) {
            $checked = 'checked';
            $text = 'Active';
            $checked_class = 'wpssc-toggle-db-status-active';
        }

        return sprintf(
            '<label class="wpssc-switch %s">
                <input type="checkbox" 
                       class="wpssc-toggle-db-status" 
                       data-id="%d"
                       %s>
                <span class="wpssc-slider">%s</span>
            </label>',
            $checked_class,
            $form_id,
            $checked,
            $text
        );
    }

    /* --------------------------
     * TITLE COLUMN
     * -------------------------- */
    public function column_title($item)
    {

        $form_id = (int)$item->ID;

        $edit_link = admin_url(
            'admin.php?page=wpcf7&post=' . $form_id . '&active-tab=google-sheets'
        );

        $entries_link = add_query_arg(
        [
            'page' => isset($_REQUEST['page']) ? sanitize_key(wp_unslash($_REQUEST['page'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Read-only URL param used only for building an admin link; no data is mutated.
            'view' => 'entries',
            'form_id' => $form_id,
        ],
            admin_url('admin.php')
        );

        $actions = [
            'edit' => '<a href="' . esc_url($edit_link) . '">Edit</a>',
            'entries' => '<a href="' . esc_url($entries_link) . '">Entries</a>',
        ];

        return sprintf(
            '<strong>%s</strong> %s',
            esc_html($item->post_title),
            $this->row_actions($actions)
        );
    }

    /* --------------------------
     * ENTRIES (Cached)
     * -------------------------- */
    public function column_entries($item)
    {

        global $wpdb;

        $table_name = esc_sql($wpdb->prefix . 'wpssc_form_entry');
        $form_id = (int)$item->ID;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Per-form entry count for list table; dynamic form ID makes caching impractical.
        $count = $wpdb->get_var(
            $wpdb->prepare(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            "SELECT COUNT(DISTINCT data_id) FROM {$table_name} WHERE cf7_id = %d",
            $form_id
        )
        );

        $count = (int)$count;

        $link = admin_url('admin.php?page=wpsyncsheets-for-contact-form-7&view=entries&form_id=' . $form_id);

        return sprintf(
            '<a href="%s"><strong>%d</strong></a>',
            esc_url($link),
            $count
        );
    }
    protected function pagination($which)
    {

        // Remove top pagination only
        if ('top' === $which) {
            return;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only view routing param used only to build pagination URL; no data mutated.
        $view = isset($_REQUEST['view']) && !empty($_REQUEST['view'])
            ? sanitize_text_field(wp_unslash($_REQUEST['view']))
            : 'forms';
        // phpcs:enable

        $base = add_query_arg(
            array(
            'page' => 'wpsyncsheets-for-contact-form-7',
            'view' => $view,
        ),
            admin_url('admin.php')
        );

        $this->_pagination_args['base'] = $base . '%_%';

        parent::pagination($which);
    }
    public function display()
    {
        $get_table_classes = implode(' ', $this->get_table_classes());
?>
        <div class="tablenav top">
            <div class="alignleft actions bulkactions">
                <?php
        $this->bulk_actions('top'); // Bulk actions 
?>
            </div>
            <br class="clear">
            <?php
        $this->extra_tablenav('top'); // Extra filters if any
?>
        </div>

        <table class="wp-list-table <?php echo esc_attr($get_table_classes); ?>">
            <thead>
                <tr>
                    <?php $this->print_column_headers(); ?>
                </tr>
            </thead>

            <tbody id="the-list">
                <?php $this->display_rows_or_placeholder(); ?>
            </tbody>

            <?php /* Removed tfoot (bottom titles) */?>
        </table>

        <div class="tablenav bottom">
            <?php $this->pagination('bottom'); ?>
        </div>
        <?php
    }
}