<?php
namespace AcademyProSendfox;

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

class Integration {
	public static function init() {
		$self = new self();
		add_action( 'wp_ajax_academy_pro/sendfox/get_lists', array( $self, 'get_sendfox_lists' ) );
		add_action( 'academy/course/after_enroll', array( $self, 'academy_course_enroll' ), 11, 3 );
	}

	public function get_sendfox_lists() {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}
		$lists = gb_sf4wp_get_lists();
		if ( 'success' === $lists['status'] ) {
			$result = $lists['result']['data'] ?? [];
			wp_send_json_success( [
				'message' => $lists['status'],
				'data' => $result
			] );
		}
		wp_send_json_error( [
			'message' => $lists['status'],
			'data' => [],
		] );
	}

	public function academy_course_enroll( $course_id, $enroll_id, $user_id ) {
		$user = get_user_by( 'id', $user_id );

		if ( ! empty( $user ) && ! empty( $user->user_email ) ) {
			$sendfox_list_id = (int) \Academy\Helper::get_settings( 'sendfox_trigger_lists' )->student_enrolled_sendfox_list_id;
			if ( $sendfox_list_id ) {
				$contact = array(
					'email' => $user->user_email,
					'lists' => array(
						$sendfox_list_id
					),
				);

				if ( ! empty( $user->user_nicename ) ) {
					$contact['first_name'] = $user->user_nicename;
				}

				$contact = apply_filters( 'academy_pro_sendfox/before_add_contact', $contact, 'academy-course', $user );

				$result = gb_sf4wp_add_contact( $contact );
			}
		}
	}
}
