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

/**
 * Reverse relationship query. v3.0.0 prefers the indexed relationship table and
 * automatically falls back to legacy CSV post meta when the index is absent.
 */
function lt_core_relationship_query( $post_type, $meta_key, $source_id, $limit = 12 ) {
    $source_id = absint( $source_id );
    $args = array(
        'post_type'=>$post_type,
        'post_status'=>'publish',
        'posts_per_page'=>$limit,
        'orderby'=>'menu_order title',
        'order'=>'ASC',
    );
    if ( function_exists( 'lt_core_relationship_source_ids' ) && lt_core_relationship_table_exists() ) {
        $ids = lt_core_relationship_source_ids( $post_type, $meta_key, $source_id, $limit > 0 ? $limit : 0 );
        if ( ! $ids ) { $args['post__in']=array(0); }
        else { $args['post__in']=$ids; $args['orderby']='post__in'; }
    } else {
        $args['meta_query']=array(array('key'=>$meta_key,'value'=>'(^|,)' . $source_id . '(,|$)','compare'=>'REGEXP'));
    }
    return new WP_Query( apply_filters( 'lt_core_relationship_query_args', $args, $post_type, $meta_key, $source_id ) );
}

function lt_core_related_practices_for_lawyer( $lawyer_id ) { return lt_core_get_related_posts( $lawyer_id, 'lt_practice_ids', 'practice' ); }
function lt_core_related_lawyers_for_practice( $practice_id ) {
    $explicit = lt_core_get_related_posts( $practice_id, 'lt_lawyer_ids', 'lawyer' );
    if ( $explicit ) { return $explicit; }
    $q = lt_core_relationship_query( 'lawyer', 'lt_practice_ids', $practice_id, -1 );
    return $q->posts;
}
