<?php

function sendy_list_exists( $list_id ) {

	$sendy_url = get_option( 'sendy_url' );
	$url = $sendy_url . '/api/subscribers/active-subscriber-count.php';
	$sendy_api_key = get_option( 'sendy_api_key' );

	$response = wp_remote_post( $url, array( 'body'=>array( 'api_key'=>$sendy_api_key, 'list_id'=>$list_id ) ) );

	if ( is_wp_error( $response ) ) {

		$error_message = $response->get_error_message();

		$count = "Something went wrong.Make sure API key and List ID are correct";

	} else {

		if ( $response['body'] == 'List does not exist' ) {
			return false;
		} else {
			return true;
		}
	}
}


add_action( 'wp_ajax_add_sendy_user', 'add_sendy_user' );
add_action( 'wp_ajax_nopriv_add_sendy_user', 'add_sendy_user' );

function add_sendy_user() {

	if ( isset( $_POST ) && ! empty( $_POST ) ) {


		parse_str( $_POST['formdata'], $fields );

		if ( isset( $fields['captcha_code'] ) ) {
			/* Check captcha */
			include plugin_dir_path( __FILE__ ) . '/captcha/securimage.php';

			$securimage = new Securimage();

			if ( $securimage->check( $fields['captcha_code'] ) == false ) {

				echo "captcha_error";
				die;
			}
		}

		/* Add data to sendy list*/
		$name = empty( $fields['name'] )?'':$fields['name'];
		$response = add_user_to_sendy( $name, $fields['email'], $fields['list'] );

		echo $response;

	}

	die();
}



function add_user_to_sendy( $name, $email, $listids, $custom_fields = array( '' ) ) {

	if ( ! empty( $email ) ) {

		$sendy_url = rtrim( get_option( 'sendy_url' ), '/' ) . '/subscribe';
		if ( empty( $listids ) ) {
			$listids = array();
		}
		$body = array( 'name' => $name, 'email' => $email, 'boolean' => 'true' );

		if ( ! empty( $custom_fields ) ) {
			foreach ( $custom_fields as $key => $value ) {
				$body[$key] = $value;
			}
		}

		foreach ( $listids as $list_id ) {
			$body['list'] = $list_id;
			$response = wp_remote_post( $sendy_url, array( 'body' => $body ) );
		}

		if ( is_wp_error( $response ) ) {

			return $error_message = $response->get_error_message();

		} else {

			return $response['body'];
		}
	}


}


function delete_user_to_sendy() {

	parse_str( $_POST['formdata'], $fields );

	if ( ! empty( $fields['unsubscribe-email'] ) ) {

		$sendy_url = rtrim( get_option( 'sendy_url' ), '/' ) . '/unsubscribe';

		foreach ( $fields['list'] as $list_id ) {

			$response = wp_remote_post( $sendy_url, array( 'body' => array(  'email' => $fields['unsubscribe-email'], 'list' => $list_id, 'boolean' => 'true' ) ) );
		}

		if ( is_wp_error( $response ) ) {

			echo  $error_message = $response->get_error_message();

		} else {

			echo  $response['body'];
		}
	}
	die;

}


add_action( 'wp_ajax_delete_sendy_user', 'delete_user_to_sendy' );
add_action( 'wp_ajax_nopriv_delete_sendy_user', 'delete_user_to_sendy' );


function save_sendy_options() {

	update_option( 'sendy_url', $_POST['sendy_url'] );
	update_option( 'sendy_api_key', $_POST['api_key'] );
	update_option( 'sendy_terms_link', $_POST['sendy_terms_link'] );
	update_option( 'sendy_redirect_url', $_POST['sendy_redirect_url'] );

	if ( ! empty( $_POST['new_list_name'] ) && ! empty( $_POST['new_list_id'] ) ) {

		$sendy_lists = get_option( 'sendy_lists' );

		$list_id = trim( $_POST['new_list_id'] );

		$sendy_lists[$list_id] = $_POST['new_list_name'];

		update_option( 'sendy_lists', $sendy_lists );

	}

	if ( ! empty( $_POST['sendy_on_register'] ) ) {
		update_option( 'sendy_on_register', $_POST['sendy_on_register'] );
	}else {
		update_option( 'sendy_on_register', '' );
	}


	if ( ! empty( $_POST['sendy_register_page_lists'] ) ) {
		update_option( 'sendy_register_page_lists', $_POST['sendy_register_page_lists'] );
	}



	if ( ! empty( $_POST['sendy_woo_checkout_check'] ) && $_POST['sendy_woo_checkout_check'] == 'on' ) {
		update_option( 'sendy_woo_checkout_check', $_POST['sendy_woo_checkout_check'] );

	}else {
		update_option( 'sendy_woo_checkout_check', '' );
	}
	if ( ! empty( $_POST['sendy_woo_checkout_page_lists'] ) ) {
		update_option( 'sendy_woo_checkout_page_lists', $_POST['sendy_woo_checkout_page_lists'] );

	}

	if ( ! empty( $_POST['sendy_edd_checkout_check'] ) && $_POST['sendy_edd_checkout_check'] == 'on' ) {
		update_option( 'sendy_edd_checkout_check', $_POST['sendy_edd_checkout_check'] );

	}else {
		update_option( 'sendy_edd_checkout_check', '' );
	}
	if ( ! empty( $_POST['sendy_edd_checkout_page_lists'] ) ) {
		update_option( 'sendy_edd_checkout_page_lists', $_POST['sendy_edd_checkout_page_lists'] );

	}

	if ( ! empty( $_POST['sendy_buddypress_check'] ) && $_POST['sendy_buddypress_check'] == 'on' ) {
		update_option( 'sendy_buddypress_check', $_POST['sendy_buddypress_check'] );

	}else {
		update_option( 'sendy_buddypress_check', '' );
	}
	if ( ! empty( $_POST['sendy_buddypress_lists'] ) ) {
		update_option( 'sendy_buddypress_lists', $_POST['sendy_buddypress_lists'] );

	}

	update_option( 'sendy_recaptcha', $_POST['sendy_recaptcha'] );

}
/* Delete sendy List */


function delete_sendy_list() {
	$sendy_lists = get_option( 'sendy_lists' );

	$list_id = trim( $_GET['id'] );

	if ( ! empty( $list_id ) ) {

		if ( array_key_exists( $list_id, $sendy_lists ) ) {
			unset( $sendy_lists[$list_id] );
			update_option( 'sendy_lists', $sendy_lists );
		}
	}

}


function swp_ajax_form_submit() {
	parse_str( $_POST['formdata'] , $fields );
	$email = sanitize_email( $fields['swp_email'] );
	$list = $fields['listid'];

	if ( empty( $email ) ) {
		echo 'invalid-email'; die;
	}

	if ( empty( $list ) ) {
		echo 'invalid-list'; die;
	}
	// check if unsubscribe form
	if ( $fields['form_type'] == 'unsubscribe' ) {
		// Unsubscribe and return
		$result = swp_unsubscribe_user( $email, $list );
		echo $result;
		die;
	}

	// Check recaptcha
	if ( isset( $fields['g-recaptcha-response'] ) ) {
		if ( ! empty( $fields['g-recaptcha-response'] ) ) {
			$sendy_recaptcha = get_option( 'sendy_recaptcha' );
			$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $sendy_recaptcha['secret_key'] . '&response=' . sanitize_text_field( $fields['g-recaptcha-response'] );
			$resp = wp_remote_get( esc_url_raw( $url ) );
			if ( ! is_wp_error( $resp ) ) {
				$body = wp_remote_retrieve_body( $resp );
				$response = json_decode( $body );
				if ( $response->success === false ) {
					if ( ! empty( $response->{'error-codes'} ) && $response->{'error-codes'} != 'missing-input-response' ) {
						$error = __( 'invalid-site-key', 'ninja-forms' );
					}else {
						$error = __( 'invalid-captcha', 'ninja-forms' );
					}
					echo 'invalid-captcha'; die;
				}else {

				}
			}

		}else {
			echo 'invalid-captcha'; die;
		}
	}
	if ( ! is_array( $list ) ) {
		$listid[] = $list;
	}else {
		$listid = $list;
	}

	$listids = apply_filters( 'swp-forms-subscription-list', $listid );

	$name = ! empty( $fields['swp_name'] )?sanitize_text_field( $fields['swp_name'] ):'' ;
	$custom_fields = array();
	// check for custom fields
	$extra_fields = ! empty( $fields['swp_custom'] )?$fields['swp_custom']:'';
	if ( ! empty( $extra_fields ) && is_array( $extra_fields ) ) {
		foreach ( $extra_fields as $key => $value ) {
			$custom_fields[$key] = $value;
		}
	}

	$form_id = $fields['form_id'];
	$form_settings = get_post_meta( $form_id, 'swp_styler_settings', true );
	if ( ! empty( $form_settings['gdpr'] ) ) {
		$custom_fields['gdpr'] = 'true';
	}
	if ( ! empty( $form_settings['page_referrer'] ) ) {
		$custom_fields['referrer'] =  isset( $_SERVER['HTTP_REFERER'] )? $_SERVER['HTTP_REFERER']: '' ;
	}
	if ( ! empty( $form_settings['ip_address'] ) ) {
		$custom_fields['ipaddress'] = swp_forms_get_ip();
	}

	$status = add_user_to_sendy( $name, $email, $listids, $custom_fields );

	echo $status;
	die;

}

add_action( 'wp_ajax_swp_form_submit', 'swp_ajax_form_submit' );
add_action( 'wp_ajax_nopriv_swp_form_submit', 'swp_ajax_form_submit' );



function swp_unsubscribe_user( $email, $list ) {
	if ( ! is_array( $list ) ) {
		$listids[] = $list;
	}else {
		$listids = $list;
	}
	$result = '';
	$sendy_url = rtrim( get_option( 'sendy_url' ), '/' ) . '/unsubscribe';

	foreach ( $listids as $list_id ) {

		$response = wp_remote_post( $sendy_url, array( 'body' => array(  'email' => $email, 'list' => $list_id, 'boolean' => 'true' ) ) );

		if ( is_wp_error( $response ) ) {

			$result = $response->get_error_message();

		} else {

			$result = $response['body'];
		}
		// code...
	}

	return $result;

}

/**
 * Get User IP
 *
 * Returns the IP address of the current visitor
 *
 * @since 1.1
 * @return string $ip User's IP address
 */
function swp_forms_get_ip() {
	$ip = '127.0.0.1';
	if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
		//check ip from share internet
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
		//to check ip is pass from proxy
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return apply_filters( 'swp_forms_get_ip', $ip );
}
