<?php
namespace WACVP\Inc\Email;

use WACVP\Inc\Data;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Sendinblue_WACV' ) ) {
	class Sendinblue_WACV {
		public $settings;
		protected $api_key;
		protected static $instance = null;

		function __construct() {
			$this->settings = Data::get_params();
			$this->api_key  = $this->settings[ 'sendinblue_api' ];
		}

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

			return self::$instance;
		}

		public function get_lists() {
			if ( ! $this->api_key ) {
				return array();
			}

			try {
				$r = wp_remote_get( 'https://api.sendinblue.com/v3/contacts/lists?limit=50&offset=0&sort=desc', [
					'headers' => [
						'api-key'      => $this->api_key,
						'Accept'       => 'application/json',
						'Content-Type' => 'application/json',
					]
				] );

				$body = wp_remote_retrieve_body( $r );

				return json_decode( $body )->lists;

			} catch ( \Exception $e ) {

			}

			return [];
		}

		public function add_recipient( $email = '', $list_id = [], $firstname = '', $lastname = '' ) {
			if ( ! $this->api_key || ! $email ) {
				return;
			}

			$list_id = array_map( 'absint', (array) $list_id );

			$body = wp_json_encode( [
				'email'         => $email,
				"attributes"    => [
					"FIRSTNAME" => $firstname,
					"LASTNAME"  => $lastname
				],
				"listIds"       => $list_id,
				"updateEnabled" => false,
			] );

			$r = wp_remote_post( 'https://api.sendinblue.com/v3/contacts', [
				'body'    => $body,
				'headers' => [
					'api-key'      => $this->api_key,
					'Accept'       => 'application/json',
					'Content-Type' => 'application/json',
				],
			] );
		}

	}
}
