<?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

if ( ! current_user_can( 'edit_others_posts' ) ) {
    wp_die( esc_html__( 'You do not have permission to perform this action.', 'scholar-sync' ) );
}

global $wpdb;
$table = SCHOLAR_SYNC_DB_CO_AUTHORS;

$co_author_id = isset( $_POST['co_author_id'] ) ? (int) $_POST['co_author_id'] : 0;
$full_name    = sanitize_text_field( wp_unslash( $_POST['full_name'] ?? '' ) );
$short_name   = sanitize_text_field( wp_unslash( $_POST['short_name'] ?? '' ) );
$image_url    = esc_url_raw( wp_unslash( $_POST['image_url'] ?? '' ) ) ?: null;
$profile_link = esc_url_raw( wp_unslash( $_POST['profile_link'] ?? '' ) ) ?: null;
$affiliations = sanitize_text_field( wp_unslash( $_POST['affiliations'] ?? '' ) ) ?: null;

if ( empty( $full_name ) || empty( $short_name ) ) {
    wp_safe_redirect( admin_url( 'admin.php?page=scholar-sync-co-authors-slug' ) );
    exit;
}

if ( $co_author_id > 0 ) {
    // UPDATE
    $result = $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Update bypasses cache and uses direct DB call safely
        $table,
        array(
            'full_name'    => $full_name,
            'short_name'   => $short_name,
            'image_url'    => $image_url,
            'profile_link' => $profile_link,
            'affiliations' => $affiliations,
        ),
        array( 'co_author_id' => $co_author_id )
    );
    if ( $result === false && $wpdb->last_error !== '' ) {
        // Likely a short_name uniqueness violation.
        $redirect = add_query_arg( array(
            'page'         => 'scholar-sync-co-authors-slug',
            'action'       => 'edit',
            'co-author-id' => $co_author_id,
            'save_error'   => 'duplicate_short_name',
        ), admin_url( 'admin.php' ) );
        wp_safe_redirect( $redirect );
        exit;
    }
} else {
    // INSERT
    $result = $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Insert bypasses cache and uses direct DB call safely
        $table,
        array(
            'full_name'    => $full_name,
            'short_name'   => $short_name,
            'image_url'    => $image_url,
            'profile_link' => $profile_link,
            'affiliations' => $affiliations,
        )
    );
    if ( $result === false ) {
        // Likely a short_name uniqueness violation.
        $redirect = add_query_arg( array(
            'page'       => 'scholar-sync-co-authors-slug',
            'action'     => 'create',
            'save_error' => 'duplicate_short_name',
        ), admin_url( 'admin.php' ) );
        wp_safe_redirect( $redirect );
        exit;
    }
}

wp_safe_redirect( add_query_arg( '_wpnonce', wp_create_nonce( 'scholar_sync_notice' ), admin_url( 'admin.php?page=scholar-sync-co-authors-slug&msg=saved' ) ) );
exit;
