<?php
/**
 * File Path: includes/api/esp/class-mbs-esp-brevo.php
 * Brevo ESP Adapter -- My Book Showroom
 * Sprint F-026: Email Channel Integration.
 * @package My_Book_Showroom
 * @since   1.1.0
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

class MBS_ESP_Brevo extends MBS_ESP_Adapter_Base { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix
	protected const BASE_URL = 'https://api.brevo.com/v3/';
	private string $api_key;
	public function __construct( string $api_key ) { $this->api_key = $api_key; }
	public function connect(): bool {
		$r = $this->get( 'account' );
		return ! is_wp_error( $r ) && 200 === (int) wp_remote_retrieve_response_code( $r );
	}
	public function get_lists(): array {
		$r = $this->get( 'contacts/lists?limit=50' );
		if ( is_wp_error( $r ) ) { return array(); }
		$b = json_decode( wp_remote_retrieve_body( $r ), true );
		if ( empty( $b['lists'] ) ) { return array(); }
		$out = array();
		foreach ( $b['lists'] as $lst ) { $out[] = array( 'id' => (string) $lst['id'], 'name' => (string) $lst['name'] ); }
		return $out;
	}
	public function subscribe( string $email, string $name, string $list_id, bool $double_optin ): bool {
		$list_id_int = (int) $list_id;
		if ( $double_optin ) {
			$payload = array( 'email' => $email, 'includeListIds' => array( $list_id_int ), 'redirectionUrl' => '' );
			$r = $this->post( 'contacts/doubleOptinConfirmation', $payload );
		} else {
			$payload = array( 'email' => $email, 'listIds' => array( $list_id_int ) );
			if ( '' !== $name ) { $payload['attributes'] = array( 'FIRSTNAME' => $name ); }
			$r = $this->post( 'contacts', $payload );
		}
		if ( is_wp_error( $r ) ) { return false; }
		$code = (int) wp_remote_retrieve_response_code( $r );
		// 201 created, 204 already exists.
		return in_array( $code, array( 201, 204 ), true );
	}
	public function tag_contact( string $email, array $tags, string $list_id ): bool {
		if ( empty( $tags ) ) { return true; }
		$endpoint = 'contacts/' . rawurlencode( $email );
		$r = $this->request( 'PUT', $endpoint, array( 'tags' => array_values( $tags ) ) );
		return ! is_wp_error( $r ) && (int) wp_remote_retrieve_response_code( $r ) >= 200 && (int) wp_remote_retrieve_response_code( $r ) < 300;
	}
	public function supports_tags(): bool { return true; }
	public function create_campaign( string $subject, string $body_html, string $list_id ): ?string {
		$sender_name  = mbs_get_setting( 'email', 'from_name', '' );
		if ( empty( $sender_name ) ) { $sender_name = get_bloginfo( 'name' ); }
		$sender_email = mbs_get_setting( 'email', 'reply_to', '' );
		if ( empty( $sender_email ) ) { $sender_email = get_option( 'admin_email' ); }
		$payload = array(
			'name'        => $subject, 'subject'     => $subject, 'type'        => 'classic',
			'sender'      => array( 'name' => $sender_name, 'email' => $sender_email ),
			'recipients'  => array( 'listIds' => array( (int) $list_id ) ),
			'htmlContent' => $body_html,
		);
		$r = $this->post( 'emailCampaigns', $payload, self::TIMEOUT_CAMPAIGN );
		if ( is_wp_error( $r ) ) { return null; }
		if ( (int) wp_remote_retrieve_response_code( $r ) < 200 || (int) wp_remote_retrieve_response_code( $r ) >= 300 ) { return null; }
		$b = json_decode( wp_remote_retrieve_body( $r ), true );
		return isset( $b['id'] ) ? (string) $b['id'] : null;
	}
	public function send_campaign( string $campaign_id ): bool {
		$endpoint = 'emailCampaigns/' . rawurlencode( $campaign_id ) . '/sendNow';
		$r = $this->post( $endpoint, array(), self::TIMEOUT_CAMPAIGN );
		return ! is_wp_error( $r ) && (int) wp_remote_retrieve_response_code( $r ) >= 200 && (int) wp_remote_retrieve_response_code( $r ) < 300;
	}
	public function supports_campaigns(): bool { return true; }
	protected function auth_headers(): array { return array( 'api-key' => $this->api_key ); }
}
