<?php

class BWFCRM_Webhook_Sendgrid 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 = "Sendgrid";
	}

	public function handle_webhook() {
		if ( ! is_array( $this->_data ) || empty( $this->_data ) ) {
			return;
		}

		$this->maybe_bounce_contact_email();
	}

	private function maybe_bounce_contact_email() {
		foreach ( $this->_data as $datum ) {
			if ( ! is_array( $datum ) || ! isset( $datum['event'] ) || 'bounce' !== $datum['event'] || ! is_email( $datum['email'] ) ) {
				continue;
			}

			$this->mark_contact_bounce( $datum['email'] );
			break;
		}
	}
}

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