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

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

/**
 * eac_register_route_repeater
 * Récupère les repeaters et subfields ACF du post pour l'API REST
 * Exemple d'URL pour tester dans le navigateur ou Postman (remplacer postId par un ID de post existant) :
 * http://127.0.0.1/eac234/wp-json/eac-blocks/v1/acf-repeater?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_repeater() {
	register_rest_route(
		'eac-blocks/v1',
		'/acf-repeater/(?P<postId>\d+)',
		array(
			'methods'             => WP_REST_Server::READABLE, // GET
			'callback'            => 'eac_rest_get_repeater',
			'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-subfield/(?P<postId>\d+)/(?P<fieldId>[^/]+)',
		array(
			'methods'             => WP_REST_Server::READABLE, // GET
			'callback'            => 'eac_rest_get_repeater_subfield',
			'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',
				),
				'fieldId' => array(
					'required' => true,
					'validate_callback' => function ( $param ) {
						return is_string( $param ) && preg_match( '/^field_[a-z0-9]+$/i', $param );
					},
					'sanitize_callback' => 'sanitize_text_field',
				),
			),
		)
	);
}

// Enregistre les routes REST pour les repeaters et subfields ACF
add_action( 'rest_api_init', 'eac_register_route_repeater', 26 );

/**
 * eac_rest_get_repeater
 * Récupère les repeaters ACF du post
 *
 * @param WP_REST_Request $request
 *
 * @return WP_REST_Response | WP_Error
 */
function eac_rest_get_repeater( 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 ( \acf_field_type_exists( $field['type'] ) && 'eac_repeater' === $field['type'] ) {
					$result[] = array(
						'key'  => sanitize_text_field( (string) $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'] ),
					);
				}
			}
		}
	}
	return rest_ensure_response( $result );
}

/**
 * eac_rest_get_repeater_subfield
 * Récupère les sous champs d'un repeater ACF du post pour l'API REST
 *
 * @param WP_REST_Request $request
 *
 * @return WP_REST_Response | WP_Error
 */
function eac_rest_get_repeater_subfield( WP_REST_Request $request ) {
	$postid       = $request->get_param( 'postId' ) ? absint( $request->get_param( 'postId' ) ) : 0;
	$repeater_key = $request->get_param( 'fieldId' ) ? sanitize_text_field( $request->get_param( 'fieldId' ) ) : '';
	$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 ( empty( $repeater_key ) ) {
		return new WP_Error( 'invalid_field_id', 'Invalid field ID', array( 'status' => 400 ) );
	}

	$repeater_obj = get_field_object( $repeater_key, $postid );

	if ( $repeater_obj && ! empty( $repeater_obj['sub_fields'] ) ) {
		$temp = array();
		$temp_image = array();
		$temp_other = array();
		foreach ( $repeater_obj['sub_fields'] as $sub_field ) {
			if ( isset( $sub_field['type'] ) && eac_is_supported_field_type( $sub_field['type'] ) ) {
				$key   = sanitize_text_field( (string) $sub_field['key'] );
				$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'] );
				$type  = sanitize_text_field( (string) $sub_field['type'] );

				if ( 'image' === $type ) {
					$temp_image[ $key ] = array(
						'key'   => $key,
						'label' => $label,
						'type'  => $type,
					);
				} else {
					$temp_other[ $key ] = array(
						'key'   => $key,
						'label' => $label,
						'type'  => $type,
					);
				}
			}
		}
		$temp = array_merge( $temp_image, $temp_other ); // les champs image en premier
		$result = array_values( $temp );
	}
	return rest_ensure_response( $result );
}

/**
 * eac_is_a_valid_pdf
 * Teste si c'est un fihcier PDF
 *
 * @param string $url
 *
 * @return bool
 */
function eac_is_a_valid_pdf( string $url = '' ): bool {
	if ( '' === $url || ! wp_http_validate_url( $url ) ) {
		return false;
	}

	$head = wp_remote_head(
		$url,
		array(
			'redirection' => 2,
			'timeout' => 10,
		),
	);

	if ( is_wp_error( $head ) ) {
		return false;
	}

	$code = wp_remote_retrieve_response_code( $head );
	if ( $code < 200 || $code >= 400 ) {
		return false;
	}

	$content_type = wp_remote_retrieve_header( $head, 'content-type' );
	if ( $content_type && stripos( $content_type, 'application/pdf' ) === false ) {
		return false;
	}

	$args = array(
		'method'      => 'GET',
		'timeout'     => 15,
		'redirection' => 2,
		'headers'     => array( 'Range' => 'bytes=0-1023' ),
	);
	$res = wp_remote_get( $url, $args );
	if ( is_wp_error( $res ) ) {
		return false;
	}

	$code = wp_remote_retrieve_response_code( $res );
	if ( $code < 200 || $code >= 400 ) {
		return false;
	}

	$body = wp_remote_retrieve_body( $res );
	if ( '' === $body ) {
		return false;
	}

	// Vérifie la signature %PDF- dans les premiers octets

	if ( strpos( substr( $body, 0, 8 ), '%PDF-' ) !== false ) {
		return true;
	}

	return false;
}
