<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.Security.NonceVerification -- read-only author search form; capability check handled by admin menu registration
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- search input sanitized via sanitize_text_field/wp_unslash below

require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
require_once SCHOLAR_SYNC_PLUGIN_DIR . '/includes/class-scholar-sync-data-source.php';

class ScholarSync_NewAuthorListTableClass extends WP_List_Table {

    const MIN_INPUT_LENGTH = 4;

    private $has_error = false;

    public function has_error() {
        return $this->has_error;
    }

    public function prepare_items() {
        if ( $this->has_search_term() ) {
            $data = $this->get_table_data();
            if ( isset( $data['message'] ) ) {
                $this->has_error = true;
                echo wp_kses_post( $data['message'] );
            }
            if ( isset( $data['profiles'] ) && ! empty( $data['profiles'] ) ) {
                $this->items = $data['profiles'];
            }
            $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_search_term() {
        return isset( $_POST['add_author_search_input'] ) ? sanitize_text_field( wp_unslash( $_POST['add_author_search_input'] ) ) : '';
    }

    public function has_search_term() {
        return ( strlen( $this->get_search_term() ) >= self::MIN_INPUT_LENGTH );
    }

    public function after_prepare_items() {
        if ( isset( $_POST['add_author_search_input'] ) && ! $this->has_search_term() ) {
            echo '<div class="scholar-sync-alert">' . esc_html__( 'Name should be at least 4 characters', 'scholar-sync' ) . '</div>';
        }
    }

    public function get_table_data() {
        $out    = array();
        $source = scholar_sync_get_data_source();
        $result = $source->search_authors( $this->get_search_term() );
        if ( is_wp_error( $result ) ) {
            $out = array(
                'message'  => '<div class="notice error"><p><strong>' . esc_html__( 'Error', 'scholar-sync' ) . ':</strong> ' . esc_html( $result->get_error_message() ) . '</p></div>',
                'profiles' => array(),
            );
        } else {
            if ( isset( $result['profiles'] ) && is_array( $result['profiles'] ) ) {
                $out['profiles'] = self::get_search_results_display( $result['profiles'] );
            }
        }
        return $out;
    }

    private static function get_search_results_display( $profiles ) {
        $data = array();
        foreach ( $profiles as $profile ) {
            if ( ! is_array( $profile ) ) {
                continue;
            }
            $affiliations = '';
            if ( ! empty( $profile['affiliations'] ) && is_array( $profile['affiliations'] ) ) {
                $affiliations = implode( ', ', $profile['affiliations'] );
            }
            $interests = '';
            if ( ! empty( $profile['interests'] ) && is_array( $profile['interests'] ) ) {
                $interests = implode( ', ', $profile['interests'] );
            }
            $data[] = array(
                'id'             => $profile['author_id']       ?? '',
                'name'           => $profile['name']            ?? '',
                'works_count'    => (int) ( $profile['works_count']     ?? 0 ),
                'h_index'        => (int) ( $profile['h_index']         ?? 0 ),
                'affiliations'   => $affiliations,
                'citations'      => (int) ( $profile['citations_count'] ?? 0 ),
                'i10_index'      => (int) ( $profile['i10_index']       ?? 0 ),
                'interests'      => $interests,
                'counts_by_year' => $profile['counts_by_year']  ?? array(),
            );
        }
        return $data;
    }

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

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

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

    public function get_columns() {
        return array(
            'id'           => '',
            'name'         => __( 'Name', 'scholar-sync' ),
            'works_count'  => __( 'Works', 'scholar-sync' ),
            'h_index'      => __( 'H-Index', 'scholar-sync' ),
            'affiliations' => __( 'Affiliations', 'scholar-sync' ),
        );
    }

    protected function get_primary_column_name() {
        return 'name';
    }

    public function column_default( $item, $column_name ) {
        switch ( $column_name ) {
            case 'id':
                return '<button type="button"'
                    . ' class="button button-small scholar-sync-add-btn"'
                    . ' data-id="'             . esc_attr( $item['id'] )                                      . '"'
                    . ' data-name="'           . esc_attr( $item['name'] )                                    . '"'
                    . ' data-affiliations="'   . esc_attr( $item['affiliations'] )                            . '"'
                    . ' data-h-index="'        . esc_attr( (string) $item['h_index'] )                        . '"'
                    . ' data-citations="'      . esc_attr( (string) $item['citations'] )                      . '"'
                    . ' data-i10-index="'      . esc_attr( (string) $item['i10_index'] )                      . '"'
                    . ' data-interests="'      . esc_attr( $item['interests'] )                               . '"'
                    . ' data-counts-by-year="' . esc_attr( wp_json_encode( $item['counts_by_year'] ) )        . '"'
                    . '>' . esc_html__( 'Add', 'scholar-sync' ) . '</button>';
            case 'name':
            case 'affiliations':
                return esc_html( $item[ $column_name ] );
            case 'works_count':
            case 'h_index':
                return esc_html( (int) $item[ $column_name ] );
            default:
                return '';
        }
    }
}

function scholar_sync_list_table_layout() {
    $scholar_sync_list_table = new ScholarSync_NewAuthorListTableClass();
    $scholar_sync_list_table->prepare_items();

    echo '<div class="wrap">';
    echo '<h1 class="wp-heading-inline">' . esc_html__( 'Add New Author', 'scholar-sync' ) . '</h1>';
    echo '<form method="post" id="search-author-form" onsubmit="clickSubmitSearchAuthor()">';

    echo '<label class="screen-reader-text" for="add_author_search_input">' . esc_html__( 'Search Author:', 'scholar-sync' ) . '</label>';
    echo '<input type="search" id="add_author_search_input" size="40" name="add_author_search_input"
        placeholder="' . esc_attr__( 'Type in first and last name', 'scholar-sync' ) . '"
        value="' . esc_attr( $scholar_sync_list_table->get_search_term() ) . '">';
    echo '<input type="submit" id="search-submit" class="button" value="' . esc_attr__( 'Search & Add Author', 'scholar-sync' ) . '">';

    echo '<div id="message_display" class="scholar-sync-alert" style="display: none"></div>';
    echo '</form>';

    echo '<p class="scholar-sync-manual-hint">'
        . esc_html__( "Can't find the author?", 'scholar-sync' ) . ' '
        . '<a href="' . esc_url( admin_url( 'admin.php?page=scholar-sync-add-author-slug&manual' ) ) . '" class="scholar-sync-manual-link">'
        . esc_html__( 'Add Manually', 'scholar-sync' )
        . '</a></p>';


    echo '<div id="search-author-loader" style="display:none">';
    echo '<image id="image-wait" src="' . esc_url( SCHOLAR_SYNC_PLUGIN_URL . 'includes/images/wait.gif' ) . '" style="width: 200px;height: 200px;">';
    echo '<div>' . esc_html__( 'Loading...', 'scholar-sync' ) . '</div>';
    echo '</div>';

    $scholar_sync_list_table->after_prepare_items();

    if ( $scholar_sync_list_table->has_search_term() ) {
        if ( ! $scholar_sync_list_table->has_error() ) {
            $scholar_sync_list_table->display();
        }
        if ( ! empty( $scholar_sync_list_table->items ) ) {
            scholar_sync_display_instruction_step2();
        }
    } else {
        scholar_sync_display_instruction_step1();
    }

    echo '</div>';
}

function scholar_sync_display_instruction_step2() {
    $option_name = 'scholar-sync-add-author-step2';
    if ( get_option( $option_name, false ) === false ) {
        $title   = esc_js( __( 'Step 2/3 — Add', 'scholar-sync' ) );
        $message = esc_js( __( "Click 'Add' next to the required author or search again", 'scholar-sync' ) );
        $point   = '{x: "50%",y: "5%"}';
        wp_print_inline_script_tag( 'openInstructions("' . $title . '","' . $message . '",' . $point . ',"' . esc_js( $option_name ) . '")' );
    }
}

function scholar_sync_display_instruction_step1() {
    $option_name = 'scholar-sync-add-author-step1';
    if ( get_option( $option_name, false ) === false ) {
        $title   = esc_js( __( 'Step 1/3 — Search', 'scholar-sync' ) );
        $message = esc_js( __( 'Enter author first, last name and click the button.', 'scholar-sync' ) );
        $point   = '{x: "50%",y: "5%"}';
        wp_print_inline_script_tag( 'openInstructions("' . $title . '","' . $message . '",' . $point . ',"' . esc_js( $option_name ) . '")' );
    }
}

scholar_sync_list_table_layout();
