<?php
/**
 * Account_API class.
 *
 * @since 1.0.0
 * @package smtp
 * @subpackage mailers
 */

namespace DoubleScale\Modules\Smtp\Providers\ElasticEmail;

defined( 'ABSPATH' ) || exit;

use WP_Error;

/**
 * Account_API class.
 *
 * @since 1.0.0
 */
class Account_API {

	/**
	 * API
	 *
	 * @var string
	 */
	protected $api_key;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param array $api_key API key.
	 */
	public function __construct( $api_key ) {
		$this->api_key = $api_key;
	}

	/**
	 * Send email
	 *
	 * @param array  $args Email arguments.
	 * @param string $content_type Content type.
	 *
	 * @return WP_Error|array
	 */
	public function send( $args, $content_type = 'application/json' ) {
		$response = wp_remote_request(
			'https://api.elasticemail.com/v2/email/send?apikey=' . $this->api_key,
			array(
				'method'  => 'POST',
				'headers' => array(
					'Content-Type' => $content_type,
				),
				'body'    => $args,
			)
		);

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$body = wp_remote_retrieve_body( $response );

		if ( empty( $body ) ) {
			return new WP_Error( 'empty_response', __( 'Empty response.', 'doublescale' ) );
		}

		$body = json_decode( $body, true );

		if ( ! is_array( $body ) ) {
			return new WP_Error( 'invalid_response', __( 'Invalid response.', 'doublescale' ) );
		}

		if ( ! isset( $body['success'] ) || ( isset( $body['success'] ) && ! $body['success'] ) ) {
			return new WP_Error( 'could_not_send', isset( $body['error'] ) ? $body['error'] : __( 'Could not send email.', 'doublescale' ) );
		}

		return $body;
	}

	/**
	 * Send batch emails using Elastic Email API v4 Bulk Endpoint
	 *
	 * Uses the /v4/emails bulk endpoint to send all recipients in a single API call.
	 * Elastic Email handles {field} merge tag replacement server-side using the
	 * Fields property for each recipient.
	 *
	 * @see https://elasticemail.com/developers/api-documentation/rest-api#operation/emailsPost
	 *
	 * @since 1.0.0
	 *
	 * @param array $batch_args {
	 *     Batch email arguments.
	 *
	 *     @type string $from_email          Sender email address
	 *     @type string $from_name           Sender name
	 *     @type array  $to                  Array of recipient email addresses
	 *     @type string $subject             Email subject (can contain {field} merge tags)
	 *     @type string $html                HTML body (can contain {field} merge tags)
	 *     @type string $text                Plain text body (optional)
	 *     @type string $reply_to            Reply-to email (optional)
	 *     @type array  $recipient_variables Associative array keyed by email with merge field data
	 *     @type string $channel             Channel name for tracking (optional)
	 *     @type string $connection_id       Connection ID for logging (optional)
	 *     @type string $account_id          Account ID for logging (optional)
	 * }
	 *
	 * @return WP_Error|array
	 */
	public function send_batch( $batch_args ) {
		// Validate recipients
		if ( empty( $batch_args['to'] ) || ! is_array( $batch_args['to'] ) ) {
			return new WP_Error( 'invalid_recipients', __( 'Recipients array is required.', 'doublescale' ) );
		}

		// Elastic Email bulk endpoint supports large batches
		if ( count( $batch_args['to'] ) > 10000 ) {
			return new WP_Error( 'too_many_recipients', __( 'Maximum 10000 recipients per batch.', 'doublescale' ) );
		}

		$recipients = array();
		foreach ( $batch_args['to'] as $email ) {
			if ( ! is_email( $email ) ) {
				continue;
			}
			$recipients[] = $email;
		}

		if ( empty( $recipients ) ) {
			return new WP_Error( 'no_valid_recipients', __( 'No valid recipient emails found.', 'doublescale' ) );
		}

		// Build recipients array with Fields for personalization (merge tags)
		// Elastic Email will replace {field} in subject/body with these values server-side
		$recipients_data = array();
		foreach ( $recipients as $email ) {
			$recipient = array(
				'Email' => $email,
			);

			// Add merge fields for this recipient
			if ( ! empty( $batch_args['recipient_variables'][ $email ] ) ) {
				$recipient['Fields'] = $batch_args['recipient_variables'][ $email ];
			}

			$recipients_data[] = $recipient;
		}

		// Build the from address
		$from_email = $batch_args['from_email'] ?? '';
		$from_name  = $batch_args['from_name'] ?? '';
		$from       = ! empty( $from_name ) ? "{$from_name} <{$from_email}>" : $from_email;

		// Build the Bulk API v4 payload
		$payload = array(
			'Recipients' => $recipients_data,
			'Content'    => array(
				'From'    => $from,
				'Subject' => $batch_args['subject'] ?? '',
				'Body'    => array(),
			),
		);

		// Add HTML body
		if ( ! empty( $batch_args['html'] ) ) {
			$payload['Content']['Body'][] = array(
				'ContentType' => 'HTML',
				'Content'     => $batch_args['html'],
			);
		}

		// Add text body
		if ( ! empty( $batch_args['text'] ) ) {
			$payload['Content']['Body'][] = array(
				'ContentType' => 'PlainText',
				'Content'     => $batch_args['text'],
			);
		}

		// Add reply-to
		if ( ! empty( $batch_args['reply_to'] ) ) {
			$payload['Content']['ReplyTo'] = $batch_args['reply_to'];
		}

		// Add tracking options
		$payload['Options'] = array(
			'TrackOpens'  => true,
			'TrackClicks' => true,
		);

		// Add channel/campaign for tracking
		if ( ! empty( $batch_args['tags'] ) && is_array( $batch_args['tags'] ) ) {
			$payload['Options']['ChannelName'] = $batch_args['tags'][0];
		}

		// Send via Elastic Email Bulk API v4 (single request for all recipients)
		$response = wp_remote_post(
			'https://api.elasticemail.com/v4/emails',
			array(
				'headers' => array(
					'Accept'                => 'application/json',
					'Content-Type'          => 'application/json',
					'X-ElasticEmail-ApiKey' => $this->api_key,
				),
				'body'    => wp_json_encode( $payload ),
				'timeout' => 120,
			)
		);

		if ( is_wp_error( $response ) ) {
			$this->log_batch_emails( $batch_args, $recipients, $response );
			return $response;
		}

		$status_code = wp_remote_retrieve_response_code( $response );
		$body        = wp_remote_retrieve_body( $response );
		$body_data   = json_decode( $body, true );

		// Check for errors
		if ( $status_code >= 400 || ( isset( $body_data['Success'] ) && $body_data['Success'] === false ) ) {
			$error_message = $body_data['Error'] ?? $body_data['Message'] ?? __( 'Unknown API error.', 'doublescale' );
			$error         = new WP_Error(
				'elasticemail_error',
				$error_message,
				array(
					'status' => $status_code,
					'body'   => $body,
				)
			);
			$this->log_batch_emails( $batch_args, $recipients, $error );
			return $error;
		}

		// Success - build result
		$result = array(
			'id'             => $body_data['MessageID'] ?? $body_data['TransactionID'] ?? '',
			'message'        => __( 'Batch email sent successfully.', 'doublescale' ),
			'sent_count'     => count( $recipients ),
			'failed'         => array(),
			'transaction_id' => $body_data['TransactionID'] ?? '',
		);

		$this->log_batch_emails( $batch_args, $recipients, $result );

		return $result;
	}

	/**
	 * Log batch emails to smtp email log
	 *
	 * @since 1.0.0
	 *
	 * @param array $batch_args  Original batch arguments
	 * @param array $recipients  Valid recipient emails
	 * @param mixed $result      API response (array on success, WP_Error on failure)
	 */
	protected function log_batch_emails( $batch_args, $recipients, $result ) {
		if ( ! function_exists( 'doublescale_get_smtp_email_log' ) ) {
			return;
		}

		$smtp_outbound_log = doublescale_get_smtp_email_log();
		if ( ! $smtp_outbound_log ) {
			return;
		}

		$connection_id = $batch_args['connection_id'] ?? '';
		$account_id    = $batch_args['account_id'] ?? '';

		if ( empty( $connection_id ) || empty( $account_id ) ) {
			$settings    = get_option( 'doublescale_smtp_settings', array() );
			$connections = $settings['connections'] ?? array();

			foreach ( array( 'default_connection', 'fallback_connection' ) as $key ) {
				if ( ! empty( $settings[ $key ] ) && isset( $connections[ $settings[ $key ] ] ) ) {
					$conn = $connections[ $settings[ $key ] ];
					if ( ( $conn['mailer'] ?? '' ) === 'elasticemail' ) {
						$connection_id = $settings[ $key ];
						$account_id    = $conn['account_id'] ?? '';
						break;
					}
				}
			}
		}

		$status   = is_wp_error( $result ) ? 'failed' : 'succeeded';
		$response = is_wp_error( $result ) ? $result->get_error_message() : $result;

		$from_email = $batch_args['from_email'] ?? '';
		$from_name  = $batch_args['from_name'] ?? '';
		$from       = ! empty( $from_name ) ? "{$from_name} <{$from_email}>" : $from_email;

		$subject         = $batch_args['subject'] ?? '';
		$body            = $batch_args['html'] ?? $batch_args['text'] ?? '';
		$headers         = array();
		$attachments     = array();
		$recipients_data = array(
			'to'       => implode( ', ', $recipients ),
			'cc'       => '',
			'bcc'      => '',
			'reply_to' => $batch_args['reply_to'] ?? '',
		);

		$smtp_outbound_log->handle(
			$subject . ' [Batch: ' . count( $recipients ) . ' recipients]',
			$body,
			$headers,
			$attachments,
			$from,
			$recipients_data,
			$status,
			'elasticemail',
			$connection_id,
			$account_id,
			$response
		);
	}

	/**
	 * Get user account
	 *
	 * @return object|WP_Error
	 */
	public function get_account() {
		$response = wp_remote_get(
			'https://api.elasticemail.com/v2/account/load?apikey=' . $this->api_key,
			array(
				'headers' => array(
					'Accept'        => 'application/json',
					'Content-Type'  => 'application/json; charset=' . get_option( 'blog_charset' ),
					'Cache-Control' => 'no-cache',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$body = wp_remote_retrieve_body( $response );
		if ( empty( $body ) ) {
			return new WP_Error( 'empty_response', __( 'Empty response.', 'doublescale' ) );
		}

		$body = json_decode( $body, true );

		if ( ! isset( $body['success'] ) || ( isset( $body['success'] ) && ! $body['success'] ) ) {
			return new WP_Error( 'invalid_api_key', __( 'Failed to get account.', 'doublescale' ) );
		}

		return $body;
	}
}
