<?php

/**
 * Elastic Email Bounce Handling Controller
 */
class BWFCRM_Webhook_ElasticEmail extends BWFCRM_Email_Webhook_Base {
	private static $ins = null;

	public static function get_instance() {
		if ( null === self::$ins ) {
			self::$ins = new self;
		}

		return self::$ins;
	}

	public function __construct() {
		$this->_name = "Elastic Email";
	}

	/**
	 * Email Bounce Service Handler
	 *
	 * @return void
	 */
	public function handle_webhook() {
		if ( ! is_array( $this->_data ) || empty( $this->_data ) ) {
			return;
		}

		$this->maybe_bounce_contact_email();
	}

	/**
	 * Mark contact bounced
	 *
	 * @return void
	 */
	private function maybe_bounce_contact_email() {
		if ( ! is_array( $this->_data ) || ! isset( $this->_data['status'] ) || ! is_email( $this->_data['to'] ) ) {
			return;
		}

		/*
		 * If status is not Error or Complaint
		 */
		if ( ! in_array( $this->_data['status'], array( 'Error', 'Complaint' ), true ) ) {
			return;
		}

		/**
		 * Marking the contact status as Bounce
		 */
		$this->mark_contact_bounce( $this->_data['to'] );
	}
}

BWFCRM_Core()->email_webhooks->register( 'BWFCRM_Webhook_ElasticEmail' );
