<?php
/**
 * Created by PhpStorm.
 * User: Andrei
 * Date: 15/9/2015
 * Time: 10:14 AM
 */

require_once dirname( __FILE__ ) . "/ConvertKit/Exception.php";

class Thrive_Dash_Api_ConvertKit {

	protected $api_version = 'v3';
	protected $api_url_base = 'https://api.convertkit.com/';
	protected $resources = array();
	protected $markup = array();

	protected $key;


	public function __construct( $key ) {

		if ( empty( $key ) ) {
			throw new Thrive_Dash_Api_ConvertKit_Exception( "Invalid API credentials" );
		}

		$this->key = $key;
	}

	/**
	 * get forms from the API
	 *
	 * @return array|mixed
	 * @throws Thrive_Dash_Api_ConvertKit_Exception
	 */
	public function getForms() {
		$response = $this->_call( 'forms' );

		$forms = isset( $response['forms'] ) ? $response['forms'] : array();

		if ( isset( $response['error_message'] ) ) {
			throw new Thrive_Dash_Api_ConvertKit_Exception( $response['error_message'] );
		}

		return $forms;
	}

	/**
	 * Subscribe user with the old version of the API (v2).
	 * If the V3 API returns failure, it means it's an old form, created when API had version 2
	 *
	 * It seems that the developers at ConvertKit have learnt to write code yesterday.
	 * API V2 -> API V3 changed the IDs of their FORMS for Christ's sake!
	 * I wish they all get diarrhea
	 *
	 * @param mixed $form_id
	 * @param array $fields
	 *
	 * @return array
	 *
	 * @throws Thrive_Dash_Api_ConvertKit_Exception
	 */
	protected function _subscribeForm__v2( $form_id, $fields ) {
		$request = sprintf( 'forms/%s/subscribe', $form_id );

		$args = array(
			'email' => $fields['email'],
			'fname' => $fields['name'],
		);

		$data = $this->_call__v2( $request, $args, 'POST' );

		if ( isset( $data['status'] ) && $data['status'] == 'created' ) {
			return $data;
		}

		if ( isset( $data['status'] ) ) {
			throw new Thrive_Dash_Api_ConvertKit_Exception( 'Error from ConvertKit: ' . $data['status'] );
		}

		throw new Thrive_Dash_Api_ConvertKit_Exception( ( 'Unknown ConvertKit error. Response was: ' . var_export( $data, true ) ) );
	}

	/**
	 * @param string $form_id
	 * @param        $fields array
	 *
	 * @throws Thrive_Dash_Api_ConvertKit_Exception
	 * @return array
	 */
	public function subscribeForm( $form_id, $fields ) {
		$request = sprintf( 'forms/%s/subscribe', $form_id );

		$args = array(
			'email'      => $fields['email'],
			'first_name' => $fields['name'],
		);

		$data = $this->_call( $request, $args, 'POST' );
		/**
		 * Error message generated by API v3 when an older form is submitted - this form has unmatched IDs in API v3
		 */
		if ( isset( $data['error'] ) && $data['error'] === 'Not Found' ) {
			return $this->_subscribeForm__v2( $form_id, $fields );
		}

		if ( isset( $data['error'] ) ) {
			throw new Thrive_Dash_Api_ConvertKit_Exception( 'Error from ConvertKit: ' . ( isset( $data['message'] ) ? $data['message'] : $data['error'] ) );
		}

		if ( ! empty( $data['subscription'] ) && ! empty( $data['subscription']['id'] ) ) {
			return $data['subscription'];
		}

		/* some general error */
		throw new Thrive_Dash_Api_ConvertKit_Exception( ( 'Unknown ConvertKit error. Response was: ' . var_export( $data, true ) ) );
	}

	/**
	 * Does the calls to the API
	 *
	 * @param $path
	 * @param $args
	 * @param $method
	 *
	 * @return array|WP_Error
	 * @throws Thrive_Dash_Api_ConvertKit_Exception
	 */
	protected function _call( $path, $args = array(), $method = "GET" ) {
		$url = $this->build_request_url( $path, $args );
		//build parameters depending on the send method type
		if ( $method == 'GET' ) {
			$request = tve_dash_api_remote_get( $url, $args );
		} elseif ( $method == 'POST' ) {
			$request = tve_dash_api_remote_post( $url, $args );
		} else {
			$request = null;
		}

		if ( is_wp_error( $request ) ) {
			throw new Thrive_Dash_Api_ConvertKit_Exception( 'Could not parse the response !' );
		} else {
			$data = json_decode( wp_remote_retrieve_body( $request ), true );
		}

		return $data;
	}

	/**
	 * @param        $path
	 * @param array  $args
	 * @param string $method
	 *
	 * @return mixed
	 *
	 * @throws Thrive_Dash_Api_ConvertKit_Exception
	 */
	protected function _call__v2( $path, $args = array(), $method = 'GET' ) {

		/* v2 way of doing things */
		$args = array_merge( $args, array( 'k' => $this->key, 'v' => '2' ) );

		$url = $this->api_url_base . $path . '?' . http_build_query( $args );
		if ( $method == 'GET' ) {
			$response = tve_dash_api_remote_get( $url, $args );
		} else {
			$response = tve_dash_api_remote_post( $url, $args );
		}
		if ( is_wp_error( $response ) ) {
			throw new Thrive_Dash_Api_ConvertKit_Exception( 'Could not send request to ConvertKit API: ' . $response->get_error_message() );
		}

		return json_decode( wp_remote_retrieve_body( $response ), true );
	}

	/**
	 * Merge default request arguments with those of this request
	 *
	 * @param  array $args Request arguments
	 *
	 * @return array        Request arguments
	 */
	public function filter_request_arguments( $args = array() ) {
		return array_merge( $args, array( 'api_key' => $this->key ) );
	}

	/**
	 * Build the full request URL
	 *
	 * @param  string $request Request path
	 * @param  array  $args    Request arguments
	 *
	 * @return string          Request URL
	 */
	public function build_request_url( $request, $args = array() ) {
		return $this->api_url_base . $this->api_version . '/' . $request . '?' . http_build_query( $this->filter_request_arguments( $args ) );
	}

}