<?php

/**
 * Class BWFCRM_Webhook_Sendinblue
 * This class tracks the bounced mail from sendinblue
 */
class BWFCRM_Webhook_Sendinblue 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;
	}

	/*
	 * the name in the constructor is the name which will be shown in the dropdown in setting
	 */
	public function __construct() {
		$this->_name = "Sendinblue";
	}

	/**
	 * this is the abstract function from the base class
	 * it needs to be define in child class
	 * it receives the data received from webhook set in sendinblue
	 */
	public function handle_webhook() {
		if ( ! is_array( $this->_data ) || empty( $this->_data ) ) {
			return;
		}

		$this->maybe_bounce_contact_email();
	}

	/**
	 * this function mark the email as bounce
	 */
	private function maybe_bounce_contact_email() {

		if ( ! is_array( $this->_data ) || ! isset( $this->_data['event'] ) || ! is_email( $this->_data['email'] ) ) {
			return;
		}

		/*
		 * filter to handle the softbounce as well
		 * by default it's no
		 */
		$handle_softbounce = apply_filters( 'bwfan_sendinblue_soft_bounce', 'no' );

		if ( $handle_softbounce === 'no' ) {
			if ( 'hard_bounce' !== $this->_data['event'] ) {
				return;
			}
		} else {
			if ( ! in_array( $this->_data['event'], array( 'hard_bounce', 'soft_bounce' ), true ) ) {
				return;
			}
		}

		/**
		 * marking the email as bounce
		 */
		$this->mark_contact_bounce( $this->_data['email'] );
	}
}

/**
 * Registering the BWFCRM_Webhook_Sendinblue
 * it will add the option of sendinblue in the dropdown in setting
 */
BWFCRM_Core()->email_webhooks->register( 'BWFCRM_Webhook_Sendinblue' );
