<?php
function get_amendment_process_bonus_discount(){
    $html = "";
	global $wpdb;
	ob_start();
	$total_step = 5;
	?>
    <div class="container-fluid">
	    <div class="row justify-content-center">
			<div class="col-10 col-sm-9 col-md-7 col-lg-10 col-xl-10 text-center p-0 mt-3 mb-2">
				<div class="card px-0 pt-4 pb-0 mt-3 mb-3">
					<form name="amendment_process_bonus_discount" class="amendment_process_bonus_discount" id="msform">
					<!-- progressbar -->
					<ul id="progressbar">
	                        <li class="active" id="fieldmapping"><strong><?php _e('Step 1',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="fieldmapping"><strong><?php _e('Step 2',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="fieldmapping"><strong><?php _e('Step 3',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="fieldmapping"><strong><?php _e('Step 4',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="fieldmapping"><strong><?php _e('Step 5',CIP_TXTDOMAIN) ?></strong></li>
	                    </ul>
	                    <div class="progress">
	                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
	                    </div> <br> <!-- fieldsets -->
	                    <fieldset class="step_0">
	                        <div class="form-card">
	                            <div class="row">
	                                <div class="col-12">
	                                    <h2 class="steps"><?php echo sprintf('Step %s - %s', 1, $total_step); ?></h2>
	                                </div>
	                            </div>
	                            <div class="row">
                                    <div class="col-md-4">
                                        <label class="fieldlabels" for="email_or_username"><?php _e('Enter email or username',CIP_TXTDOMAIN); ?></label>
                                        <input class="form-control" type="text" name="email_or_username" id="email_or_username" required />
                                    </div>
                                    <div class="col-md-4">
                                        <label class="fieldlabels" for="redemption_date"><?php _e('Select redemption date',CIP_TXTDOMAIN); ?></label>
                                        <input class="form-control" type="text" name="redemption_date" id="redemption_date" placeholder="dd/mm/yyyy" required />
                                    </div>
									<div class="col-md-4">
                                        <label class="fieldlabels" for="reference"><?php _e('Reference',CIP_TXTDOMAIN); ?></label>
                                        <input class="form-control" type="text" name="reference" id="reference" />
                                    </div>
                                </div>
	                        </div>
	                        <input type="button" name="next" class="next action-button" value="Next" />
	                    </fieldset>
	                    
						<fieldset class="step_1">
							<div class="form-card">
								<div class="row">
									<div class="col-12">
										<h2 class="steps"><?php echo sprintf('Step %s - %s', 2, $total_step); ?></h2>
									</div>
								</div>
								<div class="row justify-content-center">
									<div class="col-12 text-center amendment_process_section_table" style="display:none;"></div>
								</div>
							</div>
							<input type="button" name="next" class="next action-button" value="Next" />
							<input type="button" name="previous" class="previous action-button-previous" value="Previous" />
						</fieldset>
	                    <fieldset class="step_2">
	                        <div class="form-card">
	                            <div class="row">
	                                <div class="col-12">
	                                    <h2 class="steps"><?php echo sprintf('Step %s - %s', 3, $total_step); ?></h2>
	                                </div>
	                            </div>
								<div class="row justify-content-center">
									<div class="col-12 amendment_process_adjust_bonus_discount_section" style="display:none;"></div>
								</div>
	                        	
	                        </div>
							<input type="button" name="next" class="next action-button" value="Next" />
							<input type="button" name="previous" class="previous action-button-previous" value="Previous" />
	                    </fieldset>
						<fieldset class="step_3">
	                        <div class="form-card">
	                            <div class="row">
	                                <div class="col-12">
	                                    <h2 class="steps"><?php echo sprintf('Step %s - %s', 4, $total_step); ?></h2>
	                                </div>
	                            </div>
								<div class="row justify-content-center">
									<div class="col-12 text-center amendment_process_review_section_table" style="display:none;"></div>
								</div>
	                        </div>
							<input type="button" name="next" class="next action-button" value="Confirm" />
							<input type="button" name="previous" class="previous action-button-previous" value="Previous" />
	                    </fieldset>
						<fieldset class="step_4">
	                        <div class="form-card">
	                            <div class="row">
	                                <div class="col-12">
	                                    <h2 class="steps"><?php echo sprintf('Step %s - %s', 5, $total_step); ?></h2>
	                                </div>
	                            </div>
	                            <div class="row">
									<div class="col-md-12 otp_section pb-3">
										<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
										<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
										<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
									</div>
								</div>
								<div class="row justify-content-center amendment_process_final_response" style="display: none;"></div>
	                        </div>
							<input type="button" name="next" class="next action-button" value="Complete" />
							<input type="button" name="previous" class="previous action-button-previous" value="Previous" />
	                    </fieldset>
	                    <input type="hidden" name="action" value="cip_amendment_process_bonus_discount_act" />
	                    <input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPxYSMNewDeliveryPlanWizardMSYxCIP_'); ?>" />
	                </form>
				</div>
			</div>
		</div>
    </div>
    <?php
	$html .= ob_get_clean();
	return $html;
}
add_action( 'wp_footer', 'scripts_amendment_process_bonus_discount_callback' );
function scripts_amendment_process_bonus_discount_callback(){
    ?>
    <script>
    jQuery(document).ready(function($){
        var inputmask_options = {
			inputFormat:'dd/mm/yyyy',
			alias: "datetime",
			placeholder: "dd/mm/yyyy",
		};
        var notifyErrorOpt = {position:"bottom",className: 'error',autoHide:true,autoHideDelay: 4000,clickToHide: true};
        if( $('.amendment_process_bonus_discount #redemption_date').length > 0 ){		
            $('.amendment_process_bonus_discount #redemption_date').inputmask(inputmask_options);
            $('.amendment_process_bonus_discount #redemption_date').datepicker({
                format: "dd/mm/yyyy",
                endDate: "today",
                autoclose: true,
                clearBtn: true,
            }).on('hide', function(e) {
            });
        }

        var block_config_amendment = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

		var current_fs_amendment, next_fs_amendment, previous_fs_amendment; //fieldsets
		var opacity_amendment;
		var current_amendment = 1;
		var steps_amendment = $(".amendment_process_bonus_discount fieldset").length;
		var $form_amendment = $('.amendment_process_bonus_discount'); 
		var csr_spinner = $('.csr_spinner');
		var csr_split_spinner = $('.csr_split_spinner');
		var process_log = document.getElementById('process_log');
		var process_split_log = document.getElementById('process_split_log');
		var splited = false;
		var isError = true;
		var lastMsg = "";
		var lastMsg_total = "";
		setProgressBarAmendment(current_amendment);

        $(".amendment_process_bonus_discount .next").click(function(){
            var this_next = $(this);
			current_fs_amendment = $(this).closest('fieldset');
			next_fs_amendment = $(this).closest('fieldset').next();

			if( current_amendment == 1 ){
				var email_or_username = $('.amendment_process_bonus_discount input[name="email_or_username"]').val();
				var redemption_date = $('.amendment_process_bonus_discount input[name="redemption_date"]').val();
				if( email_or_username == "" ){
					$('.amendment_process_bonus_discount input[name="email_or_username"]').notify( 'Email or username is required', notifyErrorOpt );
					return false;
				}
				if( redemption_date == "" ){
					$('.amendment_process_bonus_discount input[name="redemption_date"]').notify( 'Redemption date is required', notifyErrorOpt );
					return false;
				}

				$('body').find('.amendment_process_section_table').html('').hide();

				$form = $(this).closest('fieldset');
				$form.block( block_config_amendment );
				var data = $('.amendment_process_bonus_discount').serialize();
				data = data + '&step=step_1';
				$.post(cipscript.ajax_url, data, async function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						$('body').find('.amendment_process_section_table').html( obj.html ).show();

						if( $('body').find('[data-toggle="tooltip"]').length > 0 ){
							$('[data-toggle="tooltip"]').tooltip();
						}

						$(".amendment_process_bonus_discount #progressbar li").eq( $("fieldset").index(next_fs_amendment) ).addClass("active");
						next_fs_amendment.show();
						current_fs_amendment.animate({opacity_amendment: 0}, {
							step: function(now) {
								opacity_amendment = 1 - now;
			
								current_fs_amendment.css({
									'display': 'none',
									'position': 'relative'
								});
								next_fs_amendment.css({'opacity': opacity_amendment});
							},
							duration: 500
						});
						setProgressBarAmendment(++current_amendment);

					}else{
						swalToast({ type: 'error', title: obj.msg });
						$form.unblock();
						return false;
					}
					$form.unblock();
				});

			}else if( current_amendment == 2 ){


				$('body').find('.amendment_process_adjust_bonus_discount_section').html('').hide();
				
				$form = $(this).closest('fieldset');
				$form.block( block_config_amendment );
				var data = $('.amendment_process_bonus_discount').serialize();
				data = data + '&step=step_2';
				$.post(cipscript.ajax_url, data, async function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						$('body').find('.amendment_process_adjust_bonus_discount_section').html( obj.html ).show();

						$(".amendment_process_bonus_discount #progressbar li").eq( $("fieldset").index(next_fs_amendment) ).addClass("active");
						next_fs_amendment.show();
						current_fs_amendment.animate({opacity_amendment: 0}, {
							step: function(now) {
								opacity_amendment = 1 - now;
			
								current_fs_amendment.css({
									'display': 'none',
									'position': 'relative'
								});
								next_fs_amendment.css({'opacity': opacity_amendment});
							},
							duration: 500
						});
						setProgressBarAmendment(++current_amendment);

					}else{
						swalToast({ type: 'error', title: obj.msg });
						$form.unblock();
						return false;
					}
					$form.unblock();
				});

			}else if( current_amendment == 3 ){

				var promotionType = $('.amendment_process_bonus_discount').find('input[name="promotionType"]').val();
				if( promotionType == 'discount' ){
					var promotion_discount = $('.amendment_process_bonus_discount input[name="promotion_discount"]').val();
					var promotion_csr_price = $('.amendment_process_bonus_discount input[name="promotion_csr_price"]').val();

					if( promotion_discount == "" ){
						$('.amendment_process_bonus_discount input[name="promotion_discount"]').notify( 'Discount is required', notifyErrorOpt );
						return false;
					}
					if( !jQuery.isNumeric( promotion_discount )  ){
						$('.amendment_process_bonus_discount input[name="promotion_discount"]').notify( 'Please enter valid Discount', notifyErrorOpt );
						return false;
					}
					if( promotion_discount != "" && parseInt( promotion_discount ) < 1 ){
						$('.amendment_process_bonus_discount input[name="promotion_discount"]').notify( 'Minimum Discount Percentage is 1', notifyErrorOpt );
						return false;
					}
					if( promotion_discount != "" && parseInt( promotion_discount ) > 99 ){
						$('.amendment_process_bonus_discount input[name="promotion_discount"]').notify( 'Maximum Discount Percentage is 99', notifyErrorOpt );
						return false;
					}

					if( promotion_csr_price == "" ){
						$('.amendment_process_bonus_discount input[name="promotion_csr_price"]').notify( 'CSR price is required', notifyErrorOpt );
						return false;
					}
				}else if( promotionType == 'bonus' ){
					var promotion_bonus = $('.amendment_process_bonus_discount input[name="promotion_bonus"]').val();

					if( promotion_bonus == "" ){
						$('.amendment_process_bonus_discount input[name="promotion_bonus"]').notify( 'Bonus is required', notifyErrorOpt );
						return false;
					}
					if( !jQuery.isNumeric( promotion_bonus )  ){
						$('.amendment_process_bonus_discount input[name="promotion_bonus"]').notify( 'Please enter valid Bonus', notifyErrorOpt );
						return false;
					}
					if( promotion_bonus != "" && parseInt( promotion_bonus ) < 1 ){
						$('.amendment_process_bonus_discount input[name="promotion_bonus"]').notify( 'Minimum Bonus Percentage is 1', notifyErrorOpt );
						return false;
					}
				}else{
					$('.amendment_process_bonus_discount').notify( 'Bonus or Discount not found', notifyErrorOpt );
					return false;
				}

				$('body').find('.amendment_process_review_section_table').html('').hide();

				$form = $(this).closest('fieldset');
				$form.block( block_config_amendment );
				var data = $('.amendment_process_bonus_discount').serialize();
				data = data + '&step=step_3';
				$.post(cipscript.ajax_url, data, async function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						$('body').find('.amendment_process_review_section_table').html( obj.html ).show();

						$(".amendment_process_bonus_discount #progressbar li").eq( $("fieldset").index(next_fs_amendment) ).addClass("active");
						next_fs_amendment.show();
						current_fs_amendment.animate({opacity_amendment: 0}, {
							step: function(now) {
								opacity_amendment = 1 - now;
			
								current_fs_amendment.css({
									'display': 'none',
									'position': 'relative'
								});
								next_fs_amendment.css({'opacity': opacity_amendment});
							},
							duration: 500
						});
						setProgressBarAmendment(++current_amendment);

					}else{
						swalToast({ type: 'error', title: obj.msg });
						$form.unblock();
						return false;
					}
					$form.unblock();
				});

			}else if( current_amendment == 4 ){
				$(".amendment_process_bonus_discount #progressbar li").eq( $("fieldset").index(next_fs_amendment) ).addClass("active");
				next_fs_amendment.show();
				current_fs_amendment.animate({opacity_amendment: 0}, {
					step: function(now) {
						opacity_amendment = 1 - now;
	
						current_fs_amendment.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_amendment.css({'opacity': opacity_amendment});
					},
					duration: 500
				});
				setProgressBarAmendment(++current_amendment);
			}else if( current_amendment == 5 ){
				
				var user_ga_otp = $('.amendment_process_bonus_discount input[name="user_ga_otp"]').val();
				if( user_ga_otp == "" ){
					$('.amendment_process_bonus_discount input[name="user_ga_otp"]').notify( 'Please enter the authentication code', notifyErrorOpt );
					return false;
				}

				$form = $(this).closest('fieldset');
				$form.block( block_config_amendment );
				var data = $('.amendment_process_bonus_discount').serialize();
				data = data + '&step=step_5';
				$.post(cipscript.ajax_url, data, async function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						$('.otp_section').hide();
						$('.amendment_process_final_response').html( obj.html ).show();
						$('.amendment_process_final_response').closest('fieldset').find('input').prop('disabled', true).hide();

						swalToast({ type: 'success', title: obj.msg });

						setTimeout(() => {
							window.location.reload();
						}, 1000 * 20);

					}else{
						swalToast({ type: 'error', title: obj.msg });
						$form.unblock();
						return false;
					}
					$form.unblock();
				});
			}else{
				$(".amendment_process_bonus_discount #progressbar li").eq( $("fieldset").index(next_fs_amendment) ).addClass("active");
				next_fs_amendment.show();
				current_fs_amendment.animate({opacity_amendment: 0}, {
					step: function(now) {
						opacity_amendment = 1 - now;
	
						current_fs_amendment.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_amendment.css({'opacity': opacity_amendment});
					},
					duration: 500
				});
				setProgressBarAmendment(++current_amendment);
			}


        });

        $(".amendment_process_bonus_discount .previous").click(function(){

            current_fs_amendment = $(this).closest('fieldset');
            previous_fs_amendment = $(this).closest('fieldset').prev();

            $(".amendment_process_bonus_discount #progressbar li").eq($("fieldset").index(current_fs_amendment)).removeClass("active");

            previous_fs_amendment.show();

            current_fs_amendment.animate({opacity_amendment: 0}, {
                step: function(now) {
                    // for making fielset appear animation
                    opacity_amendment = 1 - now;

                    current_fs_amendment.css({
                    'display': 'none',
                    'position': 'relative'
                    });
                    previous_fs_amendment.css({'opacity': opacity_amendment});
                },
                duration: 500
            });
            setProgressBarAmendment(--current_amendment);

        });
        
        function setProgressBarAmendment(curStep){
			var percent = parseFloat(100 / steps_amendment) * curStep;
			percent = percent.toFixed();
			$(".amendment_process_bonus_discount .progress-bar").css("width",percent+"%")
		}

		$("#email_or_username").bind("input", function () {
			var c = this.selectionStart,
			r = /[^A-Za-z0-9-_.+@]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});

		$('body').on("input", "#promotion_discount, #promotion_bonus", function () {
			var c = this.selectionStart,
			r = /[^0-9]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		$('body').on("input", "#promotion_csr_price", function () {
			var c = this.selectionStart,
			r = /[^0-9.]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});

    });
    </script>
    <?php
}
add_action('wp_ajax_cip_amendment_process_bonus_discount_act','cip_amendment_process_bonus_discount_act_callback');
function cip_amendment_process_bonus_discount_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN), 'msg2' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxYSMNewDeliveryPlanWizardMSYxCIP_' ) ){
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$emailOrUsernameWhere = "";
		$email_or_username = $_POST['email_or_username'];
		$redemption_date = $_POST['redemption_date'];

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;

		if( isset( $_POST['step'] ) && $_POST['step'] == 'step_1' ){	//step 1

			if( !empty( $email_or_username ) && filter_var($email_or_username, FILTER_VALIDATE_EMAIL) ){
				$emailOrUsernameWhere = " AND `email`='". $email_or_username ."'";
			}else if( !empty( $email_or_username ) ){
				$emailOrUsernameWhere = " AND `username`='". $email_or_username ."'";
			}
			if( empty( $email_or_username ) || empty( $redemption_date ) ){
				$out = array( "error" => 1,'msg' => __('Email or username & Redemption date is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;	
			}

			$referenceQry = "";
			if( !empty( $_POST['reference'] ) ){
				$referenceQry = "AND `reference` LIKE '%-".$_POST['reference']."-%'";
			}

			$getTokenHolderResults = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND ( `text_9` = 'discount' OR `text_9` = 'bonus' ) $referenceQry");

			$getTokenHolderResultsCheckIsNotPending = $wpdb->get_var("SELECT COUNT(*) FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND ( `text_9` = 'discount' OR `text_9` = 'bonus' ) AND ( `corp_approved` != 'Pending' OR `corp_approved` IS NULL OR `corp_approved` = '' ) $referenceQry");

			if( $getTokenHolderResultsCheckIsNotPending ){
				$out = array( "error" => 1,'msg' => __('All records have not "corp_approved" is "Pending"',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$html = "";
			if( $getTokenHolderResults ){
				ob_start();
				?>
				<div class="table-responsive">
				<table>
					<tr>
						<th><?php _e('#', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Reference', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Username', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Email', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Redemption date', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Corp approved', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Bonus or Discount', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('PNP CSR amount initial', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Current CSR amount initial', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Current Amount due', CIP_TXTDOMAIN); ?></th>
					</tr>
					<?php
					$loopCounter = 1;
					$parentReferenceNumber = array();
					$promotionType = "";
					foreach( $getTokenHolderResults as $getTokenHolderResult ){
						$promotionType = $getTokenHolderResult->text_9;
						$notes_external = getTwoWordsAfterHyphen( $getTokenHolderResult->notes_external );
	
						$firstHyphenPos = strpos($getTokenHolderResult->reference, '-');
						$lastHyphenPos = strrpos($getTokenHolderResult->reference, '-');
						$parentReference = substr($getTokenHolderResult->reference, $firstHyphenPos + 1, $lastHyphenPos - $firstHyphenPos - 1);
						$parentReferenceNumber[] = $parentReference;
						$pnpReference = 'PNP-' . $parentReference;
						$getParentReferenceData = $wpdb->get_row("SELECT `csr_amount_initial` as `parentReferenceInitialAmount` FROM $tableTokenHolder WHERE `reference` LIKE '". $pnpReference ."%' ORDER BY `id` DESC LIMIT 1");
						if( !$getParentReferenceData ){
							break;
							$out = array( "error" => 1,'msg' => __('PNP records not found for reference :: '. $parentReference,CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						?>
						<tr>
							<td><?php echo $loopCounter; ?></td>
							<td class="eth_address"><a href="javascript:void(0);"><?php echo $getTokenHolderResult->reference; ?></a></td>
							<td><?php echo $getTokenHolderResult->username; ?></td>
							<td><?php echo $getTokenHolderResult->email; ?></td>
							<td><?php echo $getTokenHolderResult->redemption_date; ?></td>
							<td><?php echo $getTokenHolderResult->corp_approved; ?></td>
							<td><?php echo $notes_external; ?></td>
							<td><?php echo number_format( $getParentReferenceData->parentReferenceInitialAmount ); ?></td>
							<td><?php echo number_format( $getTokenHolderResult->csr_amount_initial ); ?></td>
							<td><?php echo number_format( $getTokenHolderResult->amount_due ); ?></td>
						</tr>
						<?php
						$loopCounter++;
					}
					?>
				</table>
				</div>
				<?php
				$parentReferenceNumber = array_unique( $parentReferenceNumber );
				if( $parentReferenceNumber ){
					foreach( $parentReferenceNumber as $parentReferenceId ){
						?><input type="hidden" name="parentReferenceNumber[]" value="<?php echo $parentReferenceId; ?>" /><?php
	
					}
				}
				?>
				<input type="hidden" name="promotionType" value="<?php echo $promotionType; ?>" />
				<input type="hidden" name="currentPromotion" value="<?php echo $notes_external; ?>" />
				<?php
				$html .= ob_get_clean();
				$out = array( "error" => 0,'msg' => 'Record fetch.', 'html' => $html );
			}else{
				$out = array( "error" => 1,'msg' => 'No records found.', 'html' => $html );
			}
		}else if( isset( $_POST['step'] ) && $_POST['step'] == 'step_2' ){	//step 2
			
			if( isset( $_POST['parentReferenceNumber'] ) && !empty( $_POST['parentReferenceNumber'] ) && ( $_POST['promotionType'] == 'discount' || $_POST['promotionType'] == 'bonus' ) ){
				$html = "";
				if( $_POST['promotionType'] == 'discount' ){
					?>
					<div class="row">
						<div class="col-md-12">
							<p><?php echo sprintf( __('Current Discount: <b>%s</b>', CIP_TXTDOMAIN), $_POST['currentPromotion'] ); ?></p>
						</div>
					</div>
					<div class="row">
						<div class="col-md-6">
							<label class="fieldlabels" for="promotion_discount"><?php _e('Enter discount',CIP_TXTDOMAIN); ?></label>
							<input class="form-control" type="text" name="promotion_discount" id="promotion_discount" required />
						</div>
						<div class="col-md-6">
							<label class="fieldlabels" for="promotion_csr_price"><?php _e('Enter CSR price',CIP_TXTDOMAIN); ?></label>
							<input class="form-control" type="text" name="promotion_csr_price" id="promotion_csr_price" required />
						</div>
					</div>
					<?php
				}else if( $_POST['promotionType'] == 'bonus' ){
					?>
					<div class="row">
						<div class="col-md-12">
							<p><?php echo sprintf( __('Current Bonus: <b>%s</b>', CIP_TXTDOMAIN), $_POST['currentPromotion'] ); ?></p>
						</div>
					</div>
					<div class="row">
						<div class="col-md-12">
							<label class="fieldlabels" for="promotion_bonus"><?php _e('Enter bonus',CIP_TXTDOMAIN); ?></label>
							<input class="form-control" type="text" name="promotion_bonus" id="promotion_bonus" required />
						</div>
					</div>
					<?php
				}
				$html .= ob_get_clean();
				$out = array( "error" => 0,'msg' => 'Adjustment process', 'html' => $html );
			}else{
				$out = array( "error" => 1,'msg' => 'Parent reference unable to find.' );
			}

		}else if( isset( $_POST['step'] ) && $_POST['step'] == 'step_3' ){	//step 3
			
			$promotion_type = $_POST['promotionType'];
			$bonus_percentage = ( isset( $_POST['promotion_bonus'] ) ) ? $_POST['promotion_bonus'] : 0;
			$discount_percentage = ( isset( $_POST['promotion_discount'] ) ) ? $_POST['promotion_discount'] : 0;
			$csr_price = ( isset( $_POST['promotion_csr_price'] ) ) ? $_POST['promotion_csr_price'] : 0;
			
			if( !empty( $email_or_username ) && filter_var($email_or_username, FILTER_VALIDATE_EMAIL) ){
				$emailOrUsernameWhere = " AND `email`='". $email_or_username ."'";
			}else if( !empty( $email_or_username ) ){
				$emailOrUsernameWhere = " AND `username`='". $email_or_username ."'";
			}
			if( empty( $email_or_username ) || empty( $redemption_date ) ){
				$out = array( "error" => 1,'msg' => __('Email or username & Redemption date is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;	
			}

			if( $promotion_type == 'bonus' ){

				$html = "";
				ob_start();
				if( is_array( $_POST['parentReferenceNumber'] ) ){
					?>
					<div class="table-responsive">
					<table>
					<tr>
						<th><?php _e('#', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Reference', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Username', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Email', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Redemption date', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Corp approved', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Bonus or Discount', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('PNP CSR amount initial', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Current CSR amount initial', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Current Amount due', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('New CSR amount initial', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('New Amount due', CIP_TXTDOMAIN); ?></th>
					</tr>
					<?php
					foreach( $_POST['parentReferenceNumber'] as $parentReferenceId ){

						$disReference = 'BNS-'.$parentReferenceId;
						
						$getAffectedRecords = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND `text_9` = 'bonus' AND `reference` LIKE '". $disReference ."%' ORDER BY `id` ASC");

						$getTokenHolderResultsCheckIsNotPending = $wpdb->get_var("SELECT COUNT(*) FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND `text_9` = 'bonus' AND ( `corp_approved` != 'Pending' OR `corp_approved` IS NULL OR `corp_approved` = '' )");
						if( $getTokenHolderResultsCheckIsNotPending ){
							?><tr><td colspan="12"><?php echo __('All records have not "corp_approved" is "Pending"',CIP_TXTDOMAIN); ?></td><?php
							$out = array( "error" => 1,'msg' => __('All records have not "corp_approved" is "Pending"',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

						$pnpReference = 'PNP-' . $parentReferenceId;
						$getParentReferenceData = $wpdb->get_row("SELECT `csr_amount_initial` as `parentReferenceInitialAmount` FROM $tableTokenHolder WHERE `reference` LIKE '". $pnpReference ."%' ORDER BY `id` DESC LIMIT 1");
						if( !$getParentReferenceData ){
							$html .= ob_get_clean();
							$html .= '<tr><td colspan="12">'. __('PNP records not found for reference :: '. $parentReferenceId,CIP_TXTDOMAIN). '</td>';
							$out = array( "error" => 1,'msg' => __('PNP records not found for reference :: '. $parentReferenceId,CIP_TXTDOMAIN), 'html' => $html );
							echo wp_json_encode( $out );
							exit;
							break;
						}

						$csr_amount_initial = $getParentReferenceData->parentReferenceInitialAmount;
						$bonus_amount = $csr_amount_initial * $bonus_percentage / 100;
						$csr_amount_initial = ceil( $bonus_amount );

						$csr_amount_pending = $csr_amount_initial;

						$loopCounter = 1;
						$promotion_number_of_deliveries = count( $getAffectedRecords );
						foreach( $getAffectedRecords as $getTokenHolderResult ){

							

							if( $promotion_number_of_deliveries <= 1 ){
								$amount_due = $csr_amount_initial;
							}else{
								
								$i = $loopCounter - 1;

								$amount_due = $csr_amount_pending / ( $promotion_number_of_deliveries - $i );
								$amount_due = ceil( $amount_due );
							}



							$promotionType = $getTokenHolderResult->text_9;
							$notes_external = $bonus_percentage.'% bonus';
		
							?>
							<tr>
								<td><?php echo $loopCounter; ?></td>
								<td class="eth_address"><a href="javascript:void(0);"><?php echo $getTokenHolderResult->reference; ?></a></td>
								<td><?php echo $getTokenHolderResult->username; ?></td>
								<td><?php echo $getTokenHolderResult->email; ?></td>
								<td><?php echo $getTokenHolderResult->redemption_date; ?></td>
								<td><?php echo $getTokenHolderResult->corp_approved; ?></td>
								<td><?php echo $notes_external; ?></td>
								<td><?php echo number_format( $getParentReferenceData->parentReferenceInitialAmount ); ?></td>
								<td><?php echo number_format( $getTokenHolderResult->csr_amount_initial ); ?></td>
								<td><?php echo number_format( $getTokenHolderResult->amount_due ); ?></td>
								<td><?php echo number_format( $csr_amount_initial ); ?></td>
								<td><?php echo number_format( $amount_due ); ?></td>
							</tr>
							<?php
							$csr_amount_pending = $csr_amount_pending - $amount_due;
							$loopCounter++;
						}
					}
					?>
					</table>
					</div>
					<?php
				}
				$html .= ob_get_clean();
				$out = array( "error" => 0,'msg' => 'Adjustment process', 'html' => $html );

			}else if( $promotion_type == 'discount' ){
				
				$html = "";
				ob_start();
				if( is_array( $_POST['parentReferenceNumber'] ) ){
					?>
					<div class="table-responsive">
					<table>
					<tr>
						<th><?php _e('#', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Reference', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Username', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Email', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Redemption date', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Corp approved', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Bonus or Discount', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('PNP CSR amount initial', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Current CSR amount initial', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('Current Amount due', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('New CSR amount initial', CIP_TXTDOMAIN); ?></th>
						<th><?php _e('New Amount due', CIP_TXTDOMAIN); ?></th>
					</tr>
					<?php
					foreach( $_POST['parentReferenceNumber'] as $parentReferenceId ){

						$disReference = 'DIS-'.$parentReferenceId;
						
						$getAffectedRecords = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND `text_9` = 'discount' AND `reference` LIKE '". $disReference ."%' ORDER BY `id` ASC");

						$getTokenHolderResultsCheckIsNotPending = $wpdb->get_var("SELECT COUNT(*) FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND `text_9` = 'discount' AND ( `corp_approved` != 'Pending' OR `corp_approved` IS NULL OR `corp_approved` = '' )");
						if( $getTokenHolderResultsCheckIsNotPending ){
							?><tr><td colspan="12"><?php echo __('All records have not "corp_approved" is "Pending"',CIP_TXTDOMAIN); ?></td><?php
							$out = array( "error" => 1,'msg' => __('All records have not "corp_approved" is "Pending"',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

						$pnpReference = 'PNP-' . $parentReferenceId;
						$getParentReferenceData = $wpdb->get_row("SELECT `csr_amount_initial` as `parentReferenceInitialAmount` FROM $tableTokenHolder WHERE `reference` LIKE '". $pnpReference ."%' ORDER BY `id` DESC LIMIT 1");
						if( !$getParentReferenceData ){
							$html .= ob_get_clean();
							$html .= '<tr><td colspan="12">'. __('PNP records not found for reference :: '. $parentReferenceId,CIP_TXTDOMAIN). '</td>';
							$out = array( "error" => 1,'msg' => __('PNP records not found for reference :: '. $parentReferenceId,CIP_TXTDOMAIN), 'html' => $html );
							echo wp_json_encode( $out );
							exit;
							break;
						}

						$csr_amount_initial = $getParentReferenceData->parentReferenceInitialAmount;
						$getEuroAmount =  (int)(string)($csr_price * $csr_amount_initial);
						$final_discount_percentage = 100 - $discount_percentage;
						$discountedCsrRate = $csr_price * $final_discount_percentage / 100;
						$estimated_amount_csr = $getEuroAmount / $discountedCsrRate;

						$discounted_amount_csr = $estimated_amount_csr - $csr_amount_initial;
						$discounted_amount_csr = sprintf("%.2f", $discounted_amount_csr);

						$csr_amount_initial = ceil( $discounted_amount_csr );
						$csr_amount_pending = $csr_amount_initial;

						$loopCounter = 1;
						$promotion_number_of_deliveries = count( $getAffectedRecords );
						foreach( $getAffectedRecords as $getTokenHolderResult ){

							

							if( $promotion_number_of_deliveries <= 1 ){
								$amount_due = $csr_amount_initial;
							}else{
								
								$i = $loopCounter - 1;

								$amount_due = $csr_amount_pending / ( $promotion_number_of_deliveries - $i );
								$amount_due = ceil( $amount_due );
							}



							$promotionType = $getTokenHolderResult->text_9;
							$notes_external = $discount_percentage.'% discount';
		
							?>
							<tr>
								<td><?php echo $loopCounter; ?></td>
								<td class="eth_address"><a href="javascript:void(0);"><?php echo $getTokenHolderResult->reference; ?></a></td>
								<td><?php echo $getTokenHolderResult->username; ?></td>
								<td><?php echo $getTokenHolderResult->email; ?></td>
								<td><?php echo $getTokenHolderResult->redemption_date; ?></td>
								<td><?php echo $getTokenHolderResult->corp_approved; ?></td>
								<td><?php echo $notes_external; ?></td>
								<td><?php echo number_format( $getParentReferenceData->parentReferenceInitialAmount ); ?></td>
								<td><?php echo number_format( $getTokenHolderResult->csr_amount_initial ); ?></td>
								<td><?php echo number_format( $getTokenHolderResult->amount_due ); ?></td>
								<td><?php echo number_format( $csr_amount_initial ); ?></td>
								<td><?php echo number_format( $amount_due ); ?></td>
							</tr>
							<?php
							$csr_amount_pending = $csr_amount_pending - $amount_due;
							$loopCounter++;
						}
					}
					?>
					</table>
					</div>
					<?php
				}
				$html .= ob_get_clean();
				$out = array( "error" => 0,'msg' => 'Adjustment process', 'html' => $html );
			}

		}else if( isset( $_POST['step'] ) && $_POST['step'] == 'step_5' ){	//step 5



			$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
			if( empty( $google_auth_key ) ){
				$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}

			$gaOTPValid = false;
			if( !empty( $_POST['user_ga_otp'] ) ){
				$google2fa = new \PragmaRX\Google2FA\Google2FA();
				if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
					$gaOTPValid = true;
				}
			}

			if( $gaOTPValid === false ){
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}

			$promotion_type = $_POST['promotionType'];
			$bonus_percentage = ( isset( $_POST['promotion_bonus'] ) ) ? $_POST['promotion_bonus'] : 0;
			$discount_percentage = ( isset( $_POST['promotion_discount'] ) ) ? $_POST['promotion_discount'] : 0;
			$csr_price = ( isset( $_POST['promotion_csr_price'] ) ) ? $_POST['promotion_csr_price'] : 0;

			if( !empty( $email_or_username ) && filter_var($email_or_username, FILTER_VALIDATE_EMAIL) ){
				$emailOrUsernameWhere = " AND `email`='". $email_or_username ."'";
			}else if( !empty( $email_or_username ) ){
				$emailOrUsernameWhere = " AND `username`='". $email_or_username ."'";
			}
			if( empty( $email_or_username ) || empty( $redemption_date ) ){
				$out = array( "error" => 1,'msg' => __('Email or username & Redemption date is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;	
			}

			if( $promotion_type == 'bonus' ){

				$html = "";
				$recordsUpdateCounter = 0;
				if( is_array( $_POST['parentReferenceNumber'] ) ){
					foreach( $_POST['parentReferenceNumber'] as $parentReferenceId ){

						$disReference = 'BNS-'.$parentReferenceId;
						
						$getAffectedRecords = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND `text_9` = 'bonus' AND `reference` LIKE '". $disReference ."%' ORDER BY `id` ASC");

						$getTokenHolderResultsCheckIsNotPending = $wpdb->get_var("SELECT COUNT(*) FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND `text_9` = 'bonus' AND ( `corp_approved` != 'Pending' OR `corp_approved` IS NULL OR `corp_approved` = '' )");
						if( $getTokenHolderResultsCheckIsNotPending ){
							$out = array( "error" => 1,'msg' => __('All records have not "corp_approved" is "Pending"',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

						$pnpReference = 'PNP-' . $parentReferenceId;
						$getParentReferenceData = $wpdb->get_row("SELECT `csr_amount_initial` as `parentReferenceInitialAmount` FROM $tableTokenHolder WHERE `reference` LIKE '". $pnpReference ."%' ORDER BY `id` DESC LIMIT 1");
						if( !$getParentReferenceData ){
							$out = array( "error" => 1,'msg' => __('PNP records not found for reference :: '. $parentReference,CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
							break;
						}

						$csr_amount_initial = $getParentReferenceData->parentReferenceInitialAmount;
						$bonus_amount = $csr_amount_initial * $bonus_percentage / 100;
						$csr_amount_initial = ceil( $bonus_amount );
						
						$csr_amount_pending = $csr_amount_initial;

						$loopCounter = 1;
						$promotion_number_of_deliveries = count( $getAffectedRecords );
						foreach( $getAffectedRecords as $getTokenHolderResult ){


							if( $promotion_number_of_deliveries <= 1 ){
								$amount_due = $csr_amount_initial;
							}else{
								
								$i = $loopCounter - 1;

								$amount_due = $csr_amount_pending / ( $promotion_number_of_deliveries - $i );
								$amount_due = ceil( $amount_due );
							}



							$promotionType = $getTokenHolderResult->text_9;
							$notes_external = $getTokenHolderResult->notes_external;

							$old_promotion = getTwoWordsAfterHyphen( $getTokenHolderResult->notes_external );
							$new_promotion = $bonus_percentage.'% bonus';
							
							$notes_external = str_replace($old_promotion, $new_promotion, $notes_external);

							$updateData = [
								'csr_amount_initial'	=>	$csr_amount_initial,
								'amount_due'			=>	$amount_due,
								'notes_external'		=>	$notes_external,
								'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
							];

							$whereData = [ 'reference' => $getTokenHolderResult->reference ];

							$updatePromotion = $wpdb->update( $tableTokenHolder, $updateData, $whereData );

							if( $updatePromotion ){
								$log_type = 'promotion_redemptions_update';
								$logs = sprintf( __('Promotion record update holder of reference :: %s at %s
								csr_amount_initial : %s to %s
								amount_due : %s to %s
								notes : %s to %s', CIP_TXTDOMAIN), $getTokenHolderResult->reference, date_i18n('d/m/Y H:i:s'),
								$getTokenHolderResult->csr_amount_initial, $csr_amount_initial,
								$getTokenHolderResult->amount_due, $amount_due,
								$old_promotion, $new_promotion );
								create_weekly_distribution_cip_logs( 'sm', $log_type, $logs );
								$recordsUpdateCounter++;
							}
							
							$csr_amount_pending = $csr_amount_pending - $amount_due;
							$loopCounter++;
						}
					}
					$html .= '<p><b>'. $recordsUpdateCounter .' Promotion</b> records updated.</p>';
					$out = array( "error" => 0,'msg' => 'Adjustment process complete', 'html' => $html );
				}

			}else if( $promotion_type == 'discount' ){

				$html = "";
				$recordsUpdateCounter = 0;
				if( is_array( $_POST['parentReferenceNumber'] ) ){
					foreach( $_POST['parentReferenceNumber'] as $parentReferenceId ){

						$disReference = 'DIS-'.$parentReferenceId;
						
						$getAffectedRecords = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND `text_9` = 'discount' AND `reference` LIKE '". $disReference ."%' ORDER BY `id` ASC");

						$getTokenHolderResultsCheckIsNotPending = $wpdb->get_var("SELECT COUNT(*) FROM $tableTokenHolder WHERE 1 $emailOrUsernameWhere AND `redemption_date` = '". $redemption_date ."' AND `text_9` = 'discount' AND ( `corp_approved` != 'Pending' OR `corp_approved` IS NULL OR `corp_approved` = '' )");
						if( $getTokenHolderResultsCheckIsNotPending ){
							$out = array( "error" => 1,'msg' => __('All records have not "corp_approved" is "Pending"',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

						$pnpReference = 'PNP-' . $parentReferenceId;
						$getParentReferenceData = $wpdb->get_row("SELECT `csr_amount_initial` as `parentReferenceInitialAmount` FROM $tableTokenHolder WHERE `reference` LIKE '". $pnpReference ."%' ORDER BY `id` DESC LIMIT 1");
						if( !$getParentReferenceData ){
							$out = array( "error" => 1,'msg' => __('PNP records not found for reference :: '. $parentReference,CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
							break;
						}

						$csr_amount_initial = $getParentReferenceData->parentReferenceInitialAmount;
						$getEuroAmount =  (int)(string)($csr_price * $csr_amount_initial);
						$final_discount_percentage = 100 - $discount_percentage;
						$discountedCsrRate = $csr_price * $final_discount_percentage / 100;
						$estimated_amount_csr = $getEuroAmount / $discountedCsrRate;

						$discounted_amount_csr = $estimated_amount_csr - $csr_amount_initial;
						$discounted_amount_csr = sprintf("%.2f", $discounted_amount_csr);

						$csr_amount_initial = ceil( $discounted_amount_csr );
						$csr_amount_pending = $csr_amount_initial;

						$loopCounter = 1;
						$promotion_number_of_deliveries = count( $getAffectedRecords );
						foreach( $getAffectedRecords as $getTokenHolderResult ){


							if( $promotion_number_of_deliveries <= 1 ){
								$amount_due = $csr_amount_initial;
							}else{
								
								$i = $loopCounter - 1;

								$amount_due = $csr_amount_pending / ( $promotion_number_of_deliveries - $i );
								$amount_due = ceil( $amount_due );
							}



							$promotionType = $getTokenHolderResult->text_9;
							$notes_external = $getTokenHolderResult->notes_external;

							$old_promotion = getTwoWordsAfterHyphen( $getTokenHolderResult->notes_external );
							$new_promotion = $discount_percentage.'% discount';
							
							$notes_external = str_replace($old_promotion, $new_promotion, $notes_external);

							$updateData = [
								'csr_amount_initial'	=>	$csr_amount_initial,
								'amount_due'			=>	$amount_due,
								'notes_external'		=>	$notes_external,
								'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
							];

							$whereData = [ 'reference' => $getTokenHolderResult->reference ];

							$updatePromotion = $wpdb->update( $tableTokenHolder, $updateData, $whereData );

							if( $updatePromotion ){
								$log_type = 'promotion_redemptions_update';
								$logs = sprintf( __('Promotion record update holder of reference :: %s at %s
								csr_amount_initial : %s to %s
								amount_due : %s to %s
								notes : %s to %s', CIP_TXTDOMAIN), $getTokenHolderResult->reference, date_i18n('d/m/Y H:i:s'),
								$getTokenHolderResult->csr_amount_initial, $csr_amount_initial,
								$getTokenHolderResult->amount_due, $amount_due,
								$old_promotion, $new_promotion );
								create_weekly_distribution_cip_logs( 'sm', $log_type, $logs );
								$recordsUpdateCounter++;
							}
							
							$csr_amount_pending = $csr_amount_pending - $amount_due;
							$loopCounter++;
						}
					}
					$html .= '<p><b>'. $recordsUpdateCounter .' Promotion</b> records updated.</p>';
					$out = array( "error" => 0,'msg' => 'Adjustment process complete', 'html' => $html );
				}
			}

		}

		echo wp_json_encode( $out );
		exit;
	}
	echo wp_json_encode( $out );
	exit;
}
function getTwoWordsAfterHyphen($string) {
    if (preg_match('/-\s*(\S+\s+\S+)/', $string, $matches)) {
        return trim($matches[1]);
    }
    return '-';
}