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

function lt_core_ajax_relation_search() {
    check_ajax_referer( 'lt_relation_search', 'nonce' );
    if ( ! lt_core_current_user_can( 'lt_access_firm_dashboard' ) ) { wp_send_json_error( array( 'message'=>__( 'Permission denied.', 'law-temple-core' ) ), 403 ); }
    $post_type = sanitize_key( $_GET['post_type'] ?? '' );
    $allowed = array_keys( lt_core_meta_schema() );
    if ( ! in_array( $post_type, $allowed, true ) ) { wp_send_json_error( array( 'message'=>__( 'Unsupported relationship type.', 'law-temple-core' ) ), 400 ); }
    $q = sanitize_text_field( wp_unslash( $_GET['q'] ?? '' ) );
    $exclude = absint( $_GET['exclude'] ?? 0 );
    $args = array( 'post_type'=>$post_type, 'post_status'=>array('publish','draft','private'), 'posts_per_page'=>20, 'orderby'=>'title', 'order'=>'ASC', 's'=>$q, 'fields'=>'ids', 'no_found_rows'=>true );
    if ( $exclude ) { $args['post__not_in'] = array( $exclude ); }
    $ids = get_posts( $args );
    $items = array_map( static function( $id ) { return array( 'id'=>absint($id), 'text'=>get_the_title($id), 'status'=>get_post_status($id) ); }, $ids );
    wp_send_json_success( array( 'items'=>$items ) );
}
add_action( 'wp_ajax_lt_relation_search', 'lt_core_ajax_relation_search' );
