<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.Security.NonceVerification -- read-only list table; capability check handled by admin menu registration
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- GET/POST/REQUEST params cast to int or sanitized with sanitize_key/absint

require_once SCHOLAR_SYNC_PLUGIN_DIR . '/admin/scholar_sync_functions.php';

class ScholarSync_GroupsListTableClass extends WP_List_Table {

    const PER_PAGE = 20;

    public function __construct() {
        parent::__construct( array(
            'singular' => 'group',
            'plural'   => 'groups',
            'ajax'     => false,
        ) );
    }

    public function prepare_items() {
        $search_term = isset( $_REQUEST['s'] )   ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) )   : '';
        $order_by    = isset( $_GET['orderby'] ) ? sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) : '';
        $order       = isset( $_GET['order'] )   ? sanitize_text_field( wp_unslash( $_GET['order'] ) )   : '';

        $records = $this->get_table_data( $search_term, $order_by, $order );

        $this->set_pagination_args( array(
            'total_items' => count( $records ),
            'per_page'    => self::PER_PAGE,
        ) );
        $this->items = array_slice( $records, ( $this->get_pagenum() - 1 ) * self::PER_PAGE, self::PER_PAGE );

        $columns                = $this->get_columns();
        $hidden_columns         = $this->get_hidden_columns();
        $sortable_columns       = $this->get_sortable_columns();
        $this->_column_headers  = array( $columns, $hidden_columns, $sortable_columns );
    }

    public function get_table_data( $search_term = '', $order_by = '', $order = '' ) {
        global $wpdb;
        $groups_table  = SCHOLAR_SYNC_DB_GROUPS;
        $members_table = SCHOLAR_SYNC_DB_GROUP_AUTHORS;

        $allowed_orderby = array( 'name', 'created', 'member_count' );
        $allowed_order   = array( 'ASC', 'DESC' );
        $safe_orderby    = in_array( $order_by, $allowed_orderby, true ) ? $order_by : 'created';
        $safe_order      = in_array( strtoupper( $order ), $allowed_order, true ) ? strtoupper( $order ) : 'DESC';

        // ORDER BY uses only allowlisted values: the column is a %i identifier placeholder and
        // the direction is a hardcoded ASC/DESC literal, so nothing untrusted is interpolated.
        if ( ! empty( $search_term ) ) {
            $like = '%' . $wpdb->esc_like( $search_term ) . '%';
            if ( $safe_order === 'ASC' ) {
                $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare(
                        "SELECT g.group_id, g.name, g.view_type, g.created, COUNT(ga.id) AS member_count
                         FROM %i g LEFT JOIN %i ga ON ga.group_id = g.group_id
                         WHERE g.name LIKE %s GROUP BY g.group_id ORDER BY %i ASC",
                        $groups_table, $members_table, $like, $safe_orderby
                    )
                );
            } else {
                $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare(
                        "SELECT g.group_id, g.name, g.view_type, g.created, COUNT(ga.id) AS member_count
                         FROM %i g LEFT JOIN %i ga ON ga.group_id = g.group_id
                         WHERE g.name LIKE %s GROUP BY g.group_id ORDER BY %i DESC",
                        $groups_table, $members_table, $like, $safe_orderby
                    )
                );
            }
        } else {
            if ( $safe_order === 'ASC' ) {
                $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare(
                        "SELECT g.group_id, g.name, g.view_type, g.created, COUNT(ga.id) AS member_count
                         FROM %i g LEFT JOIN %i ga ON ga.group_id = g.group_id
                         GROUP BY g.group_id ORDER BY %i ASC",
                        $groups_table, $members_table, $safe_orderby
                    )
                );
            } else {
                $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare(
                        "SELECT g.group_id, g.name, g.view_type, g.created, COUNT(ga.id) AS member_count
                         FROM %i g LEFT JOIN %i ga ON ga.group_id = g.group_id
                         GROUP BY g.group_id ORDER BY %i DESC",
                        $groups_table, $members_table, $safe_orderby
                    )
                );
            }
        }

        $data = array();
        foreach ( $results as $row ) {
            $data[] = array(
                'id'           => $row->group_id,
                'name'         => $row->name,
                'view_type'    => $row->view_type,
                'member_count' => (int) $row->member_count,
                'created'      => $row->created,
            );
        }
        return $data;
    }

    public function get_hidden_columns() {
        return array();
    }

    public function get_sortable_columns() {
        return array(
            'name'         => array( 'name',         false ),
            'member_count' => array( 'member_count', false ),
            'created'      => array( 'created',      false ),
        );
    }

    public function get_bulk_actions() {
        return array(
            'delete-group' => __( 'Delete', 'scholar-sync' ),
        );
    }

    public function get_columns() {
        return array(
            'cb'           => '<input type="checkbox" />',
            'name'         => __( 'Name', 'scholar-sync' ),
            'view_type'    => __( 'View Type', 'scholar-sync' ),
            'member_count' => __( 'Members', 'scholar-sync' ),
            'created'      => __( 'Created', 'scholar-sync' ),
        );
    }

    public function column_cb( $item ) {
        return sprintf( '<input type="checkbox" name="post[]" value="%s" />', (int) $item['id'] );
    }

    public function column_name( $item ) {
        $edit_url    = add_query_arg( array( 'page' => 'scholar-sync-groups-slug', 'group-id' => $item['id'] ), admin_url( 'admin.php' ) );
        $preview_url = add_query_arg( array( 'page' => 'scholar-sync-preview-group-slug', 'group-id' => $item['id'] ), admin_url( 'admin.php' ) );
        $delete_url  = wp_nonce_url(
            add_query_arg( array( 'page' => 'scholar-sync-actions-slug', 'action' => 'delete-group', 'group-id' => $item['id'] ), admin_url( 'admin.php' ) ),
            'scholar_sync_delete_group'
        );
        $actions = array(
            'edit'    => sprintf( '<a href="%s">%s</a>', esc_url( $edit_url ), esc_html__( 'Edit', 'scholar-sync' ) ),
            'delete'  => sprintf( '<a href="%s" onclick="return confirm(\'%s\')" style="color:#b32d2e;">%s</a>', esc_url( $delete_url ), esc_js( __( 'Delete this group?', 'scholar-sync' ) ), esc_html__( 'Delete', 'scholar-sync' ) ),
            'preview' => sprintf( '<a href="%s" target="wp-preview-group-%d">%s</a>', esc_url( $preview_url ), (int) $item['id'], esc_html__( 'Preview &amp; Publish', 'scholar-sync' ) ),
        );
        return sprintf( '%s %s', esc_html( $item['name'] ), $this->row_actions( $actions ) );
    }

    public function column_default( $item, $column_name ) {
        switch ( $column_name ) {
            case 'view_type':
                return $item['view_type'] === 'feed'
                    ? esc_html__( 'Research Feed', 'scholar-sync' )
                    : esc_html__( 'Staff Directory (Grid)', 'scholar-sync' );
            case 'member_count':
                return (int) $item['member_count'];
            case 'created':
                return esc_html( $item['created'] );
            default:
                return '';
        }
    }
}

function scholar_sync_manage_bulk_delete_groups() {
    check_admin_referer( 'bulk-groups' );
    require_once SCHOLAR_SYNC_PLUGIN_DIR . '/admin/actions/delete_group.php';
    $post_ids = isset( $_POST['post'] ) ? array_map( 'intval', (array) wp_unslash( $_POST['post'] ) ) : array();
    scholar_sync_delete_groups( $post_ids );
    return count( $post_ids );
}

$scholar_sync_bulk_groups_deleted = 0;
if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST'
    && isset( $_POST['action'] )
    && sanitize_key( wp_unslash( $_POST['action'] ) ) === 'delete-group'
    && ! empty( $_POST['post'] )
) {
    $scholar_sync_bulk_groups_deleted = scholar_sync_manage_bulk_delete_groups();
}

// Render the list table.
$scholar_sync_groups_table = new ScholarSync_GroupsListTableClass();
$scholar_sync_groups_table->prepare_items();

echo '<div class="wrap">';
echo '<h1 class="wp-heading-inline">' . esc_html__( 'Groups', 'scholar-sync' ) . '</h1>';
echo '<a href="' . esc_url( add_query_arg( array( 'page' => 'scholar-sync-groups-slug', 'action' => 'new-group' ), admin_url( 'admin.php' ) ) ) . '" class="page-title-action">' . esc_html__( 'Add New', 'scholar-sync' ) . '</a>';
echo '<hr class="wp-header-end">';

if ( ! empty( $_GET['msg'] ) && $_GET['msg'] === 'saved'
     && isset( $_GET['_wpnonce'] )
     && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'scholar_sync_notice' ) ) {
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Group saved.', 'scholar-sync' ) . '</p></div>';
}
if ( ! empty( $scholar_sync_bulk_groups_deleted ) ) {
    /* translators: %d: number of groups deleted */
    echo '<div class="notice notice-success is-dismissible"><p>' . sprintf( esc_html__( '%d group(s) deleted.', 'scholar-sync' ), (int) $scholar_sync_bulk_groups_deleted ) . '</p></div>';
}

echo '<form method="GET">';
echo '<input type="hidden" name="page" value="scholar-sync-groups-slug">';
$scholar_sync_groups_table->search_box( esc_html__( 'Search Groups', 'scholar-sync' ), 'group_search' );
echo '</form>';

echo '<form id="bulk-actions" method="POST">';
$scholar_sync_groups_table->display();

echo '</form>';
echo '</div>';
