<?php
require_once 'meta.php';
require_once 'builder-template-helper.php';
require_once 'builder-cpt.php';
require_once 'builder-integration.php';
require_once 'themes-hooks/themes/astra.php';
require_once 'themes-hooks/themes/bbtheme.php';
require_once 'themes-hooks/themes/generatepress.php';
require_once 'themes-hooks/themes/genesis.php';
require_once 'themes-hooks/themes/neve.php';
require_once 'themes-hooks/themes/oceanwp.php';
require_once 'themes-hooks/theme-support.php';
require_once 'themes-hooks/activator.php';
require_once 'template-conditions.php';
require_once 'builder-preview-manager.php';
require_once 'admin/class-theme-builder-admin.php';

function bdt_templates_render_elementor_content( $content_id ) {

	$elementor_instance = \Elementor\Plugin::instance();

	return $elementor_instance->frontend->get_builder_content_for_display( $content_id, true );
}

/**
 * REST: Select2 search + preload for Theme Builder / modal “selective singular” lists.
 *
 * @param \WP_REST_Request $request Request.
 * @return \WP_REST_Response
 */
function bdt_templates_get_singular_list( \WP_REST_Request $request ) {
	$pt = $request->get_param( 'post_type' );
	$pt = is_string( $pt ) ? sanitize_key( $pt ) : '';

	$query_args = array(
		'post_status'    => 'publish',
		'posts_per_page' => 15,
		'post_type'      => ( $pt && post_type_exists( $pt ) ) ? $pt : 'any',
	);

	$ids_param = $request->get_param( 'ids' );
	if ( $ids_param ) {
		$ids_raw = is_array( $ids_param ) ? $ids_param : explode( ',', (string) $ids_param );
		$ids     = array_map( 'absint', $ids_raw );
		$ids     = array_values( array_filter( $ids ) );
		if ( $ids ) {
			$query_args['post__in'] = $ids;
			$query_args['orderby']  = 'post__in';
		}
	}

	$search = $request->get_param( 's' );
	if ( $search ) {
		$query_args['s']         = sanitize_text_field( $search );
		$query_args['orderby']   = 'relevance';
	} elseif ( empty( $query_args['post__in'] ) ) {
		$query_args['orderby'] = 'modified';
		$query_args['order']   = 'DESC';
	}

	$query   = new \WP_Query( $query_args );
	$options = array();
	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();
			$title = get_the_title();
			if ( '' === $title ) {
				/* translators: %d: post ID */
				$title = sprintf( __( 'Post #%d', 'bdthemes-element-pack' ), (int) get_the_ID() );
			}
			$options[] = array(
				'id'   => get_the_ID(),
				'text' => $title,
			);
		}
	}

	wp_reset_postdata();

	return rest_ensure_response( array( 'results' => $options ) );
}

/**
 * REST: taxonomy term search for Theme Builder conditions.
 *
 * @param \WP_REST_Request $request Request.
 * @return \WP_REST_Response
 */
function bdt_templates_get_term_list( \WP_REST_Request $request ) {
	$taxonomy = sanitize_key( (string) $request->get_param( 'taxonomy' ) );
	if ( ! $taxonomy || ! taxonomy_exists( $taxonomy ) ) {
		return rest_ensure_response( array( 'results' => array() ) );
	}

	$options = array();

	$ids_param = $request->get_param( 'ids' );
	if ( $ids_param ) {
		$ids_raw = is_array( $ids_param ) ? $ids_param : explode( ',', (string) $ids_param );
		$ids     = array_map( 'absint', $ids_raw );
		$ids     = array_values( array_filter( $ids ) );
		foreach ( $ids as $tid ) {
			$t = get_term( $tid, $taxonomy );
			if ( $t && ! is_wp_error( $t ) ) {
				$options[] = array(
					'id'   => (int) $t->term_id,
					'text' => $t->name,
				);
			}
		}
		return rest_ensure_response( array( 'results' => $options ) );
	}

	$search = sanitize_text_field( (string) $request->get_param( 's' ) );
	$args   = array(
		'taxonomy'   => $taxonomy,
		'hide_empty' => false,
		'number'     => 20,
	);
	if ( $search !== '' ) {
		$args['search'] = $search;
	}

	$terms = get_terms( $args );
	if ( is_wp_error( $terms ) || ! is_array( $terms ) ) {
		return rest_ensure_response( array( 'results' => array() ) );
	}

	foreach ( $terms as $t ) {
		if ( ! $t instanceof \WP_Term ) {
			continue;
		}
		$options[] = array(
			'id'   => (int) $t->term_id,
			'text' => $t->name,
		);
	}

	return rest_ensure_response( array( 'results' => $options ) );
}

/**
 * REST: user (author) search for Theme Builder conditions.
 *
 * @param \WP_REST_Request $request Request.
 * @return \WP_REST_Response
 */
function bdt_templates_get_user_list( \WP_REST_Request $request ) {
	$options = array();

	$ids_param = $request->get_param( 'ids' );
	if ( $ids_param ) {
		$ids_raw = is_array( $ids_param ) ? $ids_param : explode( ',', (string) $ids_param );
		$ids     = array_map( 'absint', $ids_raw );
		$ids     = array_values( array_filter( $ids ) );
		foreach ( $ids as $uid ) {
			$u = get_userdata( $uid );
			if ( $u ) {
				$options[] = array(
					'id'   => (int) $u->ID,
					'text' => $u->display_name,
				);
			}
		}
		return rest_ensure_response( array( 'results' => $options ) );
	}

	$search = sanitize_text_field( (string) $request->get_param( 's' ) );
	$uq     = array(
		'number'  => 20,
		'orderby' => 'display_name',
		'order'   => 'ASC',
	);
	if ( $search !== '' ) {
		$uq['search']         = '*' . $search . '*';
		$uq['search_columns'] = array( 'user_login', 'user_nicename', 'display_name' );
	}
	$query = new \WP_User_Query( $uq );

	foreach ( $query->get_results() as $u ) {
		if ( ! $u instanceof \WP_User ) {
			continue;
		}
		$options[] = array(
			'id'   => (int) $u->ID,
			'text' => $u->display_name ? $u->display_name : $u->user_login,
		);
	}

	return rest_ensure_response( array( 'results' => $options ) );
}

add_action( 'rest_api_init', function () {
	register_rest_route(
		'bdt/v1',
		'/get-singular-list',
		array(
			'methods'             => 'GET',
			'callback'            => 'bdt_templates_get_singular_list',
			'permission_callback' => function () {
				return current_user_can( 'edit_posts' );
			},
		)
	);
	register_rest_route(
		'bdt/v1',
		'/get-term-list',
		array(
			'methods'             => 'GET',
			'callback'            => 'bdt_templates_get_term_list',
			'permission_callback' => function () {
				return current_user_can( 'edit_posts' );
			},
		)
	);
	register_rest_route(
		'bdt/v1',
		'/get-user-list',
		array(
			'methods'             => 'GET',
			'callback'            => 'bdt_templates_get_user_list',
			'permission_callback' => function () {
				return current_user_can( 'edit_posts' );
			},
		)
	);
} );

/**
 * Theme Builder card iframe: trim admin bar / top margin when embedding a template preview (same origin).
 */
add_action(
	'init',
	static function () {
		if ( is_admin() ) {
			return;
		}
		if ( empty( $_GET['bdt_tb_card_embed'] ) || '1' !== (string) $_GET['bdt_tb_card_embed'] ) {
			return;
		}
		$preview_id = isset( $_GET['elementor-preview'] ) ? absint( $_GET['elementor-preview'] ) : 0;
		if ( ! $preview_id && isset( $_GET['p'] ) ) {
			$preview_id = absint( $_GET['p'] );
		}
		if ( ! $preview_id || ! current_user_can( 'edit_post', $preview_id ) ) {
			return;
		}
		if ( \ElementPack\Includes\Builder\Meta::POST_TYPE !== get_post_type( $preview_id ) ) {
			return;
		}

		// Force a deterministic template-only render for card iframes so each card previews
		// its own template (instead of inheriting active header/footer context output).
		add_filter(
			'template_include',
			static function ( $template ) use ( $preview_id ) {
				$embed_template = BDTEP_INC_PATH . 'builder/templates/embed-card-preview.php';
				if ( file_exists( $embed_template ) ) {
					$GLOBALS['bdt_tb_card_embed_preview_id'] = $preview_id;
					return $embed_template;
				}

				return $template;
			},
			99999
		);

		add_filter( 'show_admin_bar', '__return_false' );
		add_action(
			'wp_enqueue_scripts',
			static function () {
				wp_register_style( 'bdt-tb-card-embed', false, [], '1.0' );
				wp_enqueue_style( 'bdt-tb-card-embed' );
				wp_add_inline_style(
					'bdt-tb-card-embed',
					'html{margin-top:0!important}#wpadminbar{display:none!important}'
				);
			},
			99999
		);
	},
	9
);

add_action(
	'send_headers',
	static function () {
		if ( is_admin() || headers_sent() ) {
			return;
		}
		if ( empty( $_GET['bdt_tb_card_embed'] ) || '1' !== (string) $_GET['bdt_tb_card_embed'] ) {
			return;
		}
		header_remove( 'X-Frame-Options' );
		header( 'X-Frame-Options: SAMEORIGIN', true );
	},
	0
);
