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

if ( ! function_exists( 'avi_agency_google_create_local_post_wp_remote' ) ) {

/**
 * Crée un Local Post via Google My Business API v4 (wp_remote_post).
 *
 * @param string $access_token           Bearer.
 * @param string $location_resource_name accounts/{aid}/locations/{lid}.
 * @param string $summary                Corps du post.
 * @param string $image_url              URL image optionnelle.
 * @param string $cta_type               LEARN_MORE, BOOK, etc.
 * @param string $cta_link               URL du CTA.
 * @return true|string True ou message d'erreur.
 */
function avi_agency_google_create_local_post_wp_remote( $access_token, $location_resource_name, $summary, $image_url, $cta_type, $cta_link ) {
	$access_token           = is_string( $access_token ) ? trim( $access_token ) : '';
	$location_resource_name = is_string( $location_resource_name ) ? trim( $location_resource_name ) : '';
	if ( $access_token === '' || $location_resource_name === '' || strpos( $location_resource_name, 'accounts/' ) !== 0 ) {
		return 'invalid_google_context';
	}
	$summary = is_string( $summary ) ? trim( $summary ) : '';
	if ( $summary === '' ) {
		return 'empty_post_text';
	}
	$max = 1500;
	if ( function_exists( 'mb_strlen' ) && mb_strlen( $summary ) > $max ) {
		$summary = mb_substr( $summary, 0, $max );
	} elseif ( strlen( $summary ) > $max ) {
		$summary = substr( $summary, 0, $max );
	}

	$allowed_cta = array( 'LEARN_MORE', 'BOOK', 'ORDER', 'SHOP', 'SIGN_UP', 'CALL' );
	$cta_type    = is_string( $cta_type ) ? strtoupper( trim( $cta_type ) ) : 'LEARN_MORE';
	if ( ! in_array( $cta_type, $allowed_cta, true ) ) {
		$cta_type = 'LEARN_MORE';
	}

	$body = array(
		'topicType'    => 'STANDARD',
		'summary'      => $summary,
		'languageCode' => 'fr',
	);

	$image_url = is_string( $image_url ) ? trim( $image_url ) : '';
	if ( $image_url !== '' && filter_var( $image_url, FILTER_VALIDATE_URL ) ) {
		$body['media'] = array(
			array(
				'mediaFormat' => 'PHOTO',
				'sourceUrl'   => $image_url,
			),
		);
	}

	$cta_link = is_string( $cta_link ) ? trim( $cta_link ) : '';
	if ( $cta_link !== '' && filter_var( $cta_link, FILTER_VALIDATE_URL ) ) {
		$body['callToAction'] = array(
			'actionType' => $cta_type,
			'url'        => $cta_link,
		);
	}

	$url = 'https://mybusiness.googleapis.com/v4/' . $location_resource_name . '/localPosts';
	$res = wp_remote_post(
		$url,
		array(
			'headers' => array(
				'Authorization' => 'Bearer ' . $access_token,
				'Content-Type'  => 'application/json; charset=utf-8',
			),
			'body'    => wp_json_encode( $body, JSON_UNESCAPED_UNICODE ),
			'timeout' => 45,
		)
	);

	if ( is_wp_error( $res ) ) {
		return $res->get_error_message();
	}

	$code = (int) wp_remote_retrieve_response_code( $res );
	$raw  = wp_remote_retrieve_body( $res );
	$data = json_decode( $raw, true );

	if ( $code >= 200 && $code < 300 && is_array( $data ) && empty( $data['error'] ) ) {
		return true;
	}

	if ( $code === 401 ) {
		return 'HTTP_401';
	}
	if ( is_array( $data ) && isset( $data['error']['status'] ) && $data['error']['status'] === 'UNAUTHENTICATED' ) {
		return 'HTTP_401';
	}

	if ( is_array( $data ) && isset( $data['error']['message'] ) ) {
		return (string) $data['error']['message'];
	}

	return 'HTTP ' . $code;
}

}
