<?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
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- inputs sanitized with absint/sanitize_*

    global $wpdb;
    $table_name = SCHOLAR_SYNC_DB_AUTHORS;


    /**
     * Form Data Validation - start
     */
    $valid_input = true;
    if (Empty(scholar_sync_get_param('name'))) {
        $valid_input = false;
    }

    /**
     * Form Data Validation - end
     */

    if ( ! $valid_input ) {
        wp_safe_redirect( add_query_arg(
            array(
                'page'       => 'scholar-sync-authors-slug',
                'author-id'  => absint( scholar_sync_get_param( 'author-id' ) ),
                'tab'        => absint( scholar_sync_get_param( 'tab' ) ),
                'save_error' => 'missing_name',
            ),
            admin_url( 'admin.php' )
        ) );
        exit();
    }

    if ($valid_input) {

        $author_id = absint( scholar_sync_get_param('author-id') );

        $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') ),
        );

        // A manual edit to one of the 4 sync-protected fields locks just that field from
        // being overwritten by a future sync (admin/class-scholar-sync-author-sync.php's
        // update_author_stats()) until the flag is re-enabled — a field left unchanged here
        // keeps its current flag untouched, no auto re-enabling. Checking the field's
        // "Re-enable sync" box (admin/author_edit_details_tab.php) always wins over the diff
        // check, even if the submitted value still differs from what's stored.
        $current = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->prepare( 'SELECT interests, citations_all, h_index_all, i10_index_all, interests_sync, citations_all_sync, h_index_all_sync, i10_index_all_sync FROM %i WHERE author_id = %d', $table_name, $author_id ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
            ARRAY_A
        );

        $locked_labels = array();

        if ( $current ) {
            $protected_fields = array(
                'interests'     => array( 'flag' => 'interests_sync', 'label' => 'Interests' ),
                'citations_all' => array( 'flag' => 'citations_all_sync', 'label' => 'Citations Total' ),
                'h_index_all'   => array( 'flag' => 'h_index_all_sync', 'label' => 'h-index' ),
                'i10_index_all' => array( 'flag' => 'i10_index_all_sync', 'label' => 'i10-index' ),
            );

            // Field names the admin checked "Re-enable sync" for, restricted to the known set —
            // never trust this list to build a column name directly.
            $reenable_raw = isset( $_GET['reenable_sync'] ) && is_array( $_GET['reenable_sync'] )
                ? array_map( 'sanitize_key', wp_unslash( $_GET['reenable_sync'] ) )
                : array();
            $reenable = array_intersect( $reenable_raw, array_keys( $protected_fields ) );

            foreach ( $protected_fields as $field => $meta ) {
                if ( in_array( $field, $reenable, true ) ) {
                    $values_array[ $meta['flag'] ] = 1;
                } elseif ( (string) $values_array[ $field ] !== (string) $current[ $field ] ) {
                    $values_array[ $meta['flag'] ] = 0;
                    if ( (int) $current[ $meta['flag'] ] === 1 ) {
                        $locked_labels[] = $meta['label'];
                    }
                }
            }
        }

        $result = $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Update bypasses cache safely
            $table_name,
            $values_array,
            array( 'author_id' => $author_id ) );

        if ( $result === false && $wpdb->last_error !== '' ) {
            wp_safe_redirect( add_query_arg(
                array(
                    'page'       => 'scholar-sync-authors-slug',
                    'author-id'  => $author_id,
                    'tab'        => absint( scholar_sync_get_param( 'tab' ) ),
                    'save_error' => 'save_failed',
                ),
                admin_url( 'admin.php' )
            ) );
            exit();
        }

        $msg = 'update-article';

        // clean the url
        unset($_GET['position']);
        unset($_GET['affiliations']);
        unset($_GET['interests']);
        unset($_GET['thumbnail']);
        unset($_GET['cite']);
        unset($_GET['h_index']);
        unset($_GET['i10_index']);
        unset($_GET['reenable_sync']);

        $_GET['msg'] = 'update-author';
        $_GET['action'] = '';
        if ( ! empty( $locked_labels ) ) {
            $_GET['msg-fields'] = implode( ', ', $locked_labels );
        }

    }

    $url = add_query_arg(
        array(
            'page'       => 'scholar-sync-authors-slug',
            'author-id'  => absint( scholar_sync_get_param( 'author-id' ) ),
            'tab'        => absint( scholar_sync_get_param( 'tab' ) ),
            'msg'        => sanitize_key( isset( $_GET['msg'] ) ? wp_unslash( $_GET['msg'] ) : '' ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
            'msg-fields' => sanitize_text_field( isset( $_GET['msg-fields'] ) ? wp_unslash( $_GET['msg-fields'] ) : '' ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
            'action'     => '',
            '_wpnonce'   => wp_create_nonce( 'scholar_sync_notice' ),
        ),
        admin_url( 'admin.php' )
    );

wp_safe_redirect($url);
exit();
