<?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/REQUEST params cast to int or sanitized with absint/sanitize_key

require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';

class ScholarSync_CoAuthorsListTableClass extends WP_List_Table {

    const PER_PAGE = 20;

    public function __construct() {
        parent::__construct( array(
            'singular' => 'co_author',
            'plural'   => 'co_authors',
            '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;
        $table = SCHOLAR_SYNC_DB_CO_AUTHORS;

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

        // 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 * FROM %i WHERE CONCAT_WS(' ', full_name, short_name, affiliations, profile_link) LIKE %s ORDER BY %i ASC",
                        $table, $like, $safe_orderby
                    )
                );
            } else {
                $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare(
                        "SELECT * FROM %i WHERE CONCAT_WS(' ', full_name, short_name, affiliations, profile_link) LIKE %s ORDER BY %i DESC",
                        $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 * FROM %i ORDER BY %i ASC', $table, $safe_orderby )
                );
            } else {
                $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare( 'SELECT * FROM %i ORDER BY %i DESC', $table, $safe_orderby )
                );
            }
        }

        $data = array();
        foreach ( $results as $row ) {
            $data[] = array(
                'co_author_id' => $row->co_author_id,
                'full_name'    => $row->full_name,
                'short_name'   => $row->short_name,
                'image_url'    => $row->image_url,
                'affiliations' => $row->affiliations,
                'created'      => $row->created,
            );
        }
        return $data;
    }

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

    public function get_sortable_columns() {
        return array(
            'full_name'    => array( 'full_name',    false ),
            'short_name'   => array( 'short_name',   false ),
            'affiliations' => array( 'affiliations', false ),
            'date_created' => array( 'created',      false ),
        );
    }

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

    public function get_columns() {
        return array(
            'cb'           => '<input type="checkbox" />',
            'full_name'    => __( 'Full Name',    'scholar-sync' ),
            'short_name'   => __( 'Short Name',   'scholar-sync' ),
            'thumbnail'    => __( 'Thumbnail',    'scholar-sync' ),
            'affiliations' => __( 'Affiliations', 'scholar-sync' ),
            'date_created' => __( 'Date',         'scholar-sync' ),
        );
    }

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

    public function column_full_name( $item ) {
        $edit_url = wp_nonce_url(
            add_query_arg( array(
                'page'         => 'scholar-sync-co-authors-slug',
                'action'       => 'edit',
                'co-author-id' => $item['co_author_id'],
            ), admin_url( 'admin.php' ) ),
            'scholar_sync_edit_co_author'
        );

        $delete_url = wp_nonce_url(
            add_query_arg( array(
                'page'         => 'scholar-sync-actions-slug',
                'action'       => 'delete-co-author',
                'co-author-id' => $item['co_author_id'],
            ), admin_url( 'admin.php' ) ),
            'scholar_sync_delete_co_author'
        );

        $actions = array(
            'edit'   => sprintf( '<a href="%s">%s</a>', esc_url( $edit_url ), esc_html__( 'Edit', 'scholar-sync' ) ),
            'delete' => sprintf(
                '<a href="%s" style="color:#b32d2e;" onclick="return confirm(\'%s\')">%s</a>',
                esc_url( $delete_url ),
                esc_js( __( 'Delete this co-author?', 'scholar-sync' ) ),
                esc_html__( 'Delete', 'scholar-sync' )
            ),
        );

        return sprintf( '%s %s', esc_html( $item['full_name'] ), $this->row_actions( $actions ) );
    }

    public function column_default( $item, $column_name ) {
        switch ( $column_name ) {
            case 'thumbnail':
                $img_url  = ! empty( $item['image_url'] )
                    ? $item['image_url']
                    : SCHOLAR_SYNC_PLUGIN_URL . 'includes/images/blank_profile.png';
                $edit_url = wp_nonce_url(
                    add_query_arg( array(
                        'page'         => 'scholar-sync-co-authors-slug',
                        'action'       => 'edit',
                        'co-author-id' => $item['co_author_id'],
                        'highlight'    => 'thumbnail',
                    ), admin_url( 'admin.php' ) ),
                    'scholar_sync_edit_co_author'
                );
                return sprintf(
                    '<a href="%s"><img src="%s" alt="%s" width="40" height="40" style="border-radius:50%%;object-fit:cover;"></a>',
                    esc_url( $edit_url ),
                    esc_url( $img_url ),
                    esc_attr( $item['full_name'] )
                );
            case 'short_name':
                return esc_html( $item['short_name'] );
            case 'affiliations':
                return esc_html( $item['affiliations'] ?? '' );
            case 'date_created':
                return 'Created:<br/>' . esc_html( $item['created'] );
            default:
                return '';
        }
    }
}

// Handle bulk delete.
function scholar_sync_co_authors_handle_bulk_delete() {
    check_admin_referer( 'bulk-co_authors' );
    global $wpdb;
    $ids = array_map( 'intval', $_POST['post'] );
    // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Deletion bypasses cache safely
    foreach ( $ids as $id ) {
        $wpdb->delete( SCHOLAR_SYNC_DB_CO_AUTHORS, array( 'co_author_id' => $id ), array( '%d' ) );
    }
    // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $scholar_sync_bulk_deleted = count( $ids );
}

if ( $_SERVER['REQUEST_METHOD'] === 'POST'
    && isset( $_POST['action'] )
    && $_POST['action'] === 'delete-co-author'
    && ! empty( $_POST['post'] )
) {
    scholar_sync_co_authors_handle_bulk_delete();
}

// Render.
$scholar_sync_co_authors_table = new ScholarSync_CoAuthorsListTableClass();
$scholar_sync_co_authors_table->prepare_items();

echo '<div class="wrap">';
echo '<h1 class="wp-heading-inline">' . esc_html__( 'Co-Authors', 'scholar-sync' ) . '</h1>';
echo '<a href="' . esc_url( add_query_arg( array( 'page' => 'scholar-sync-co-authors-slug', 'action' => 'create' ), admin_url( 'admin.php' ) ) ) . '" class="page-title-action">' . esc_html__( 'Add New Co-Author', '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__( 'Co-author saved.', 'scholar-sync' ) . '</p></div>';
}
if ( ! empty( $scholar_sync_bulk_deleted ) ) {
    /* translators: %d: number of co-authors deleted */
    echo '<div class="notice notice-success is-dismissible"><p>' . sprintf( esc_html__( '%d co-author(s) deleted.', 'scholar-sync' ), (int) $scholar_sync_bulk_deleted ) . '</p></div>';
}

echo '<form method="GET">';
echo '<input type="hidden" name="page" value="scholar-sync-co-authors-slug">';
$scholar_sync_co_authors_table->search_box( esc_html__( 'Search Co-Authors', 'scholar-sync' ), 'co_author_search' );
echo '</form>';

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

echo '</div>';
