<?php

namespace AcademyProMailChimp;

use Exception;
use WP_Error;
use AcademyPro\DrewM\MailChimp\MailChimp;

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

class MailChimpService {
	public static function init() {
		$self = new self();
		$settings = Admin\Settings::get_saved_data();
		if ( empty( $settings['api_key'] ) ) {
			return false;
		}

		add_action( 'academy/shortcode/after_student_registration', array(
			$self,
			'mailchimp_email_insertion_on_student_registration'
		), 3, 3 );
		add_action( 'academy/shortcode/after_instructor_registration', array(
			$self,
			'mailchimp_email_insertion_on_instructor_registration'
		), 3, 3 );
		add_action( 'academy/course/after_enroll', array(
			$self,
			'mailchimp_email_insertion_on_course_enroll'
		), 3, 3 );

	}

	public static function get_mailchimp_audience_and_groups() {
		$settings = Admin\Settings::get_saved_data();
		$api_key = $settings['api_key'];
		if ( empty( $api_key ) ) {
			return [];
		}
		try {
			$mailchimp = new MailChimp( $api_key );
		} catch ( Exception $e ) {
			return [
				'error' => $e->getMessage(),
			];
		}

		$result = $mailchimp->get( 'lists' );

		$audiences = array();
		if ( ! empty( $result['lists'] ) ) {
			foreach ( $result['lists'] as $list ) {
				$audience      = array(
					'value'  => $list['id'],
					'label'  => $list['name'],
					'groups' => array(),
				);
				$groups_result = $mailchimp->get( 'lists/' . $list['id'] . '/interest-categories' );
				if ( ! empty( $groups_result['categories'] ) ) {
					foreach ( $groups_result['categories'] as $group ) {
						$interests        = array();
						$interests_result = $mailchimp->get( 'lists/' . $list['id'] . '/interest-categories/' . $group['id'] . '/interests' );
						foreach ( $interests_result['interests'] as $interest ) {
							$interests[] = array(
								'value' => $interest['id'],
								'label' => $interest['name'],
							);
						}
						$audience['groups'][] = array(
							'value'     => $group['id'],
							'label'     => $group['title'],
							'interests' => $interests,
						);
					}
				} else {
					return array(
						'groups_result' => isset( $groups_result['detail'] ) ? $groups_result['detail'] : '',
					);
				}//end if

				array_push( $audiences, $audience );
			}//end foreach
		} else {
			return new WP_Error(
				__( 'Sorry, something went wrong.', 'academy-pro' ),
				isset( $result['detail'] ) ? $result['detail'] : '',
				array(
					'status' => 403,
				)
			);
		}//end if

		return $audiences;

	}

	public function mailchimp_email_insertion_on_course_enroll( $user_id, $course_id, $order_id ): array {
		// check if the course enroll trigger is enabled and data is present
		$settings = Admin\Settings::get_saved_data();
		if ( ! isset( $settings['triggers']['course_enroll'] ) ) {
			return array(
				'error' => 'Course enroll trigger is not enabled',
			);
		}
		$course_enroll_trigger = $settings['triggers']['course_enroll'];
		$list_id               = $course_enroll_trigger['list_id'];
		$interest_id           = $course_enroll_trigger['interest_id'];

		return $this->insert_into_mailchimp( $user_id, $list_id, $interest_id );
	}

	public function insert_into_mailchimp( $user_id, $list_id, $interest_id ): array {
		$settings = Admin\Settings::get_saved_data();
		$api_key    = $settings['api_key'];
		$mailchimp  = new MailChimp( $api_key );
		$user_email = get_userdata( $user_id )->user_email;
		$user_name  = get_userdata( $user_id )->user_login;
		$first_name = get_userdata( $user_id )->first_name;
		$last_name  = get_userdata( $user_id )->last_name;

		$mailchimp->post(
			"lists/{$list_id}/members",
			array(
				'email_address' => $user_email,
				'status'        => 'subscribed',
				'merge_fields'  => array(
					'FNAME'    => $first_name,
					'LNAME'    => $last_name,
					'USERNAME' => $user_name,
				),
				'interests'     => [
					$interest_id => true,
				],

			)
		);

		if ( $mailchimp->success() ) {
			return array(
				'success' => true,
			);
		} else {
			return array(
				'error message' => $mailchimp->getLastError(),
			);
		}
	}

	public function mailchimp_email_insertion_on_instructor_registration( $user_id ): array {
		$settings = Admin\Settings::get_saved_data();
		// check if the instructor registration trigger is enabled and data is present
		if ( ! isset( $settings['triggers']['instructor_registration'] ) ) {
			return array(
				'error' => 'Instructor registration trigger is not enabled',
			);
		}
		$instructor_registration_trigger = $settings['triggers']['instructor_registration'];
		$list_id                         = $instructor_registration_trigger['list_id'];
		$interest_id                     = $instructor_registration_trigger['interest_id'];

		return $this->insert_into_mailchimp( $user_id, $list_id, $interest_id );
	}

	public function mailchimp_email_insertion_on_student_registration( $user_id ): array {
		$settings = Admin\Settings::get_saved_data();
		// check if the student registration trigger is enabled and data is present
		if ( ! isset( $settings['triggers']['student_registration'] ) ) {
			return array(
				'error' => 'Student registration trigger is not enabled',
			);
		}

		$student_registration_trigger = $settings['triggers']['student_registration'];
		$list_id                      = $student_registration_trigger['list_id'];
		$interest_id                  = $student_registration_trigger['interest_id'];

		return $this->insert_into_mailchimp( $user_id, $list_id, $interest_id );
	}
}
