<?php

namespace AcademyProMailChimp\Admin;

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

use AcademyProMailChimp\MailChimpService;
use AcademyPro\DrewM\MailChimp\MailChimp;


class Ajax {
	public static function init(): void {
		$self = new self();
		add_action( 'wp_ajax_academy_pro_mailchimp/get_mailchimp_data', array( $self, 'get_mailchimp_data' ) );
		add_action( 'wp_ajax_academy_pro/update_mail_chimp_settings', array( $self, 'update_mailchimp_settings' ) );
		add_action( 'wp_ajax_academy_pro_mailchimp/verify_mailchimp_api_key', array(
			$self,
			'verify_mailchimp_api_key'
		) );
		add_filter( 'academy/api/settings/get_settings', array( $self, 'get_mailchimp_settings' ), 10, 1 );
	}

	public function get_mailchimp_settings( $settings ) {
		if ( ! isset( $settings['mailchimp'] ) ) {
			$settings['mailchimp'] = Settings::get_saved_data();
		}
		return $settings;
	}

	public function get_mailchimp_data( $request ) {
		check_ajax_referer( 'academy_nonce', 'security' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}

		wp_send_json_success( MailChimpService::get_mailchimp_audience_and_groups() );
	}

	public function update_mailchimp_settings() {
		check_ajax_referer( 'academy_nonce', 'security' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}
		$is_enable_force_subscription = isset( $_POST['is_enable_force_subscription'] ) ? sanitize_text_field( wp_unslash( $_POST['is_enable_force_subscription'] ) ) : '';
		$api_key                      = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';
		$subscriber_consent_message   = isset( $_POST['subscriber_consent_message'] ) ? sanitize_text_field( wp_unslash( $_POST['subscriber_consent_message'] ) ) : '';
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized 
		$triggers                     = isset( $_POST['triggers'] ) ? json_decode( wp_unslash( $_POST['triggers'] ), true ) : [];

		$mailchimp_settings = [
			'is_enable_force_subscription' => $is_enable_force_subscription,
			'api_key'                      => $api_key,
			'subscriber_consent_message'   => $subscriber_consent_message,
			'triggers'                     => [
				'student_registration'    => [
					'enable'      => sanitize_text_field( $triggers['student_registration']['enable'] ),
					'list_id'     => sanitize_text_field( $triggers['student_registration']['list_id'] ),
					'group_id'    => sanitize_text_field( $triggers['student_registration']['group_id'] ),
					'interest_id' => sanitize_text_field( $triggers['student_registration']['interest_id'] )
				],
				'instructor_registration' => [
					'enable'      => sanitize_text_field( $triggers['instructor_registration']['enable'] ),
					'list_id'     => sanitize_text_field( $triggers['instructor_registration']['list_id'] ),
					'group_id'    => sanitize_text_field( $triggers['instructor_registration']['group_id'] ),
					'interest_id' => sanitize_text_field( $triggers['instructor_registration']['interest_id'] )
				],
				'course_enroll'           => [
					'enable'      => sanitize_text_field( $triggers['course_enroll']['enable'] ),
					'list_id'     => sanitize_text_field( $triggers['course_enroll']['list_id'] ),
					'group_id'    => sanitize_text_field( $triggers['course_enroll']['group_id'] ),
					'interest_id' => sanitize_text_field( $triggers['course_enroll']['interest_id'] )
				]
			]
		];

		Settings::save_settings( $mailchimp_settings );

		do_action( 'academy_pro_mailchimp_settings_updated', $mailchimp_settings, 'mailchimp_settings' );
		wp_send_json_success( 'Settings saved successfully' );
	}


	public function verify_mailchimp_api_key() {
		check_ajax_referer( 'academy_nonce', 'security' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}
		$api_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';

		if ( empty( $api_key ) ) {
			wp_send_json_error( 'API key is empty' );
		}

		try {
			$mailchimp = new MailChimp( $api_key );
			$result    = $mailchimp->get( 'lists' );
			if ( ! empty( $result['lists'] ) ) {
				Settings::save_settings( [
					'api_key' => $api_key
				] );
				wp_send_json_success( 'API key verified successfully' );
			} else {
				wp_send_json_error( 'Invalid API key' );
			}
		} catch ( Exception $e ) {
			wp_send_json_error( 'Invalid API key' );
		}

	}


}
