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

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

class ScholarSync_AuthorsListTableClass extends WP_List_Table {

    const PER_PAGE = 10;

    public function __construct() {
        parent::__construct( array(
            'singular' => 'scholar-sync-author',
            'plural'   => 'scholar-sync-authors',
            'ajax'     => false,
        ) );
    }

    public function prepare_items() {
        $add_author = isset( $_GET['add'] ) ? sanitize_text_field( wp_unslash( $_GET['add'] ) ) : '';
        if (!empty($add_author)) {
            echo 'to do check that redirtect if there are no authors';
//            add_new_author($add_author);
            require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/add_author.php';
        }
        $order_by = isset( $_GET['orderby'] ) ? sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) : '';
        $order    = isset( $_GET['order'] )   ? sanitize_text_field( wp_unslash( $_GET['order'] ) )   : '';
        $search_term = isset($_GET['s']) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
        $records = $this->get_table_data($order_by, $order,  $search_term);

        $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($order_by = '', $order = '', $search_term = '') {
        global $wpdb;

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

        $data = array();
        $table_name = SCHOLAR_SYNC_DB_AUTHORS;

        // ORDER BY is built only from allowlisted values: the column is passed as a %i
        // identifier placeholder and the direction is a hardcoded ASC/DESC literal, so no
        // value is ever interpolated into the SQL string.
        if ( ! empty( $search_term ) ) {
            $like = '%' . $wpdb->esc_like( $search_term ) . '%';
            if ( $safe_orderby === '' ) {
                $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare( "SELECT * FROM %i WHERE CONCAT_WS(' ', name, affiliations) LIKE %s", $table_name, $like )
                );
            } elseif ( $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(' ', name, affiliations) LIKE %s ORDER BY %i ASC", $table_name, $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(' ', name, affiliations) LIKE %s ORDER BY %i DESC", $table_name, $like, $safe_orderby )
                );
            }
        } else {
            if ( $safe_orderby === '' ) {
                $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare( 'SELECT * FROM %i', $table_name )
                );
            } elseif ( $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_name, $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_name, $safe_orderby )
                );
            }
        }
        foreach ($results as $result) {
            $data[] = array(
                "id" => $result->author_id,
                "name" => $result->name,
                "affiliations" => $result->affiliations,
                "thumbnail" => $result->thumbnail
            );
        }
        return $data;
    }

    public function get_hidden_columns() {
        // option to hide columns
        return array();
    }

    public function get_sortable_columns() {
        // false as #2 parameter indicates asc order
        return array(
            "name" => array("name", false),
            "date_created" => array("created", false)
        );
    }

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

    public function get_columns() {
        return array(
            'cb' => '<input type="checkbox" />',
            'name' => __( 'Name', 'scholar-sync' ),
            'articles_count' => __( 'No. of articles', 'scholar-sync' ),
            'thumbnail' => __( 'Thumbnail', 'scholar-sync' ),
            'date_created' => __( 'Date', 'scholar-sync' )
        );
    }

    public function column_default( $item, $column_name ) {
        switch ($column_name) {
            case "id":
            case "name":
            case "affiliations":
                return $item[$column_name];
            case "thumbnail":
                $img_url  = empty( $item[$column_name] ) ? SCHOLAR_SYNC_PLUGIN_URL . 'includes/images/blank_profile.png' : $item[$column_name];
                $edit_url = add_query_arg( array(
                    'page'      => 'scholar-sync-authors-slug',
                    'author-id' => (int) $item['id'],
                    'highlight' => 'thumbnail',
                ), admin_url( 'admin.php' ) );
                return sprintf(
                    '<a href="%s"><img src="%s" alt="Author image" width="50" height="50"></a>',
                    esc_url( $edit_url ),
                    esc_url( $img_url )
                );
            case "articles_count":
                $count = $this->get_articles_count($item['id']);
                if ($count == 0) {
                    return '0';
                } else {
                    $ahref = '<a href="' . esc_url( admin_url( 'admin.php?page=scholar-sync-authors-slug&tab=1&author-id=' . (int) $item['id'] ) ) . '">' . (int) $count . '</a>';
                    return $ahref;
                }
            case "date_created":
                return "Created:<br/>" . $this->get_date_created($item['id']);
            default:
                return "not found";
        }
    }

    private function get_articles_count($author_id) {
        global $wpdb;
        $table_name = SCHOLAR_SYNC_DB_ARTICLES;
        return $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->prepare('SELECT COUNT(*) FROM %i WHERE author_id = %d AND is_active = 1', $table_name, $author_id) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
        );
    }

    public function get_number_of_authors() {
        return count($this->get_table_data());
    }

    private function get_date_created($author_id) {
        global $wpdb;
        $table_name = SCHOLAR_SYNC_DB_AUTHORS;
        return $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->prepare('SELECT created FROM %i WHERE author_id = %d', $table_name, $author_id) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
        );
    }
    public function column_cb($item) {
        return sprintf('<input type="checkbox" name="post[]" value="%s" />', esc_attr($item['id']));
    }

    public function column_name($item) {
        $actions = array(
            'edit'    => sprintf('<a href="%s">Edit</a>', esc_url(add_query_arg(array('page' => 'scholar-sync-authors-slug', 'author-id' => (int) $item['id']), admin_url('admin.php')))),
            'delete'  => sprintf('<a href="%s" style="color:#b32d2e;" onclick="return confirm(\'Are you sure you want to delete this researcher? This cannot be undone.\')">Delete</a>', wp_nonce_url(add_query_arg(array('page' => 'scholar-sync-actions-slug', 'action' => 'delete-author', 'author-id' => (int) $item['id']), admin_url('admin.php')), 'scholar_sync_delete_author')),
            'preview' => sprintf('<a href="%s" target="wp-preview-author-%d">Preview &amp; Publish</a>', esc_url(wp_nonce_url(add_query_arg(array('page' => 'scholar-sync-preview-slug', 'author-id' => (int) $item['id']), admin_url('admin.php')), 'scholar_sync_preview')), (int) $item['id']),
            'sync'    => sprintf('<a href="%s">Sync</a>', esc_url(add_query_arg(array('page' => 'scholar-sync-authors-slug', 'author-id' => (int) $item['id'], 'tab' => 2), admin_url('admin.php'))))
        );
        return sprintf('%1$s %2$s', esc_html($item['name']), $this->row_actions($actions));
    }
}

function scholar_sync_authors_list_table_layout()
{

    $scholar_sync_list_table = new ScholarSync_AuthorsListTableClass();

    $scholar_sync_list_table->prepare_items();
    echo '<div class="wrap">';
    echo '<h1 class="wp-heading-inline">' . esc_html__('Scholar List', 'scholar-sync') .  '</h1>';
    echo '<a href="' . esc_url( admin_url( 'admin.php?page=scholar-sync-add-author-slug' ) ) . '" class="page-title-action">Add New</a>';
    echo '<hr class="wp-header-end">';

    if ( ! empty( $_GET['msg'] )
         && isset( $_GET['_wpnonce'] )
         && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'scholar_sync_notice' ) ) {
        $msg = new scholar_sync_message( sanitize_key( wp_unslash( $_GET['msg'] ) ) );
    }
    echo '<form method="GET" name="frm_search_post">';
    echo '<input type="hidden" name="page" value="scholar-sync-authors-slug">';
    $scholar_sync_list_table->search_box('Search Scholar(s)', 'search_post_id');

    echo '</form>';
    echo '<form id="bulk-actions" method="POST">';

    $scholar_sync_list_table->display();

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

}

scholar_sync_authors_list_table_layout();
