<?php
/**
 * EAC Relationship Block (fonctions) — Librairie de fonctions pour le bloc Relationship
 * Notamment pour l'API REST et l'enregistrement des routes Relationship
 *
 * @since 2.5.3
 */

if ( ! defined( 'ABSPATH' ) ) {
	return;
}

/**
 * eac_register_route_relationship
 * Récupère les relationship Post block ACF du post pour l'API REST
 * http://127.0.0.1/eac234/wp-json/eac-blocks/v1/acf-relationship?postId=60932
 * 'permission_callback' => '__return_true' pour autoriser l'accès à tous les utilisateurs (y compris les non connectés)
 *
 * @return void
 */
function eac_register_route_relationship() {
	register_rest_route(
		'eac-blocks/v1',
		'/acf-relationship/(?P<postId>\d+)',
		array(
			'methods'             => WP_REST_Server::READABLE, // GET
			'callback'            => 'eac_rest_get_relationship',
			'permission_callback' => function () {
				return current_user_can( 'edit_posts' );
			},
			'args' => array(
				'postId' => array(
					'required'           => true,
					'validate_callback'  => function ( $param ) {
						return is_numeric( $param ) && intval( $param ) > 0;
					},
					'sanitize_callback'  => 'absint',
				),
			),
		)
	);

	register_rest_route(
		'eac-blocks/v1',
		'/acf-relationship-author/(?P<authorId>\d+)',
		array(
			'methods'             => WP_REST_Server::READABLE, // GET
			'callback'            => 'eac_rest_get_relationship_author',
			'permission_callback' => function () {
				return current_user_can( 'edit_posts' );
			},
			'args' => array(
				'authorId' => array(
					'required'           => true,
					'validate_callback'  => function ( $param ) {
						return is_numeric( $param ) && intval( $param ) > 0;
					},
					'sanitize_callback'  => 'absint',
				),
			),
		)
	);
}

// Enregistre la route REST API pour le bloc Relationship
add_action( 'rest_api_init', 'eac_register_route_relationship', 30 );

/**
 * eac_rest_get_relationship
 * Récupère les relationship et Post block ACF du post pour l'API REST
 *
 * @param WP_REST_Request $request
 *
 * @return WP_REST_Response | WP_Error
 */
if ( ! function_exists( 'eac_rest_get_relationship' ) ) {
	function eac_rest_get_relationship( WP_REST_Request $request ) {
		$postid = $request->get_param( 'postId' ) ? absint( $request->get_param( 'postId' ) ) : 0;
		$result = array();

		if ( 0 === $postid ) {
			return new WP_Error( 'invalid_post_id', 'Invalid post ID', array( 'status' => 400 ) );
		}

		$post = get_post( $postid );
		if ( ! $post ) {
			return new WP_Error( 'rest_post_invalid', 'Post not found', array( 'status' => 404 ) );
		}

		if ( function_exists( 'acf_get_field_groups' ) ) {
			$groups = acf_get_field_groups( array( 'post_id' => $postid ) );

			foreach ( $groups as $group ) {
				if ( ! $group['active'] ) {
					continue;
				}
				$fields = acf_get_fields( $group['ID'] );

				if ( ! is_array( $fields ) ) {
					continue;
				}

				foreach ( $fields as $field ) {
					if ( isset( $field['type'] ) && \acf_field_type_exists( $field['type'] ) && in_array( $field['type'], array( 'relationship', 'post_object' ), true ) ) {
						$result[] = array(
							'key'   => sanitize_text_field( $field['key'] ),
							'label' => isset( $field['label'] ) ? html_entity_decode( sanitize_text_field( $field['label'] ), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' ) : sanitize_text_field( $field['name'] ),
						);
					} elseif ( 'group' === $field['type'] && ! empty( $field['sub_fields'] ) && is_array( $field['sub_fields'] ) ) {
						foreach ( $field['sub_fields'] as $sub_field ) {
							if ( isset( $sub_field['type'] ) && \acf_field_type_exists( $sub_field['type'] ) && in_array( $sub_field['type'], array( 'relationship', 'post_object' ), true ) ) {
								$result[] = array(
									'key'   => sprintf( '%s_%s', sanitize_text_field( $field['name'] ), sanitize_text_field( $sub_field['name'] ) ), // combinaison: group_name_field_name
									'label' => isset( $sub_field['label'] ) ? html_entity_decode( sanitize_text_field( $sub_field['label'] ), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' ) : sanitize_text_field( $sub_field['name'] ),
								);
							}
						}
					}
				}
			}
		}
		return rest_ensure_response( $result );
	}
}

/**
 * eac_rest_get_relationship_author
 * Récupère les relationship et Post block ACF du profil utilisateur pour l'API REST
 *
 * @param WP_REST_Request $request
 *
 * @return WP_REST_Response | WP_Error
 */
if ( ! function_exists( 'eac_rest_get_relationship_author' ) ) {
	function eac_rest_get_relationship_author( WP_REST_Request $request ) {
		$author_id = $request->get_param( 'authorId' ) ? absint( $request->get_param( 'authorId' ) ) : 0;
		$result = array();

		if ( 0 === $author_id ) {
			return new WP_Error( 'invalid_author_id', 'Invalid author ID', array( 'status' => 400 ) );
		}

		// Vérifier que l'utilisateur existe
		$user = get_user_by( 'id', $author_id );
		if ( ! $user ) {
			return new WP_Error( 'author_not_found', 'Author not found', array( 'status' => 404 ) );
		}

		if ( function_exists( 'acf_get_field_groups' ) ) {
			// Récupérer les groupes de champs ACF du profil utilisateur
			$groups = acf_get_field_groups( array( 'user_id' => $author_id ) );

			foreach ( $groups as $group ) {
				if ( ! $group['active'] ) {
					continue;
				}
				$fields = acf_get_fields( $group['ID'] );

				if ( ! is_array( $fields ) ) {
					continue;
				}

				foreach ( $fields as $field ) {
					if ( isset( $field['type'] ) && \acf_field_type_exists( $field['type'] ) && in_array( $field['type'], array( 'relationship', 'post_object' ), true ) ) {
						$result[] = array(
							'key'   => sanitize_text_field( $field['key'] ),
							'label' => isset( $field['label'] ) ? html_entity_decode( sanitize_text_field( $field['label'] ), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' ) : sanitize_text_field( $field['name'] ),
						);
					} elseif ( 'group' === $field['type'] && ! empty( $field['sub_fields'] ) && is_array( $field['sub_fields'] ) ) {
						foreach ( $field['sub_fields'] as $sub_field ) {
							if ( isset( $sub_field['type'] ) && \acf_field_type_exists( $sub_field['type'] ) && in_array( $sub_field['type'], array( 'relationship', 'post_object' ), true ) ) {
								$result[] = array(
									'key'   => sprintf( '%s_%s', sanitize_text_field( $field['name'] ), sanitize_text_field( $sub_field['name'] ) ),
									'label' => isset( $sub_field['label'] ) ? html_entity_decode( sanitize_text_field( $sub_field['label'] ), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' ) : sanitize_text_field( $sub_field['name'] ),
								);
							}
						}
					}
				}
			}
		}
		return rest_ensure_response( $result );
	}
}
