<?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 cast to int or sanitized at point of use

    global $wpdb;

    // Captured before the bulk branch below wipes $_GET, so the search the user was
    // looking at survives the redirect back to the Articles tab.
    $search_term = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';

    $arr = array();
    if (isset($_GET['article-id'])) {
        array_push($arr, absint( wp_unslash( $_GET['article-id'] ) ) );
    } else if (isset($_GET['post'])) {
        $arr = $_GET['post'];
        $author_id = $_GET['author-id'];
        foreach ($_GET as $key => $value) {
            unset($_GET[$key]);
        }
        $_GET['author-id'] = $author_id;
    }

    if (count($arr) > 0) {
        $safe_ids = array_filter(array_map('intval', $arr));
        if (!empty($safe_ids)) {
            $placeholders = implode(', ', array_fill(0, count($safe_ids), '%d'));
            $table_name = SCHOLAR_SYNC_DB_ARTICLES;
            $result = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Update bypasses cache safely
                $wpdb->prepare("UPDATE %i SET is_active=0 WHERE article_id IN ({$placeholders})", $table_name, ...$safe_ids) // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- dynamic IN(): array_fill()-generated %d placeholders only; IDs int-cast and passed to prepare()
            );
        } else {
            $result = 0;
        }
        if ($result > 0) {
            $_GET['msg'] = 'delete-article';
            $_GET['msg-count'] = $result;

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