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

class ScholarSync_Author_Display
{
    private $author_id;
    private $display_header;
    private $display_search;
    private $display_cited_by;
    private $display_co_authors;
    private $image_shape;
    private $image_shadow;
    private $display_article_image;
    private $display_co_author_photos;
    private $sort_by;

    private $is_preview_mode = false;
    private $author_scholar_id;

    public function __construct($author_id, $display_header, $display_search, $display_cited_by, $display_co_authors = true, $image_shape = 'circle', $image_shadow = true, $display_article_image = true, $display_co_author_photos = true, $sort_by = '') {

        $this->author_id = $author_id;
        $this->display_header = $display_header;
        $this->display_search = $display_search;
        $this->display_cited_by = $display_cited_by;
        $this->display_co_authors = $display_co_authors;
        $this->image_shape = in_array( $image_shape, array( 'circle', 'square' ), true ) ? $image_shape : 'circle';
        $this->image_shadow = (bool) $image_shadow;
        $this->display_article_image = (bool) $display_article_image;
        $this->display_co_author_photos = (bool) $display_co_author_photos;
        $this->sort_by = sanitize_key( $sort_by );
    }

    public function setPreviewMode($is_preview_mode) {
        $this->is_preview_mode = $is_preview_mode;
    }

    private function getInterestsLinks($comma_separated_interests) {
        if ( empty( $comma_separated_interests ) ) {
            return '';
        }
        $arr = array_filter( array_map( 'trim', explode( ',', $comma_separated_interests ) ) );
        if ( empty( $arr ) ) {
            return '';
        }
        $html = '';
        if (count($arr) != 0) {
            $base_url = 'https://openalex.org/works?search=';
            $html = '<ul class="scholar-sync-interests-list">';
            foreach ($arr as $item) {
                $html .= '<li><a href="' . esc_url( $base_url . rawurlencode( $item ) ) . '" target="_blank">' . esc_html($item) . '</a></li>';
            }
            $html .= '</ul>';
        }
        return $html;
    }

    public function display() {

        if ( ! isset( $this->author_id ) ) {
            return '<h3>The "author-id" parameter is missing</h3>';
        }

        global $wpdb;
        $author = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Read bypasses cache safely
            $wpdb->prepare( 'SELECT * FROM %i WHERE author_id = %d', SCHOLAR_SYNC_DB_AUTHORS, $this->author_id ) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
        );
        if ( ! $author ) {
            return '<p>' . esc_html__( 'Author not found.', 'scholar-sync' ) . '</p>';
        }

        $author_name            = $author->name;
        $this->author_scholar_id = $author->scholar_id;

        $out = '';

        // Enqueue stylesheets via the WordPress API. wp_print_styles() in the preview pages
        // outputs them inside <head>; wp_head() handles them in the normal shortcode context.
        wp_enqueue_style( 'scholar-sync-public', SCHOLAR_SYNC_PLUGIN_URL . 'public/css/scholar-sync-public.css', array(), SCHOLAR_SYNC_VERSION );

        if ( $this->is_preview_mode ) {
            wp_enqueue_style( 'scholar-sync-preview', SCHOLAR_SYNC_PLUGIN_URL . 'admin/css/scholar-sync-preview.css', array(), SCHOLAR_SYNC_VERSION );

            // Enqueue the preview scripts BEFORE getMenu() so the handle
            // 'scholar-sync-create-page' is registered when getMenu() attaches its
            // inline data (scholarSyncAjaxUrl/Nonce/AuthorId) — wp_add_inline_script()
            // silently drops data added to a not-yet-registered handle.
            $ajax_object = wp_json_encode( array(
                'site_url'   => SCHOLAR_SYNC_SITE_URL,
                'rest'       => rest_url( 'sclr/v1/' ),
                'rest_nonce' => wp_create_nonce( 'wp_rest' ),
                'plugin_url' => SCHOLAR_SYNC_PLUGIN_URL,
            ) );
            wp_enqueue_script( 'jquery' );
            wp_enqueue_script( 'scholar-sync-pagination',    SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-pagination.js',    array( 'jquery' ), SCHOLAR_SYNC_VERSION, true );
            wp_enqueue_script( 'scholar-sync-article-card',  SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-article-card.js',  array( 'jquery' ), SCHOLAR_SYNC_VERSION, true );
            wp_enqueue_script( 'scholar-sync-author-display', SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-author-display.js', array( 'jquery' ), SCHOLAR_SYNC_VERSION, true );
            wp_enqueue_script( 'scholar-sync-create-page',   SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-create-page.js',   array(), SCHOLAR_SYNC_VERSION, true );
            wp_add_inline_script( 'scholar-sync-author-display', 'window.scholar_sync_public_object = ' . $ajax_object . ';', 'before' );

            $out .= $this->getMenu();
        }

        // Container — carries data attributes JS reads for initial visibility.
        $out .= '<div class="scholar-sync-container"'
              . ' data-author-id="'          . esc_attr( (int) $this->author_id ) . '"'
              . ' data-display-header="'     . ( $this->display_header     ? '1' : '0' ) . '"'
              . ' data-display-search="'     . ( $this->display_search     ? '1' : '0' ) . '"'
              . ' data-display-cited-by="'   . ( $this->display_cited_by   ? '1' : '0' ) . '"'
              . ' data-display-co-authors="' . ( $this->display_co_authors ? '1' : '0' ) . '"'
              . ' data-image-shape="'        . esc_attr( $this->image_shape ) . '"'
              . ' data-image-shadow="'       . ( $this->image_shadow ? '1' : '0' ) . '"'
              . ' data-display-article-image="' . ( $this->display_article_image ? '1' : '0' ) . '"'
              . ' data-display-co-author-photos="' . ( $this->display_co_author_photos ? '1' : '0' ) . '"'
              . ( $this->sort_by !== '' ? ' data-sort-by="' . esc_attr( $this->sort_by ) . '"' : '' )
              . '>';

        // ── Profile header ──────────────────────────────────────────
        $out .= '<div class="scholar-sync-user-profile"' . ( $this->display_header ? '' : ' hidden' ) . '>';
        $out .= '<div class="scholar-sync-user-details">';
        $out .= '<h2 class="scholar-sync-user-name">'      . esc_html( $author_name )         . '</h2>';
        $out .= '<div class="scholar-sync-user-institute">' . esc_html( $author->affiliations ) . '</div>';
        $bio_summary = $this->getBioSummary( $author_name, $author->position, $author->affiliations, $author->interests );
        if ( $bio_summary !== '' ) {
            $out .= '<p class="scholar-sync-bio-summary">' . esc_html( $bio_summary ) . '</p>';
        }
        $out .= '<div class="scholar-sync-user-interests">' . $this->getInterestsLinks( $author->interests ) . '</div>';
        $out .= '</div>';
        $out .= '<div class="scholar-sync-after-gradiant">';
        $thumbnail = ! empty( $author->thumbnail ) ? (string) $author->thumbnail : SCHOLAR_SYNC_PLUGIN_URL . 'includes/images/scholar_avatar.png';
        $out .= '<img src="' . esc_url( $thumbnail ) . '" alt="' . esc_attr( $author_name ) . '">';
        $out .= '</div>';
        $out .= '</div>'; // .scholar-sync-user-profile

        // ── Search row ──────────────────────────────────────────────
        $out .= '<div class="scholar-sync-search-row"' . ( $this->display_search ? '' : ' hidden' ) . '>';
        $out .= '<div class="scholar-sync-search-container">';
        $out .= '<input type="text" id="scholar-sync-search" placeholder="' . esc_attr__( 'Search...', 'scholar-sync' ) . '">';
        $out .= '<button type="button" id="scholar-sync-clear-search"><svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M1 1L11 11M11 1L1 11" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button>';
        $out .= '</div>';
        $out .= '<button type="button" id="scholar-sync-search-btn">' . esc_html__( 'Search', 'scholar-sync' ) . '</button>';
        $out .= '</div>'; // .scholar-sync-search-row

        // ── Controls bar (per-page + results info) ───────────────────
        $out .= '<div class="scholar-sync-controls-bar"' . ( $this->display_search ? '' : ' hidden' ) . '>';
        $out .= '<span class="scholar-sync-results-info"></span>';
        $out .= '<div class="scholar-sync-perpage-container">';
        $out .= esc_html__( 'Per page:', 'scholar-sync' );
        $out .= '<select id="scholar-sync-per-page">';
        $out .= '<option value="20">20</option><option value="50">50</option><option value="100">100</option>';
        $out .= '</select>';
        $out .= '</div>';
        $out .= '</div>'; // .scholar-sync-controls-bar

        // ── Feed list — server-rendered first page so crawlers/AI agents that
        // don't execute JS still see real publications, not an empty container.
        // JS replaces this with the live AJAX result (search/sort/pagination) on load.
        $ssr_articles = $this->getArticlesForSsr();
        $out .= '<h3 class="scholar-sync-feed-heading">' . esc_html__( 'Publications', 'scholar-sync' ) . '</h3>';
        $out .= '<div class="wps-feed-list">';
        if ( ! empty( $ssr_articles ) ) {
            $out .= '<div class="scholar-sync-feed-container">';
            foreach ( $ssr_articles as $article ) {
                $out .= ScholarSync_SEO::render_article_card_ssr( $article );
            }
            $out .= '</div>';
        }
        $out .= '</div>';
        $out .= '<div class="wps-author-pagination"></div>';

        $out .= '</div>'; // .scholar-sync-container

        // ── Structured data ───────────────────────────────────────────
        $person_schema = array_merge(
            array( '@context' => 'https://schema.org' ),
            ScholarSync_SEO::person_schema( $author )
        );
        if ( ! empty( $ssr_articles ) ) {
            $article_items = array_map( array( 'ScholarSync_SEO', 'scholarly_article_schema' ), $ssr_articles );
            $person_schema['subjectOf'] = ScholarSync_SEO::item_list_document( $article_items, __( 'Publications', 'scholar-sync' ) );
        }
        ob_start();
        ScholarSync_SEO::render_json_ld( $person_schema );
        $out .= ob_get_clean();

        return $out;
    }

    /**
     * First page of this author's active articles, in the same default order
     * REST get_display() uses, for the server-rendered fallback + JSON-LD.
     */
    private function getArticlesForSsr( $limit = 20 ) {
        global $wpdb;
        $table = SCHOLAR_SYNC_DB_ARTICLES;
        // ORDER BY is a hardcoded literal in each branch (mirrors REST get_display()), never
        // built from a variable, so no value is ever interpolated into the SQL string.
        if ( 'year' === $this->sort_by ) {
            $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Read bypasses cache safely
                $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
                    'SELECT article_id, title, link, authors, publication, cited_by_value, year FROM %i WHERE author_id = %d AND is_active = 1 ORDER BY year DESC, cited_by_value DESC LIMIT %d',
                    $table,
                    $this->author_id,
                    $limit
                ),
                ARRAY_A
            );
        } else {
            $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Read bypasses cache safely
                $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
                    'SELECT article_id, title, link, authors, publication, cited_by_value, year FROM %i WHERE author_id = %d AND is_active = 1 ORDER BY cited_by_value DESC, year DESC LIMIT %d',
                    $table,
                    $this->author_id,
                    $limit
                ),
                ARRAY_A
            );
        }
        return is_array( $rows ) ? $rows : array();
    }

    /**
     * One-sentence, LLM-quotable identity summary: "{name} is {position} at
     * {affiliations}. Research interests: {a, b, c}." Only the clauses with
     * data are included.
     */
    private function getBioSummary( $name, $position, $affiliations, $interests ) {
        $parts    = array();
        $position = trim( (string) $position );
        $affil    = trim( (string) $affiliations );

        if ( $position !== '' && $affil !== '' ) {
            $parts[] = trim( (string) $name ) . ' is ' . $position . ' at ' . $affil . '.';
        } elseif ( $position !== '' ) {
            $parts[] = trim( (string) $name ) . ' is ' . $position . '.';
        } elseif ( $affil !== '' ) {
            $parts[] = trim( (string) $name ) . ' is affiliated with ' . $affil . '.';
        }

        $topics = array_filter( array_map( 'trim', explode( ',', (string) $interests ) ) );
        if ( $topics ) {
            $parts[] = 'Research interests: ' . implode( ', ', $topics ) . '.';
        }

        return implode( ' ', $parts );
    }

    private function getMenu() {
        $author_id   = (int) $this->author_id;
        $back_url    = esc_url( admin_url( 'admin.php?page=scholar-sync-authors-slug&author-id=' . $author_id ) );
        $shortcode   = esc_attr( $this->getShortcode() );
        $ajax_url    = esc_js( admin_url( 'admin-ajax.php' ) );
        $nonce       = esc_js( wp_create_nonce( 'scholar_sync_create_page' ) );
        global $wpdb;
        $author_name = (string) $wpdb->get_var( $wpdb->prepare( 'SELECT name FROM %i WHERE author_id = %d', SCHOLAR_SYNC_DB_AUTHORS, $author_id ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- %i is the WordPress identifier placeholder (WP 6.2+)
        $author_name = esc_attr( $author_name );

        $existing_links     = ScholarSync_Admin::get_tracked_page_links( ScholarSync_Admin::author_page_option_name( $author_id ) );
        $existing_links_html = ScholarSync_Admin::render_tracked_page_links_html( $existing_links );
        $result_visible_class = $existing_links_html ? ' is-visible' : '';

        $checked_header     = $this->display_header     ? 'checked' : '';
        $checked_search     = $this->display_search     ? 'checked' : '';
        $checked_cited_by   = $this->display_cited_by   ? 'checked' : '';
        $checked_co_authors = $this->display_co_authors ? 'checked' : '';
        $checked_co_author_photos = $this->display_co_author_photos ? 'checked' : '';
        $checked_article_image = $this->display_article_image ? 'checked' : '';
        $sel_circle         = $this->image_shape === 'circle' ? 'selected' : '';
        $sel_square         = $this->image_shape === 'square' ? 'selected' : '';
        $checked_shadow     = $this->image_shadow ? 'checked' : '';

        $panel_html = '
        <!-- Toggle button (shown when panel is closed) -->
        <button id="wps-toggle" title="' . esc_attr__( 'Open display options', 'scholar-sync' ) . '">
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect y="3"  width="18" height="2" rx="1" fill="currentColor"/>
                <rect y="8"  width="18" height="2" rx="1" fill="currentColor"/>
                <rect y="13" width="18" height="2" rx="1" fill="currentColor"/>
            </svg>
            ' . esc_html__( 'Display Options', 'scholar-sync' ) . '
        </button>

        <!-- Sliding panel -->
        <div id="wps-panel">
            <div class="wps-panel-header">
                <a href="' . $back_url . '" class="wps-panel-back" title="' . esc_attr__( 'Back to authors', 'scholar-sync' ) . '">
                    <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M9 1.5L1.5 9L9 16.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M1.5 9H16.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                </a>
                <span class="wps-panel-title">' . esc_html__( 'Display Options', 'scholar-sync' ) . '</span>
                <button class="wps-panel-close" id="wps-panel-close" title="' . esc_attr__( 'Close panel', 'scholar-sync' ) . '">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                </button>
            </div>

            <div class="wps-panel-body">

                <label class="wps-checkbox-label">
                    <input type="checkbox" id="preview-show-header" ' . $checked_header . '>
                    ' . esc_html__( 'Show author header', 'scholar-sync' ) . '
                </label>

                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-search" ' . $checked_search . '>
                    ' . esc_html__( 'Show search bar', 'scholar-sync' ) . '
                </label>

                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-cited-by" ' . $checked_cited_by . '>
                    ' . esc_html__( 'Show cited-by count', 'scholar-sync' ) . '
                </label>

                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-co-authors" ' . $checked_co_authors . '>
                    ' . esc_html__( 'Show co-authors', 'scholar-sync' ) . '
                </label>

                <label class="wps-checkbox-label wps-checkbox-label-spaced">
                    <input type="checkbox" id="preview-show-co-author-photos" ' . $checked_co_author_photos . '>
                    ' . esc_html__( 'Show co-author photos', 'scholar-sync' ) . '
                </label>

                <label class="wps-checkbox-label wps-checkbox-label-spaced">
                    <input type="checkbox" id="preview-show-article-image" ' . $checked_article_image . '>
                    ' . esc_html__( 'Show article images', 'scholar-sync' ) . '
                </label>

                <label style="display:block;margin-top:16px;font-weight:600;color:#1d2327;font-size:13px;">' . esc_html__( 'Sort by', 'scholar-sync' ) . '</label>
                <select id="preview-sort-by" style="width:100%;margin-top:4px;">
                    <option value="cited_by">' . esc_html__( 'Cited by', 'scholar-sync' ) . '</option>
                    <option value="year">' . esc_html__( 'Year', 'scholar-sync' ) . '</option>
                </select>

                <a href="' . esc_url( admin_url( 'admin.php?page=scholar-sync-authors-slug&author-id=' . $author_id . '&tab=0&highlight=thumbnail' ) ) . '" style="display:block;margin-top:12px;font-size:13px;">' . esc_html__( 'Update image', 'scholar-sync' ) . '</a>

                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-image-shadow" ' . $checked_shadow . '>
                    ' . esc_html__( 'Show image shadow', 'scholar-sync' ) . '
                </label>

                <label style="display:block;margin-top:16px;font-weight:600;color:#1d2327;font-size:13px;">' . esc_html__( 'Image Shape', 'scholar-sync' ) . '</label>
                <select id="preview-image-shape" style="width:100%;margin-top:4px;">
                    <option value="circle" ' . $sel_circle . '>' . esc_html__( 'Circle', 'scholar-sync' ) . '</option>
                    <option value="square" ' . $sel_square . '>' . esc_html__( 'Square', 'scholar-sync' ) . '</option>
                </select>

                <div class="wps-shortcode-box">
                    <label>' . esc_html__( 'Shortcode', 'scholar-sync' ) . '</label>
                    <input type="text" id="author-shortcode-display" readonly value="' . $shortcode . '">
                    <button type="button" id="copy-author-shortcode" class="wps-copy-btn">
                        ' . esc_html__( 'Copy Shortcode', 'scholar-sync' ) . '
                    </button>
                </div>

                <div class="wps-create-page-box">
                    <label>' . esc_html__( 'Create a page', 'scholar-sync' ) . '</label>
                    <input type="text" id="wps-page-title" placeholder="' . esc_attr__( 'Page title', 'scholar-sync' ) . '" value="' . $author_name . '">
                    <button type="button" id="wps-create-page-btn" class="wps-copy-btn" style="background:#1a1f36;">
                        + ' . esc_html__( 'Create Page', 'scholar-sync' ) . '
                    </button>
                    <div id="wps-create-page-result" class="wps-create-page-result' . $result_visible_class . '">' . $existing_links_html . '</div>
                </div>

            </div><!-- /.wps-panel-body -->
        </div><!-- /#wps-panel -->
        ';
        $panel_data = 'var scholarSyncAjaxUrl = ' . wp_json_encode( $ajax_url ) . ';'
            . 'var scholarSyncCreatePageNonce = ' . wp_json_encode( $nonce ) . ';'
            . 'var scholarSyncAuthorId = ' . (int) $author_id . ';';
        wp_add_inline_script( 'scholar-sync-create-page', $panel_data, 'before' );
        return $panel_html;
    }


    private function getShortcode() {
        $header      = $this->display_header     ? '' : ' header="0"';
        $search      = $this->display_search     ? '' : ' search="0"';
        $cited_by    = $this->display_cited_by   ? '' : ' cited-by="0"';
        $co_authors  = $this->display_co_authors ? '' : ' co-authors="0"';
        $image_shape  = $this->image_shape !== 'circle' ? ' image_shape="' . esc_attr( $this->image_shape ) . '"' : '';
        $image_shadow = ! $this->image_shadow ? ' shadow="0"' : '';
        $article_image = $this->display_article_image ? '' : ' article-image="0"';
        $co_author_photos = $this->display_co_author_photos ? '' : ' co-author-photos="0"';

        return '[scholar-sync-scholar id="' . (int) $this->author_id . '"' . $header . $search . $cited_by . $co_authors . $co_author_photos . $image_shape . $image_shadow . $article_image . ']';
    }
}
