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

function scholar_sync_get_post( $key, $default = null ) {
    return isset( $_POST[ $key ] ) ? wp_unslash( $_POST[ $key ] ) : ( isset( $default ) ? $default : '' ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- callers verify nonces and apply sanitization
}

function scholar_sync_get_param( $key, $default = null ) {
    return isset( $_GET[ $key ] ) ? wp_unslash( $_GET[ $key ] ) : ( isset( $default ) ? $default : '' ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- callers verify nonces and apply sanitization
}

class scholar_sync_message {
    private $message;

    function __construct($msg_type) {

        global $wpdb;

//        $author_name = $author->name;
        switch ($msg_type) {
            case 'add-article':
            case 'update-article':
                $table_name = SCHOLAR_SYNC_DB_ARTICLES;
                $author_id  = isset( $_GET['author-id'] )  ? absint( wp_unslash( $_GET['author-id'] ) )  : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $article_id = isset( $_GET['article-id'] ) ? absint( wp_unslash( $_GET['article-id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $item = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->prepare('SELECT * FROM %i WHERE article_id = %d', $table_name, $article_id) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
                );
                $link = esc_url(
                    menu_page_url('scholar-sync-authors-slug', false)
                    . '&action=add-article&tab=2'
                    . '&author-id=' . $author_id
                    . '&article-id=' . $article_id
                    . '&title=' . rawurlencode($item->title)
                    . '&link=' . rawurlencode($item->link)
                    . '&authors=' . rawurlencode($item->authors)
                    . '&publication=' . rawurlencode($item->publication)
                    . '&cite=' . rawurlencode($item->cited_by_value)
                    . '&year=' . rawurlencode($item->year)
                );
                if ($msg_type == 'add-article') {
                    $this->message = 'New article created. <a href="' . $link . '">Edit article</a>';
                } else {
                    $this->message = 'Article updated. <a href="' . $link . '">Edit article</a>';
                    if ( ! empty( $_GET['msg-cite-locked'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                        $this->message .= ' Note: Citations will no longer sync automatically, to avoid losing your manual edit.';
                    }
                }
                break;
            case 'update-author':
                $author_id = isset( $_GET['author-id'] ) ? absint( wp_unslash( $_GET['author-id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $link = esc_url(menu_page_url('scholar-sync-authors-slug', false) . '&author-id=' . $author_id . '&tab=1');
                $this->message = 'Author updated. <a href="' . $link . '">Edit Author</a>';
                $locked_fields = isset( $_GET['msg-fields'] ) ? sanitize_text_field( wp_unslash( $_GET['msg-fields'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                if ( $locked_fields !== '' ) {
                    $this->message .= ' Note: ' . esc_html( $locked_fields ) . ' will no longer sync automatically, to avoid losing your manual edit.';
                }
                break;
            case 'delete-article':
                $delete_count = isset( $_GET['msg-count'] ) ? (int) wp_unslash( $_GET['msg-count'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                $this->message = 'Successfully deleted ' . $delete_count . ' Article(s)';
                break;
            case 'delete-author':
                $delete_count = isset( $_GET['msg-count'] ) ? (int) wp_unslash( $_GET['msg-count'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                $this->message = 'Successfully deleted ' . $delete_count . ' Author(s)';
                break;
            case 'update-directory-link':
                $this->message = 'Directory link updated';
                break;
            default:
        }


        add_action( 'admin_notices', array( $this, 'render' ) );
        $this->render();
    }

    function render() {

//        printf('<div id="message" style="margin: 10px 0px 20px" class="updated notice is-dismissible"><p>New user created %s. <a href="https://google.com">Edit user</a></p><button type="button" onclick="clickMessageDismiss(this);" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button></div>', 'aaaaaa');
        printf('<div id="message" style="margin: 10px 0px 20px" class="updated notice is-dismissible"><p>%s</p><button type="button" onclick="clickMessageDismiss(this);" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button></div>', wp_kses($this->message, array('a' => array('href' => array()))));

    }
}

/**
 * Generate the short name used for co-author matching.
 * Rule: uppercase first char of first word + " " + last word.
 * Examples: "Snait Tamir" → "S Tamir", "Faiga Magzal" → "F Magzal"
 *
 * @param string $full_name
 * @return string
 */
function scholar_sync_generate_short_name( string $full_name ): string {
    $full_name = trim( $full_name );
    if ( empty( $full_name ) ) { return ''; }
    $parts = preg_split( '/\s+/u', $full_name );

    // Strip honorific prefixes (Dr., Prof., ...), case-insensitively, repeatedly, as long as
    // a word remains. Kept in sync by hand with public/js/scholar-sync-article-card.js and
    // admin/js/scholar-sync-admin.js — update all three together.
    $prefixes = array( 'dr', 'prof', 'professor', 'mr', 'mrs', 'ms', 'mx', 'miss' );
    while ( count( $parts ) > 1 ) {
        $candidate = mb_strtolower( rtrim( $parts[0], '.' ), 'UTF-8' );
        if ( ! in_array( $candidate, $prefixes, true ) ) {
            break;
        }
        array_shift( $parts );
    }

    $first = mb_strtoupper( mb_substr( $parts[0], 0, 1, 'UTF-8' ), 'UTF-8' );
    $last  = end( $parts );
    return $first . ' ' . $last;
}