<?php

$form_id     = carbon_get_post_meta( $post_id, 'qp_hubspot_form_id' );
$form_region = carbon_get_post_meta( $post_id, 'qp_hubspot_form_region' );
$form_portal = carbon_get_post_meta( $post_id, 'qp_hubspot_form_portal' );

if ( empty( $form_id ) || empty( $form_region ) || empty( $form_portal ) ) {
	return;
}

?>

<div class="qp-popup__form">
	<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/shell.js"></script>
	<script data-form-id="<?php echo esc_html( $form_id ); ?>">
		hbspt.forms.create({
			region: '<?php echo esc_html( $form_region ); ?>',
			portalId: '<?php echo esc_html( $form_portal ); ?>',
			formId: '<?php echo esc_html( $form_id ); ?>',
			onFormSubmit: function($form) {
				var formData = $form.serializeArray();
				var formId = $form.data('form-id');
				var $ajaxContainer = jQuery('[data-form-id="' + formId + '"]').closest('.qp-popup__body');

				jQuery.ajax({
					type: 'POST',
					action: 'qp_ajax_form_submission_hubspot',
					data: {
						action: 'qp_ajax_form_submission_hubspot',
						form_data: formData
					},
					url: '<?php echo admin_url( 'admin-ajax.php' ) ?>',
					beforeSend: function() {
						$ajaxContainer.find('.qp-popup__form').hide();
						$ajaxContainer.addClass('is-loading').append('<i class="qp-ico-loading"></i>')
					},
					success: function(result) {
						console.log(result)
						$ajaxContainer.find('.qp-popup__form').remove();
						$ajaxContainer.removeClass('is-loading').find('.qp-ico-loading').remove();
						$ajaxContainer.closest('.qp-popup').addClass('is-submitted');

					},
					error: function(jqXHR, textStatus, errorThrown) {
						alert('An unexpected error occurred, please try reloading the page.');
					}
				});
		    }
		});
	</script>
</div><!-- /.qp-popup__form -->