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


/**
 * Form Data Validation - start
 */
$valid_input = true;

if (empty(scholar_sync_get_param('title'))) {
    $valid_input = false;
    $_GET['invalid_title'] = 'form-invalid';
}

if (!is_numeric(scholar_sync_get_param('cite'))) {
    $valid_input = false;
    $_GET['invalid_cite'] = 'form-invalid';
}

if (empty(scholar_sync_get_param('year')) || !is_numeric(scholar_sync_get_param('year'))) {
    $valid_input = false;
    $_GET['invalid_year'] = 'form-invalid';
}
/**
 * Form Data Validation - end
 */

if ($valid_input) {
    // Sanitize and validate inputs
    $values_array = array(
        'author_id' => absint(scholar_sync_get_param('author-id')), // Ensure author ID is an integer
        'title' => sanitize_text_field(scholar_sync_get_param('title')), // Sanitize title
        'link' => esc_url(scholar_sync_get_param('link')), // Ensure URL is valid and safe
        'authors' => sanitize_text_field(scholar_sync_get_param('authors')), // Sanitize authors
        'publication' => sanitize_text_field(scholar_sync_get_param('publication')), // Sanitize publication
        'cited_by_value' => absint(scholar_sync_get_param('cite')), // Ensure cited by value is an integer
        'year' => absint(scholar_sync_get_param('year')), // Ensure year is an integer
        'image_url' => esc_url_raw(scholar_sync_get_param('article-image'), array('http', 'https')), // Only http(s) URLs; anything else stores as empty
        'all_data' => '', // Empty string for additional data
        'is_custom' => 1
    );

    $message = '';
    $article_id = '';
    $cite_locked = false; // citation count newly locked from sync this save

    if (!empty(scholar_sync_get_param('article-id'))) {
        // Image-only edits to a synced article must not freeze it: sync never
        // writes image_url, so keeping is_custom = 0 lets title/link/authors keep
        // syncing while the image survives. Any other field change still marks the
        // article custom (otherwise sync would revert the manual edit). Citations have
        // their own independent cited_by_value_sync flag (below), so they don't
        // participate in this whole-article lock.
        $existing = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
                'SELECT title, link, authors, publication, cited_by_value, year, is_custom, cited_by_value_sync FROM %i WHERE article_id = %d',
                $table_name,
                absint($_GET['article-id']) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- checked via scholar_sync_get_param() above
            ),
            ARRAY_A
        );
        $submitted_cite = $values_array['cited_by_value'];

        if ( $existing && 0 === (int) $existing['is_custom']
            && $values_array['title'] === (string) $existing['title']
            && $values_array['link'] === (string) $existing['link']
            && $values_array['authors'] === (string) $existing['authors']
            && $values_array['publication'] === (string) $existing['publication']
            && $values_array['year'] === (int) $existing['year']
        ) {
            $values_array = array( 'image_url' => $values_array['image_url'] );
        }

        // Resolve cited_by_value_sync independently of the is_custom shortcut above — read
        // from the submitted value directly, since $values_array may have just been
        // collapsed to image_url only and no longer contain 'cited_by_value' at all.
        if ( $existing ) {
            $reenable = isset( $_GET['reenable_sync'] ) && is_array( $_GET['reenable_sync'] )
                ? array_map( 'sanitize_key', wp_unslash( $_GET['reenable_sync'] ) ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- sanitize_key() applied on the line above
            if ( in_array( 'cited_by_value', $reenable, true ) ) {
                $values_array['cited_by_value']      = $submitted_cite;
                $values_array['cited_by_value_sync'] = 1;
            } elseif ( $submitted_cite !== (int) $existing['cited_by_value'] ) {
                $values_array['cited_by_value']      = $submitted_cite;
                $values_array['cited_by_value_sync'] = 0;
                if ( 1 === (int) $existing['cited_by_value_sync'] ) {
                    $cite_locked = true;
                }
            }
        }

        // Update existing article
        $result = $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Update bypasses cache safely
            $table_name,
            $values_array,
            array('article_id' => absint($_GET['article-id'])) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- checked via scholar_sync_get_param() above
        );

        $message = 'update-article';
        $article_id = absint($_GET['article-id']); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- checked via scholar_sync_get_param() above
    } else {
        // Insert new article
        $result = $wpdb->insert($table_name, $values_array); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Insert bypasses cache safely
        $article_id = $wpdb->insert_id; // Retrieve the inserted article ID

        $message = 'add-article';
    }


    // Update GET parameters with sanitized data
    $_GET['article-id'] = $article_id;
    $_GET['msg'] = sanitize_text_field($message);
    $_GET['msg-cite-locked'] = $cite_locked ? '1' : '';
    $_GET['action'] = '';

}

// Redirect to the appropriate page with only the known, safe parameters.
$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
        'article-id'      => absint( $article_id ),
        'action'          => '',
        'msg-cite-locked' => ! empty( $_GET['msg-cite-locked'] ) ? '1' : '', // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- boolean flag, coerced to '1' or ''
        '_wpnonce'        => wp_create_nonce( 'scholar_sync_notice' ),
    ),
    admin_url( 'admin.php' )
);

wp_safe_redirect($url);
exit();
