<?php
namespace WACVP\Inc\Email;

use WACVP\Inc\Data;

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

class ActiveCampaign_WACV {
	protected $settings;
	protected $api_key;
	protected $url;
	protected static $instance = null;

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

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

		return self::$instance;
	}

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

		try {
			$r = wp_remote_get( $this->url . '/api/3/lists', [
				'headers' => [
					'Api-Token'      => $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_contact( $email = '', $list_id = '', $firstname = '', $lastname = '' ) {
		if ( ! $this->api_key || ! $email || ! $this->url ) {
			return;
		}

		$list_id = absint( $list_id );

		$body = wp_json_encode( [
			"contact"       => [
				"email"     => $email,
				"firstName" => $firstname,
				"lastName"  => $lastname
			],
		] );

		$r = wp_remote_post( $this->url . '/api/3/contacts', [
			'body'    => $body,
			'headers' => [
				'Api-Token'      => $this->api_key,
				'Accept'       => 'application/json',
				'Content-Type' => 'application/json',
			],
		] );
		$res_code = wp_remote_retrieve_response_code( $r );
		if ( 201 == intval( $res_code ) ) {
			$body_r       = wp_remote_retrieve_body( $r );
			$contact_r    = json_decode( $body_r )->contact;
			$contact_id_r = $contact_r->id;
			if ( $contact_id_r ) {
				$contact_id_r = intval( $contact_id_r );
				$l_body = wp_json_encode( [
					"contactList" => [
						"list"    => $list_id,
						"contact" => $contact_id_r,
						"status"  => 1
					],
				] );

				$r_list = wp_remote_post( $this->url . '/api/3/contactLists', [
					'body'    => $l_body,
					'headers' => [
						'Api-Token'    => $this->api_key,
						'Accept'       => 'application/json',
						'Content-Type' => 'application/json',
					],
				] );
			}
		}
	}

}
