<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- AJAX handler; all variables are local to this file
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- inputs sanitized via sanitize_text_field/wp_unslash/intval at point of use

check_ajax_referer( 'scholar_sync_create_page', 'nonce' );

if ( ! current_user_can( 'edit_others_posts' ) ) {
    wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'scholar-sync' ) ) );
}

$page_title     = isset( $_POST['page_title'] ) ? sanitize_text_field( wp_unslash( $_POST['page_title'] ) ) : '';
$shortcode      = isset( $_POST['shortcode'] )  ? sanitize_text_field( wp_unslash( $_POST['shortcode'] ) )  : '';
$group_id_post  = isset( $_POST['group_id'] )   ? absint( wp_unslash( $_POST['group_id'] ) )                : 0;
$view_type_post = isset( $_POST['view_type'] )  ? sanitize_key( wp_unslash( $_POST['view_type'] ) )         : '';

if ( empty( $page_title ) ) {
    wp_send_json_error( array( 'message' => __( 'Page title is required.', 'scholar-sync' ) ) );
}

// Fallback: rebuild shortcode from group_id when the JS-transmitted string is empty.
if ( empty( $shortcode ) && $group_id_post > 0 ) {
    if ( 'feed' === $view_type_post ) {
        $shortcode = '[scholar-sync-group id="' . $group_id_post . '"]';
    } else {
        $opt_prefix = SCHOLAR_SYNC_OPTION_PREFIX . 'group-display-' . $group_id_post . '-';
        $cols        = (int) get_option( $opt_prefix . 'columns',     '2' );
        $shape       = sanitize_key( get_option( $opt_prefix . 'image_shape', 'circle' ) );
        $show_text   = ( get_option( $opt_prefix . 'show_text', '1' ) !== '0' );
        $show_shadow = ( get_option( $opt_prefix . 'shadow',    '1' ) !== '0' );

        $shortcode = '[scholar-sync-group id="' . $group_id_post . '"';
        if ( 2 !== $cols )      { $shortcode .= ' columns="' . $cols . '"'; }
        if ( 'circle' !== $shape ) { $shortcode .= ' image_shape="' . esc_attr( $shape ) . '"'; }
        if ( ! $show_text )     { $shortcode .= ' show_text="0"'; }
        if ( ! $show_shadow )   { $shortcode .= ' shadow="0"'; }
        $shortcode .= ']';
    }
}

$block_content = "<!-- wp:shortcode -->\n" . $shortcode . "\n<!-- /wp:shortcode -->";

$page_id = wp_insert_post( array(
    'post_title'   => $page_title,
    'post_content' => $block_content,
    'post_status'  => 'draft',
    'post_type'    => 'page',
) );

if ( is_wp_error( $page_id ) ) {
    wp_send_json_error( array( 'message' => $page_id->get_error_message() ) );
}

// Track the created page per entity so the preview can re-display its links on
// reload. update_option overwrites any previous value (latest page wins).
$author_id = isset( $_POST['author_id'] ) ? (int) wp_unslash( $_POST['author_id'] ) : 0;
if ( $author_id > 0 ) {
    update_option( ScholarSync_Admin::author_page_option_name( $author_id ), $page_id );
}
if ( $group_id_post > 0 ) {
    update_option( ScholarSync_Admin::group_page_option_name( $group_id_post ), $page_id );
}

// Auto-populate the author's directory_link if it is currently empty.
if ( $author_id > 0 ) {
    global $wpdb;
    $table_authors = SCHOLAR_SYNC_DB_AUTHORS;
    $current_link = $wpdb->get_var( // 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 directory_link FROM %i WHERE author_id = %d',
            $table_authors,
            $author_id
        )
    );
    if ( empty( $current_link ) ) {
        $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            SCHOLAR_SYNC_DB_AUTHORS,
            array( 'directory_link' => home_url( '?page_id=' . $page_id ) ),
            array( 'author_id' => $author_id )
        );
    }
}

wp_send_json_success( array(
    'page_id'     => $page_id,
    'preview_url' => get_preview_post_link( $page_id ),
    'edit_url'    => get_edit_post_link( $page_id, 'raw' ),
) );
