<?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 individually at point of use below

global $wpdb;

$group_id   = isset( $_POST['group_id'] ) ? (int) $_POST['group_id'] : 0;
$group_name = isset( $_POST['group_name'] ) ? sanitize_text_field( wp_unslash( $_POST['group_name'] ) ) : '';
$view_type  = ( isset( $_POST['view_type'] ) && $_POST['view_type'] === 'feed' ) ? 'feed' : 'grid';

// Build settings JSON from posted display attributes.
$settings = array(
    'columns'            => isset( $_POST['columns'] )     ? (int) $_POST['columns']                                       : 3,
    'image_shape'        => isset( $_POST['image_shape'] ) ? sanitize_text_field( wp_unslash( $_POST['image_shape'] ) )    : 'circle',
    'per_page'           => isset( $_POST['per_page'] )    ? max( 4, min( 48, (int) $_POST['per_page'] ) )                 : 12,
    'show_position'      => ! empty( $_POST['show_position'] ),
    'show_institution'   => ! empty( $_POST['show_institution'] ),
    'show_tags'          => ! empty( $_POST['show_tags'] ),
    'max_tags'           => isset( $_POST['max_tags'] )    ? max( 1, min( 10, (int) $_POST['max_tags'] ) )                 : 3,
    'show_publications'  => ! empty( $_POST['show_publications'] ),
    'show_profile_link'  => ! empty( $_POST['show_profile_link'] ),
    'show_article_image' => ! empty( $_POST['show_article_image'] ),
);

$group_table  = SCHOLAR_SYNC_DB_GROUPS;
$member_table = SCHOLAR_SYNC_DB_GROUP_AUTHORS;

if ( empty( $group_name ) ) {
    wp_safe_redirect( admin_url( 'admin.php?page=scholar-sync-groups-slug&error=empty_name' ) );
    exit;
}

if ( $group_id > 0 ) {
    $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Update bypasses cache safely
        $group_table,
        array(
            'name'      => $group_name,
            'view_type' => $view_type,
            'settings'  => wp_json_encode( $settings ),
        ),
        array( 'group_id' => $group_id )
    );
} else {
    $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Insert bypasses cache safely
        $group_table,
        array(
            'name'      => $group_name,
            'view_type' => $view_type,
            'settings'  => wp_json_encode( $settings ),
        )
    );
    $group_id = $wpdb->insert_id;
}

// Replace all members for this group.
$wpdb->delete( $member_table, array( 'group_id' => $group_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Delete bypasses cache safely

$raw_ids    = isset( $_POST['group_author_ids'] ) ? sanitize_text_field( wp_unslash( $_POST['group_author_ids'] ) ) : '';
$author_ids = array_filter( array_map( 'intval', explode( ',', $raw_ids ) ) );

$member_links_raw = isset( $_POST['member_links'] ) && is_array( $_POST['member_links'] )
    ? array_map( function( $url ) { return esc_url_raw( wp_unslash( trim( $url ) ) ); }, $_POST['member_links'] )
    : array();

if ( ! empty( $author_ids ) ) {
    $placeholders = array();
    $values       = array();
    $table_authors = SCHOLAR_SYNC_DB_AUTHORS;
    foreach ( array_values( $author_ids ) as $order => $author_id ) {
        $link_url = isset( $member_links_raw[ $author_id ] )
            ? esc_url_raw( trim( $member_links_raw[ $author_id ] ) ) : '';

        $placeholders[] = '(%d, %d, %d, %s)';
        $values[]       = $group_id;
        $values[]       = $author_id;
        $values[]       = $order;
        $values[]       = $link_url;

        // Backfill directory_link on the author if it is currently empty.
        if ( ! empty( $link_url ) ) {
            $existing = $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- %i is the WordPress identifier placeholder (WP 6.2+)
                'SELECT directory_link FROM %i WHERE author_id = %d',
                $table_authors,
                $author_id
            ) );
            if ( empty( $existing ) ) {
                $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Update bypasses cache safely
                    SCHOLAR_SYNC_DB_AUTHORS,
                    array( 'directory_link' => $link_url ),
                    array( 'author_id'      => $author_id )
                );
            }
        }
    }
    $sql = 'INSERT INTO %i (group_id, author_id, sort_order, link_url) VALUES '
        . implode( ', ', $placeholders );
    $wpdb->query( $wpdb->prepare( $sql, array_merge( array( $member_table ), $values ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i for table; $placeholders are %d/%s only
}

wp_safe_redirect( add_query_arg( '_wpnonce', wp_create_nonce( 'scholar_sync_notice' ), admin_url( 'admin.php?page=scholar-sync-groups-slug&group-id=' . $group_id . '&msg=saved' ) ) );
exit;
