/* Notes:
 * data-discount - total applied discounts value
 * data-price-with-extras - total price including extras
*/

Hooks.add_action( 'wpj_after_page_load_without_refresh', wpj_dsct_init_scripts );
function wpj_dsct_init_scripts() {
	// Applied discounts array
	var discounts = [];
	if ( jQuery( '.js-all-applied-codes' )[0] && jQuery( '.js-all-applied-codes' ).val() ) {
		discounts = discounts.concat( jQuery( '.js-all-applied-codes' ).val().split( "," ) ); // list of applied coupons on single job page
	}

	// Send total coupons value from single job page to checkout page
	if ( jQuery( '.js-total-discounts-value' )[0] ) {
		jQuery( '.total' ).each( function() { jQuery( this ).attr( 'data-discount', jQuery( '.js-total-discounts-value' ).val() ); });
	}

	// Update price on buy button
	if ( jQuery( '.page-id-' + wpj_vars.checkout_page_id )[0] && ! jQuery( 'input[name="custom_extra"]' )[0] && ! jQuery( 'input[name="tips"]' )[0] ) {
		if ( typeof wpj_update_purchase_price === 'function' ) wpj_update_purchase_price( 'job_purchase' );
	}

	// Change seller discount value label
	if ( jQuery( '.js-discount-type' )[0] ) {
		jQuery( '.js-discount-type' ).dropdown({
			onChange: function ( val ) {
				if ( val == 'fixed' ) {
					jQuery( '.js-percent' ).hide();
					jQuery( '.js-fixed' ).show();

				} else {
					jQuery( '.js-percent' ).show();
					jQuery( '.js-fixed' ).hide();

				}
			}
		});
	}

	// Show delete button
	if ( getUrlParameter( 'discount' ) && getUrlParameter( 'action' ) == 'edit' ) {
		jQuery( '.delete-coupon-button' ).css( 'display', 'flex' );
		jQuery( '.js-delete-coupon' ).attr( 'data-code', getUrlParameter( 'discount' ) );
		jQuery( '.js-create-new-coupon-label' ).text( wpj_vars.lbl_edit_coupon_details );
	}
}

jQuery( document ).ready( function( $ ) {

	// Applied discounts array
	var discounts = [];
	if ( $( '.js-all-applied-codes' )[0] && $( '.js-all-applied-codes' ).val() )
		discounts = discounts.concat( $( '.js-all-applied-codes' ).val().split( "," ) ); // list of applied coupons on single job page

	// Copy the code from sidebar input to order additional input and vice versa
	$( document ).on( 'keyup change paste', '.discount-code', function( e ) {
		$( '.discount-code' ).val( $( this ).val() )
	});

	$( document ).on( 'click', '#apply_discount', function( e ) {
		e.preventDefault();

		// Get the discount code entered
		var discount_code = $( this ).siblings( '.discount-code' ).val().trim();

		// ERROR - coupon already applied
		if ( discounts.includes( discount_code ) == true ) {
			$( '.discount_status' ).addClass( 'negative' ).removeClass( 'success' );
			$( '.discount_status' ).html( '<i class="exclamation circle icon"></i>' + wpj_vars.lbl_coupon_already_applied ).show();
			return false;
		}

		// Make a list with current inserted coupons
		// to avoid inseration of same coupon multiple times
		if ( discount_code ) discounts.push( discount_code );

		// Add a loader while PHP send the response
		$( '.ui.input.discount-inp' ).addClass( 'left icon loading disabled' );
		$( '.ui.input.discount-inp' ).append( '<i class="search icon"></i>' )

		$.ajax({
			type: "POST",
			url : wpj_vars.ajaxurl,
			data: {
				action       : 'apply_discount_code_action',
				discount_code: discount_code,
				pid          : $( '.js-dsct-pid' ).val(),
				pck_value    : $( '.package_price' ).val()
			},
			success: function( data ) {
				// Remove loader
				$( '.ui.input.discount-inp' ).removeClass( 'left icon loading disabled' );
				$( '.ui.input.discount-inp' ).find( 'i' ).remove();

				// Parse data received from PHP
				obj = JSON.parse( data );

				// Show the positive or negative message
				if ( obj['messages']['ok'] == true ) {
					$( '.discount_status' ).addClass( 'success' );
					$( '.discount_status' ).removeClass( 'negative' );
					var icon = '<i class="check circle icon"></i>';

				} else {
					$( '.discount_status' ).addClass( 'negative' );
					$( '.discount_status' ).removeClass( 'success' );
					var icon = '<i class="exclamation circle icon"></i>';

					// Remove discount code from current inserted array if the code is not valid
					var index = discounts.indexOf( discount_code );
					if ( index > -1 ) discounts.splice( index, 1 );

				}

				$( '.discount_status' ).each( function() {
					$( this ).html( icon + obj['messages']['content'] ).show();
				});

				// Execute if the code is valid
				if ( obj['messages']['ok'] == true ) {

					// ERROR - coupon discount is bigger than job price
					if ( wpj_vars.admin_discounts_to_seller_earnings != 'yes' && obj['results']['creator'] != 1 )
						price_total = wpj_dsct_calculate_fee( parseFloat( $( '.total' ).attr( 'data-price-with-extras' ) ) );
					else
						price_total = parseFloat( $( '.total' ).attr( 'data-price-with-extras' ) );

					discount = wpj_dsct_get_discount_by_price( obj );

					if ( price_total < ( parseFloat( discount ) + parseFloat( $( '.total' ).attr( 'data-discount' ) ) ) ) {
						$( '.discount_status' ).addClass( 'negative' ).removeClass( 'success' );
						$( '.discount_status' ).html( '<i class="exclamation circle icon"></i>' + wpj_vars.lbl_total_discount_greater_than_amount ).show();

						// Remove code from list of applied coupons
						discounts = $.grep( discounts, function( value ) {
							return value != discount_code;
						});

						return false;
					}

					// Insert the coupon
					var discount = 0;
					$( '.total' ).each( function() {
						// Vars
						var $total    = $( this );
						var symbol    = $total.data( 'symbol' )   || $total.data( 'cur' );
						var position  = $total.data( 'position' ) || '';
						var space     = $total.data( 'space' )    || 'yes';
						var space_str = ""; if ( space == "yes" ) space_str = " ";

						// Discount value
						discount = wpj_dsct_get_discount_by_price( obj );

						// Discount value formatted
						var formatted_price = wpj_dsct_number_to_price( $total, discount );

						// Insert coupon details in checkout list
						if ( ! $( '.coupon-' + discount_code ).length ) {
							var before_class = $( '.js-shipping' )[0] ? '.js-shipping' : '';
							if ( ! before_class ) { before_class = $( '.js-processingfees' )[0] ? '.js-processingfees' : ''; }
							if ( ! before_class ) { before_class = $( '.js-processingtax' )[0] ? '.js-processingtax' : ''; }
							if ( ! before_class ) { before_class = '.apply-dicounts-wrapper'; }

							var wrapper_class1 = '<div class="js-discount">';
							var wrapper_class2 = '<div class="js-discount single-job-sidebar-price-content">';
							var discount_html_content = '\
									<div\
										data-creator="' + obj['results']['creator'] + '"\
										data-discount="' + discount + '"\
										data-type="' + obj['results']['type'] + '"\
										data-value="' + obj['results']['price'] + '"\
										data-min-amount="' + obj['results']['minimum_amount'] + '"\
										class="item coupon-' + discount_code + '"\
									>\
										\
										<div class="price-label"><i class="remove-discount close icon"></i>' + ( wpj_vars.lbl_coupon + ': ' + discount_code ) + '</div>\
										\
										<div class="price-value">\
											\
											<span class="coupon-amount extra-price-inside">\
											\
												' + ( position == "front" ? ( symbol + space_str + "-" + formatted_price ) : ( "-" + formatted_price + space_str + symbol ) ) + '\
											\
											</span>\
											\
										</div>\
										\
									</div>\
									\
									<input class="discount-value" type="hidden" name="discount_value[]" value="' + discount_code + '/' + discount + '" />\
								</div>\
							';

							// Insert to order details
							$( '<div class="ui divider"></div>' + wrapper_class1 + discount_html_content ).insertBefore( $( before_class ).prev( '.ui.divider' ) );

							// Insert to sidebar
							$( wrapper_class2 + discount_html_content ).insertBefore( $( '.order-additional-sidebar-wrapper' ).find( before_class ) );

							if ( $( 'input[name="discount"]' )[0] ) {
								$( 'input[name="discount"]' ).val( ( parseFloat( $( 'input[name="discount"]' ).val() ) + parseFloat( discount ) ) );
							} else {
								$( '<input name="discount" type="hidden" value="' + discount + '" />' ).insertAfter( 'input[name="purchaseformvalidation"]' );
							}

							if ( $( 'input[name="coupons"]' )[0] ) {
								$( 'input[name="coupons"]' ).val( $( 'input[name="coupons"]' ).val() + '_' +  discount_code );
							} else {
								$( '<input name="coupons" type="hidden" value="' + discount_code + '" />' ).insertAfter( 'input[name="purchaseformvalidation"]' );
							}
						}
					});

					// Empty the input for discount code
					$( '.discount-code' ).val( '' );

					// Send discount as a data for buy button to checkout page
					var total_discount_values = parseFloat( $( '.total' ).attr( 'data-discount' ) );
					if ( ! total_discount_values ) total_discount_values = 0;
					$( '.total' ).attr( 'data-discount', ( total_discount_values + discount ) );

					// Update price on buy button
					if ( typeof wpj_update_purchase_price === 'function' ) wpj_update_purchase_price( 'job_purchase' );
				}

				// Insert job max total price(extra + extra fast + additional revision) - used for packages
				$( '<input type="hidden" class="job-total-price" value="' + parseFloat( obj['job_price'] ) + '" />' ).insertAfter( '.apply-dicounts-wrapper' );
			}
		});
	});

	// Remove discount
	$( document ).on( 'click', '.remove-discount', function( e ) {
		e.preventDefault();

		// Get discount code and value
		var discount_arr   = $( this ).parents( '.js-discount' ).find( '.discount-value' ).val().split( '/' );
		var discount_code  = discount_arr[0].trim();
		var discount_value = discount_arr[1].trim();

		// Send discount as a data for buy button to checkout page
		if ( $( '.total' ).attr( 'data-discount' ) ) {
			if ( discount_value > 0 ) discount_value = parseFloat( $( '.total' ).attr( 'data-discount' ) ) - discount_value;
		}

		if ( discount_value <= 0 ) discount_value = 0;

		// Update total discount value in total button
		$( '.total' ).attr( 'data-discount', discount_value );

		// Update price on buy button
		if ( typeof wpj_update_purchase_price === 'function' ) wpj_update_purchase_price( 'job_purchase' );

		// Remove code from list of applied coupons
		discounts = $.grep( discounts, function( value ) {
			return value != discount_code;
		});

		// Remove code from input
		var all_order_coupons = $( 'input[name="coupons"]' ).val();
		if ( all_order_coupons.includes( discount_code + "_" ) ) $( 'input[name="coupons"]' ).val( all_order_coupons.replace( discount_code + "_", "" ) );
		else if ( all_order_coupons.includes( "_" + discount_code ) ) $( 'input[name="coupons"]' ).val( all_order_coupons.replace( "_" + discount_code, "" ) );
		else $( 'input[name="coupons"]' ).remove();

		// Clear the status message
		$( '.discount_status' ).html( '' ).hide();

		// Remove from front-end
		$( '.coupon-' + discount_code ).parent( '.js-discount' ).prev( '.ui.divider' ).remove();
		$( '.coupon-' + discount_code ).parent( '.js-discount' ).remove();
	});

	// Check/Uncheck Extra & Change package price
	$( document ).on( 'click', '.extra-item, .pck-order, .amount_add, .amount_rmv', function( e ) {
		if ( discounts ) {
			var total_discount_values = 0;
			discounts.forEach( function( coupon_code ) {
				if ( $( '.coupon-' + coupon_code ).length ) {
					var coupons_type    = $( '.coupon-' + coupon_code ).attr( "data-type" );
					var coupons_value   = $( '.coupon-' + coupon_code ).attr( "data-value" );
					var coupons_creator = $( '.coupon-' + coupon_code ).attr( "data-creator" );

					var $total          = $( '.total' );
					var symbol          = $total.data( 'symbol' )   || $total.data( 'cur' );
					var position        = $total.data( 'position' ) || '';
					var space           = $total.data( 'space' )    || 'yes';
					var space_str       = space == "yes" ? " " : "";

					// Discount value
					obj = { "price" : coupons_value, "results" : { "type" : coupons_type, "price" : coupons_value, "creator" : coupons_creator } }
					var discount = wpj_dsct_get_discount_by_price( obj );
					total_discount_values += discount;

					// Update coupon details in checkout list
					var formatted_price = wpj_dsct_number_to_price( $total, discount );
					if ( position == "front" )
						$( '.coupon-' + coupon_code ).find( '.coupon-amount' ).html( symbol + space_str + '-' + formatted_price );
					else
						$( '.coupon-' + coupon_code ).find( '.coupon-amount' ).html( '-' + formatted_price + space_str + symbol );

					$( '.coupon-' + coupon_code ).next( '.discount-value' ).val( coupon_code + '/' + discount );

					// Remove discount if admin fee is greater than applied discount value
					if ( wpj_vars.admin_discounts_to_seller_earnings != 'yes' && obj['results']['creator'] != 1 )
						price_total = wpj_dsct_calculate_fee( parseFloat( $( '.total' ).attr( 'data-price-with-extras' ) ) );
					else
						price_total = parseFloat( $( '.total' ).attr( 'data-price-with-extras' ) );


					if ( price_total < parseFloat( $( '.total' ).attr( 'data-discount' ) ) ) $( '.coupon-' + coupon_code ).find( '.remove-discount' ).trigger( 'click' );
				}
			});

			// Send discount as a data for buy button to checkout page
			$( '.total' ).attr( 'data-discount', ( total_discount_values ) );

			// Update price on buy button
			if ( typeof wpj_update_purchase_price === 'function' ) wpj_update_purchase_price( 'job_purchase' );
		}
	});

	// Remove discount if selected package is lower than minimum amount
	$( document ).on( 'click', '.pck-order', function( e ) {
		if ( discounts ) {
			discounts.forEach( function( coupon_code ) {
				if ( $( '.coupon-' + coupon_code ).length ) {
					var coupon_min_amount = $( '.coupon-' + coupon_code ).attr( 'data-min-amount' );
					var job_total_price = parseFloat( $( '.job-total-price' ).val() ) + parseFloat( $( '.package_price' ).val() );

					if ( job_total_price && coupon_min_amount != 0 ) {
						if ( job_total_price < coupon_min_amount ) {
							$( '.coupon-' + coupon_code ).find( '.remove-discount' ).trigger( 'click' );
						}
					}
				}
			});

			// Update price on buy button
			if ( typeof wpj_update_purchase_price === 'function' ) wpj_update_purchase_price( 'job_purchase' );
		}
	});

	// Save coupon
	$( document ).on( 'click', '.js-save-coupon', function( e ) {
		e.preventDefault();

		var $this     = $( this );
		var this_form = $( this ).parents( '.ui.form' );

		$.ajax({
			type : "POST",
			url  : wpj_vars.ajaxurl,
			data : "action=save_coupon_action&" + this_form.serialize() + "&action_type=" + getUrlParameter( 'action' ) + "&discount=" + getUrlParameter( 'discount' ),
			beforeSend: function() {
				$this.addClass( 'ui button loading' );
			},
			success: function( response ) {
				// Display message
				if ( response ) {
					$( '.js-save-coupon' ).notify( response, { position: 'top', className: 'error' } );

				} else {
					$( '.js-save-coupon' ).notify( wpj_vars.lvl_saved_lbl, { position: 'top', className: 'success' } );

					// Reset the form
					this_form.form( 'clear' );

					// Refresh div content
					if ( $( '.discounts-wrapper' )[0] ) refreshContent( '.discounts-wrapper' ); // for code
					else if ( $( '.kt-tabs-content-wrap' )[0] ) refreshContent( '.kt-tabs-content-wrap' ); // for page builder

					// Change tab
					history.pushState( null, null, wpj_vars.parent_url + 'active-coupons' ); // change url
					wpj_change_kadence_active_tab( 'active-coupons' ); // for page builder

					if ( $( '.ui.secondary.menu' )[0] ) $( '.ui.secondary.menu' ).find( '.item' ).tab( 'change tab', 'active-coupons' ); // for code
					$( '.js-tab-to-dropdown' ).find( '.ui.dropdown' ).dropdown( 'set selected', 'active-coupons' ); // for code - mobile

					jQuery.fn.wpjSemanticInit();
				}
			},
			complete: function() {
				$this.removeClass( 'ui button loading' );
			}
		});
	});

	// Delete coupon
	$( document ).on( 'click', '.js-delete-coupon', function( e ) {
		e.preventDefault();

		var $this = $( this );

		$.ajax({
			type : "POST",
			url  : wpj_vars.ajaxurl,
			data : {
				action  : 'delete_coupon_action',
				discount: $( this ).attr( 'data-code' )
			},
			beforeSend: function() {
				$this.addClass( 'ui button loading' );
			},
			success: function( response ) {
				$this.notify( response, { position: 'right', className: 'success' } );

				if ( $( '.discounts-wrapper' )[0] ) refreshContent( '.discounts-wrapper' ); // for code
				else if ( $( '.kt-tabs-content-wrap' )[0] ) refreshContent( '.kt-tabs-content-wrap' ); // for page builder
			},
			complete: function() {
				$this.removeClass( 'ui button loading' );
			}
		});
	});

	// Reset form when click New coupon tab
	$( document ).on( 'click', 'a[aria-controls="new-coupon"]', function( e ) {
		if ( e.originalEvent !== undefined ) { // if is not triggered
			wpj_dsct_add_form_to_discounts_page();
			$( '#post-new-coupon' ).form( 'clear' );
			$( '.delete-coupon-button' ).css( 'display', 'none' );
			$( '.js-create-new-coupon-label' ).text( wpj_vars.lbl_create_new_coupon );

			// Change seller discount value label
			if ( $( '.js-discount-type' )[0] ) {
				$( '.js-discount-type' ).dropdown({
					onChange: function ( val ) {
						if ( val == 'fixed' ) {
							$( '.js-percent' ).hide();
							$( '.js-fixed' ).show();

						} else {
							$( '.js-percent' ).show();
							$( '.js-fixed' ).hide();

						}
					}
				});
			}

			history.pushState( null, null, wpj_vars.page_url );
		}
	});

});

Hooks.add_filter( 'wpj_checkout_total_price_filter', wpj_dsct_update_price_after_discount, 2 );
function wpj_dsct_update_price_after_discount( total, total_elem ) {
	var discount_amount = 0;

	if ( total_elem.attr( 'data-discount' ) )
		var discount_amount = total_elem.attr( 'data-discount' ) || 0;

	total = total - discount_amount;

	return total;
}

function wpj_dsct_calculate_fee( raw_amount ) {
	var amount_fee    = 0;
	var percent_taken = 0;

	if ( wpj_vars.subscription_enabled == 'yes' && wpj_vars.subscription_fees_enabled == 'yes' ) {

		if ( wpj_vars.subscription_fee && isNumeric( wpj_vars.subscription_fee ) ) {
			percent_taken = wpj_vars.subscription_fee;
		} else {
			percent_taken = 0;
		}

		amount_fee = ( percent_taken * raw_amount ) / 100;

	} else {

		if ( wpj_vars.enable_site_fee == 'percent' ) {
			// percent
			if ( ! isNumeric( wpj_vars.percent_fee_taken ) ) {
				wpj_vars.percent_fee_taken = 0;
			}

			amount_fee = ( wpj_vars.percent_fee_taken * raw_amount ) / 100;

		} else if ( wpj_vars.enable_site_fee == 'fixed' ) {
			// fixed
			if ( isNumeric( wpj_vars.solid_fee_taken ) ) {
				amount_fee = wpj_vars.solid_fee_taken;
			} else {
				amount_fee = 0;
			}

		} else if ( wpj_vars.enable_site_fee == 'flexible' ) {
			// flexible
			if ( wpj_vars.uid != 0 ) {
				jQuery.ajax({
					type : "POST",
					async: false,
					url  : wpj_vars.ajaxurl,
					data : {
						action: 'calculate_site_fee_action',
						price: raw_amount,
						pid: jQuery( document ).find( '[data-pid]' ).first().attr( 'data-pid' )
					},
					success: function( data ) {
						if ( data ) percent_taken = data;
					}
				});

			} else {
				percent_taken = 0;
			}

			amount_fee = ( percent_taken * raw_amount ) / 100;
		}
	}

	return Math.round( amount_fee * 100 ) / 100;
}

function wpj_dsct_number_to_price( $total, number_to_format ) {
	var decimal        = $total.data( "decimal" ) || '.';
	var thousands      = $total.data( "thousands" ) || ',';
	var decimaldisplay = $total.data( "decimaldisplay" ) || 'default';

	var formatted_price = String( number_to_format.formatMoney( 2, decimal, thousands ) );

	if ( decimaldisplay == "ifneeded" ) {
		if ( isInt( number_to_format ) )
			formatted_price = String( number_to_format.formatMoney( 0, decimal, thousands ) );

		else
			formatted_price = String( number_to_format.formatMoney( 2, decimal, thousands ) );

	} else if ( decimaldisplay == "never" )
		formatted_price = String( number_to_format.formatMoney( 0, decimal, thousands ) );

	return formatted_price;
}

function wpj_dsct_get_discount_by_price( obj ) {
	// Total
	if ( wpj_vars.admin_discounts_to_seller_earnings != 'yes' && obj['results']['creator'] != 1 ) {
		price_total = wpj_dsct_calculate_fee( parseFloat( jQuery( '.total' ).attr( 'data-price-with-extras' ) ) );
	} else {
		price_total = parseFloat( jQuery( '.total' ).attr( 'data-price-with-extras' ) );
	}

	// Discount
	if ( obj['results']['type'] == 'fixed' ) {
		price    = obj['price'];
		discount = parseFloat( price );

	} else {
		price    = obj['results']['price'];
		discount = ( price * price_total ) / 100;
		discount = parseFloat( discount );

	}

	return discount;
}

Hooks.add_action( 'wpj_after_form_added_to_page_builder', wpj_dsct_add_form_to_discounts_page );
function wpj_dsct_add_form_to_discounts_page() {
	if ( jQuery( '.js-new-coupon-wrapper' )[0] && ! jQuery( '#post-new-coupon' )[0] ) {
		jQuery( '.js-new-coupon-wrapper' ).wrapAll( '<form id="post-new-coupon" class="ui form" method="POST"></form>' );
		jQuery( '.js-new-coupon-wrapper' ).find( '.wp-block-kadence-column.ui.form' ).removeClass( 'ui form' );

		jQuery.fn.wpjCalendarInit();
	}
}