<?php
if ( ! defined( 'ABSPATH' ) ) exit;

function scholar_sync_delete_groups( $group_ids ) {
    global $wpdb;

    if ( ! is_array( $group_ids ) ) {
        $group_ids = array( $group_ids );
    }
    $group_ids = array_filter( array_map( 'intval', $group_ids ) );
    if ( empty( $group_ids ) ) {
        return 0;
    }

    $placeholders = implode( ', ', array_fill( 0, count( $group_ids ), '%d' ) );

    // Remove members first to maintain referential integrity.
    $table_group_authors = SCHOLAR_SYNC_DB_GROUP_AUTHORS;
    $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Deletion bypasses cache safely
        $wpdb->prepare(
            "DELETE FROM %i WHERE group_id IN ($placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- dynamic IN(): array_fill()-generated %d placeholders only; IDs int-cast and passed to prepare()
            array_merge( array( $table_group_authors ), $group_ids )
        )
    );

    $table_groups = SCHOLAR_SYNC_DB_GROUPS;
    $deleted = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Deletion bypasses cache safely
        $wpdb->prepare(
            "DELETE FROM %i WHERE group_id IN ($placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- dynamic IN(): array_fill()-generated %d placeholders only; IDs int-cast and passed to prepare()
            array_merge( array( $table_groups ), $group_ids )
        )
    );

    return (int) $deleted;
}
