<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- included by main.php after nonce verification; local variables only
// phpcs:disable WordPress.Security.NonceVerification -- nonce verified in main.php before this file is included

    global $wpdb;
    $table_name = SCHOLAR_SYNC_DB_AUTHORS;

    // Re-echoes the submitted fields back onto the "Add Manually" form (which already
    // prefills from these same $_GET keys) so a rejected submission doesn't lose the
    // user's input.
    $preserved_args = array(
        'page'           => 'scholar-sync-add-author-slug',
        'manual'         => '',
        'name'           => scholar_sync_get_param( 'name' ),
        'position'       => scholar_sync_get_param( 'position' ),
        'affiliations'   => scholar_sync_get_param( 'affiliations' ),
        'interests'      => scholar_sync_get_param( 'interests' ),
        'thumbnail'      => scholar_sync_get_param( 'thumbnail' ),
        'cite'           => scholar_sync_get_param( 'cite' ),
        'h_index'        => scholar_sync_get_param( 'h_index' ),
        'i10_index'      => scholar_sync_get_param( 'i10_index' ),
        'directory_link' => scholar_sync_get_param( 'directory_link' ),
    );

    if ( empty( scholar_sync_get_param( 'name' ) ) ) {
        wp_safe_redirect( add_query_arg(
            array_merge( $preserved_args, array( 'save_error' => 'missing_name' ) ),
            admin_url( 'admin.php' )
        ) );
        exit();
    }

    $values_array = array(
        'name'          => sanitize_text_field( scholar_sync_get_param('name') ),
        'position'      => sanitize_text_field( scholar_sync_get_param('position') ),
        'affiliations'  => sanitize_text_field( scholar_sync_get_param('affiliations') ),
        'interests'     => sanitize_text_field( scholar_sync_get_param('interests') ),
        'thumbnail'     => esc_url_raw( scholar_sync_get_param('thumbnail') ),
        'citations_all' => absint( scholar_sync_get_param('cite') ),
        'h_index_all'   => absint( scholar_sync_get_param('h_index') ),
        'i10_index_all' => absint( scholar_sync_get_param('i10_index') ),
        'directory_link' => esc_url_raw( scholar_sync_get_param('directory_link') ),
    );

    $result = $wpdb->insert($table_name, $values_array); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Insert bypasses cache safely

    if ( $result === false ) {
        wp_safe_redirect( add_query_arg(
            array_merge( $preserved_args, array( 'save_error' => 'save_failed' ) ),
            admin_url( 'admin.php' )
        ) );
        exit();
    }

    $url = add_query_arg(
        array(
            'page'      => 'scholar-sync-authors-slug',
            'author-id' => absint( $wpdb->insert_id ),
        ),
        admin_url( 'admin.php' )
    );
    wp_safe_redirect($url);
    exit();
