<?php
use \PsychoB\Ethereum\AddressValidator;
function get_new_delivery_plan_wizard(){
	$html = "";
	global $wpdb;
	ob_start();
	$total_step = 8;
	?>
	<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="new_delivery_plan_wizard" class="new_delivery_plan_wizard" id="msform">
					<!-- progressbar -->
					<ul id="progressbar">
	                        <li class="active" id="fileupload"><strong><?php _e('Choose file',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="logging"><strong><?php _e('Logs',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="fieldmapping"><strong><?php _e('Review',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="fieldmapping"><strong><?php _e('Segment and Allocate Deliveries',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="fieldmapping"><strong><?php _e('Review Primary Deliveries',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="fieldmapping"><strong><?php _e('Review Promotion Deliveries',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="codemerge"><strong><?php _e('Append New CSR Holders',CIP_TXTDOMAIN) ?></strong></li>
	                        <li id="confirm"><strong><?php _e('Finish',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>
								<label class="fieldlabels"><?php _e('Select Token Type',CIP_TXTDOMAIN); ?></label>
								<select name="token" id="token">
									<option value="CSR25">CSR25</option>
									<option value="CSR">CSR</option>
								</select>
								<label class="fieldlabels"><?php _e('Choose file',CIP_TXTDOMAIN); ?></label> <input type="file" name="th_csv_file" accept=".csv"  required />
								<div class="pool_ref_toogle" style="display: none;">
									<div class="row">
										<div class="col-md-12">
											<label class="fieldlabels" for="pool_reference"><?php _e('Pool Reference',CIP_TXTDOMAIN); ?></label> <input class="form-control" type="text" name="pool_reference" id="pool_reference" required />
										</div>
										<div class="col-md-12">
											<label class="fieldlabels" for="csr_segmentation"><?php _e('<span class="token_type_label">CSR25</span> Segmentation',CIP_TXTDOMAIN); ?></label> <input class="form-control" type="text" name="csr_segmentation" id="csr_segmentation" min="10" value="100" placeholder="<?php _e('Default will be 100', CIP_TXTDOMAIN); ?>" required />
										</div>

										
										<div class="col-md-12">
											<div class="d-flex">
												<div class="form-check-inline">
													<label class="form-check-label d-flex lh-1"><input type="radio" name="week_wise_advanced" class="form-check-input" value="normal" checked><?php _e('Normal', CIP_TXTDOMAIN); ?></label>
												</div>
												<div class="form-check-inline">
													<label class="form-check-label d-flex lh-1"><input type="radio" name="week_wise_advanced" class="form-check-input" value="week_wise"><?php _e('Week Wise Advanced', CIP_TXTDOMAIN); ?></label>
												</div>
											</div>
										</div>

										<div class="week_wise_normal_section container-fluid pl-0 pr-0"> <!-- Week wise normal -->
											<div class="col-md-12">
												<div class="card">
													<div class="card-body">
														<h5 class="section-header mb-0 mt-2"><?php _e('Primary <span class="token_type_label">CSR25</span>', CIP_TXTDOMAIN); ?></h5>
														<div class="row">
															<div class="col-md-4 col-sm-12">
																<label class="fieldlabels" for="primary_number_of_deliveries"><?php _e('Number of deliveries',CIP_TXTDOMAIN); ?></label>
																<select class="form-control" name="primary_number_of_deliveries" id="primary_number_of_deliveries" required>
																	<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
																	<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
																	<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
																	<option value="4"><?php _e('4', CIP_TXTDOMAIN); ?></option>
																	<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
																	<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
																	<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
																	<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
																	<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
																	<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
																</select>
															</div>
															<div class="col-md-4 col-sm-12 primary_delivery_interval_toggle" style="display: none;">
																<label class="fieldlabels" for="primary_delivery_interval"><?php _e('Delivery interval',CIP_TXTDOMAIN); ?></label>
																<select class="form-control" name="primary_delivery_interval" id="primary_delivery_interval" required>
																	<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
																	<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
																	<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
																	<option value="4" selected><?php _e('4', CIP_TXTDOMAIN); ?></option>
																	<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
																	<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
																	<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
																	<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
																	<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
																	<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
																</select>
															</div>
															<div class="col-md-4 col-sm-12">
																<label class="fieldlabels" for="primary_delivery_start_week"><?php _e('Delivery start week',CIP_TXTDOMAIN); ?></label>
																<input class="form-control" type="text" name="primary_delivery_start_week" id="primary_delivery_start_week" min="0" max="200" value="40" placeholder="<?php _e('Default will be 40', CIP_TXTDOMAIN); ?>" required />
															</div>
														</div>
													</div>
												</div>
											</div>
											<div class="col-md-12">
												<div class="card">
													<div class="card-body">
														<h5 class="section-header mb-0 mt-2"><?php _e('Promotion <span class="token_type_label">CSR25</span>', CIP_TXTDOMAIN); ?></h5>
														<div class="row">
															<div class="col-md-12 col-sm-12">
																<label class="fieldlabels" for="promotion_type"><?php _e('Promotion Type',CIP_TXTDOMAIN); ?></label>
																<select class="form-control" name="promotion_type" id="promotion_type">
																	<option value="none"><?php _e('None', CIP_TXTDOMAIN); ?></option>
																	<option value="bonus"><?php _e('Bonus', CIP_TXTDOMAIN); ?></option>
																	<option value="discount"><?php _e('Discount', CIP_TXTDOMAIN); ?></option>
																</select>
															</div>
															<div class="col-md-12 col-sm-12">
																<div class="bonus_section_fields" style="display: none;">
																	<label class="fieldlabels" for="bonus_percentage"><?php _e('Bonus Percentage',CIP_TXTDOMAIN); ?></label>
																	<input class="form-control" type="text" name="bonus_percentage" id="bonus_percentage" min="0" />
																</div>
																<div class="discount_section_fields" style="display: none;">
																	<label class="fieldlabels" for="discount_percentage"><?php _e('Discount Percentage',CIP_TXTDOMAIN); ?></label>
																	<input class="form-control" type="text" name="discount_percentage" id="discount_percentage" min="1" max="99" />
																</div>
															</div>
														</div>
														<div class="row promotion_toggle_section" style="display: none;">
															<div class="col-md-4 col-sm-12">
																<label class="fieldlabels" for="promotion_number_of_deliveries"><?php _e('Number of deliveries',CIP_TXTDOMAIN); ?></label>
																<select class="form-control" name="promotion_number_of_deliveries" id="promotion_number_of_deliveries" required>
																	<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
																	<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
																	<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
																	<option value="4"><?php _e('4', CIP_TXTDOMAIN); ?></option>
																	<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
																	<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
																	<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
																	<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
																	<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
																	<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
																</select>
															</div>
															<div class="col-md-4 col-sm-12 promotion_delivery_interval_toggle" style="display: none;">
																<label class="fieldlabels" for="promotion_delivery_interval"><?php _e('Delivery interval',CIP_TXTDOMAIN); ?></label>
																<select class="form-control" name="promotion_delivery_interval" id="promotion_delivery_interval" required>
																	<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
																	<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
																	<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
																	<option value="4" selected><?php _e('4', CIP_TXTDOMAIN); ?></option>
																	<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
																	<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
																	<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
																	<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
																	<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
																	<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
																</select>
															</div>
															<div class="col-md-4 col-sm-12">
																<label class="fieldlabels" for="promotion_delivery_start_week"><?php _e('Delivery start week',CIP_TXTDOMAIN); ?></label>
																<input class="form-control" type="text" name="promotion_delivery_start_week" id="promotion_delivery_start_week" min="0" max="200" value="80" placeholder="<?php _e('Default will be 80', CIP_TXTDOMAIN); ?>" required />
															</div>
														</div>
													</div>
												</div>
											</div>
											<div class="col-md-12">
												<div class="custom-control custom-switch">
													<input type="checkbox" class="custom-control-input" name="advanced_weekly_wizard_option" id="advanced_weekly_wizard_option" value="advanced">
													<label class="custom-control-label advanced_weekly_wizard_option_label" for="advanced_weekly_wizard_option"><?php _e('Advanced',CIP_TXTDOMAIN); ?></label>
												</div>
											</div>
											<div class="col-md-12 advanced_options_table_data" style="display: none;">
											</div>
										</div> <!-- week wise normal -->

										<div class="week_wise_advanced_section container-fluid pl-0 pr-0" style="display: none;"> <!-- Week wise advanced -->
											<div class="col-md-12">
												<div class="card">
													<div class="card-body">
														<h5 class="section-header mb-0 mt-2"><?php _e('Primary <span class="token_type_label">CSR25</span>', CIP_TXTDOMAIN); ?></h5>
														<div class="row">
															<div class="col-md-12 col-sm-12">
																<label class="fieldlabels" for="week_wise_primary_number_of_deliveries"><?php _e('Number of deliveries',CIP_TXTDOMAIN); ?></label>
																<select class="form-control" name="week_wise_primary_number_of_deliveries" id="week_wise_primary_number_of_deliveries">
																	<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
																	<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
																	<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
																	<option value="4"><?php _e('4', CIP_TXTDOMAIN); ?></option>
																	<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
																	<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
																	<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
																	<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
																	<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
																	<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
																</select>
															</div>
														</div>

														<div class="row">
															<div class="col-md-8 col-sm-12">
																<table class="table table-bordered table-hover mt-2 week_wise_primary_index_table_section">
																	<tr>
																		<th><?php _e('#', CIP_TXTDOMAIN); ?></th>
																		<th><?php _e('Start Week Number', CIP_TXTDOMAIN); ?></th>
																		<th><?php _e('Redemption percentage', CIP_TXTDOMAIN); ?></th>
																	</tr>
																	<?php for( $i=1; $i <= 10; $i++ ){
																		$isShowClass = ( $i == 1 ) ? 'show' : 'hide';
																		$isDisable = ( $i == 1 ) ? '' : 'disabled';
																	?>
																	<tr class="week_wise_primary_week_loop week_wise_primary_index_<?php echo $i; ?> <?php echo $isShowClass; ?> ">
																		<td><?php echo $i; ?></td>
																		<td><input type="text" name="week_wise_start_week_index[]" class="week_wise_week_index mb-0 form-control" <?php echo $isDisable; ?> /></td>
																		<td><input type="text" name="week_wise_redemption_percentage[]" class="week_wise_redemption_percentage mb-0 form-control" <?php echo $isDisable; ?> /></td>
																	</tr>
																	<?php } ?>
																</table>
															</div>
														</div>

													</div>
												</div>
											</div>

											<div class="col-md-12">
												<div class="card">
													<div class="card-body">
														<h5 class="section-header mb-0 mt-2"><?php _e('Promotion <span class="token_type_label">CSR25</span>', CIP_TXTDOMAIN); ?></h5>
														<div class="row">
															<div class="col-md-12 col-sm-12">
																<label class="fieldlabels" for="week_wise_promotion_type"><?php _e('Promotion Type',CIP_TXTDOMAIN); ?></label>
																<select class="form-control" name="week_wise_promotion_type" id="week_wise_promotion_type">
																	<option value="none"><?php _e('None', CIP_TXTDOMAIN); ?></option>
																	<option value="bonus"><?php _e('Bonus', CIP_TXTDOMAIN); ?></option>
																	<option value="discount"><?php _e('Discount', CIP_TXTDOMAIN); ?></option>
																</select>
															</div>
															<div class="col-md-12 col-sm-12">
																<div class="week_wise_bonus_section_fields" style="display: none;">
																	<label class="fieldlabels" for="week_wise_bonus_percentage"><?php _e('Bonus Percentage',CIP_TXTDOMAIN); ?></label>
																	<input class="form-control" type="text" name="week_wise_bonus_percentage" id="week_wise_bonus_percentage" min="0" />
																</div>
																<div class="week_wise_discount_section_fields" style="display: none;">
																	<label class="fieldlabels" for="week_wise_discount_percentage"><?php _e('Discount Percentage',CIP_TXTDOMAIN); ?></label>
																	<input class="form-control" type="text" name="week_wise_discount_percentage" id="week_wise_discount_percentage" min="1" max="99" />
																</div>
															</div>
														</div>
														<div class="row week_wise_promotion_toggle_section" style="display: none;">
															<div class="col-md-12 col-sm-12">
																<label class="fieldlabels" for="week_wise_promotion_number_of_deliveries"><?php _e('Number of deliveries',CIP_TXTDOMAIN); ?></label>
																<select class="form-control" name="week_wise_promotion_number_of_deliveries" id="week_wise_promotion_number_of_deliveries" required>
																	<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
																	<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
																	<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
																	<option value="4"><?php _e('4', CIP_TXTDOMAIN); ?></option>
																	<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
																	<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
																	<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
																	<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
																	<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
																	<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
																</select>
															</div>
														</div>

														<div class="row week_wise_promotion_toggle_section" style="display: none;">
															<div class="col-md-8 col-sm-12">
																<table class="table table-bordered table-hover mt-2 week_wise_promotion_index_table_section">
																	<tr>
																		<th>#</th>
																		<th>Start Week Number</th>
																		<th>Redemption percentage</th>
																	</tr>
																	<?php for( $i=1; $i <= 10; $i++ ){
																		$isShowClass = ( $i == 1 ) ? 'show' : 'hide';
																		$isDisable = ( $i == 1 ) ? '' : 'disabled';
																	?>
																	<tr class="week_wise_promotion_week_loop week_wise_promotion_index_<?php echo $i; ?> <?php echo $isShowClass; ?> ">
																		<td><?php echo $i; ?></td>
																		<td><input type="text" name="week_wise_promotion_start_week_index[]" class="week_wise_promotion_week_index mb-0 form-control" <?php echo $isDisable; ?> /></td>
																		<td><input type="text" name="week_wise_promotion_redemption_percentage[]" class="week_wise_promotion_redemption_percentage mb-0 form-control" <?php echo $isDisable; ?> /></td>
																	</tr>
																	<?php } ?>
																</table>
															</div>
														</div>

													</div>
												</div>
											</div>

											<div class="col-md-12">
												<div class="custom-control custom-switch">
													<input type="checkbox" class="custom-control-input" name="week_wise_advanced_weekly_wizard_option" id="week_wise_advanced_weekly_wizard_option" value="advanced">
													<label class="custom-control-label week_wise_advanced_weekly_wizard_option_label" for="week_wise_advanced_weekly_wizard_option"><?php _e('Advanced',CIP_TXTDOMAIN); ?></label>
												</div>
											</div>
											<div class="col-md-12 week_wise_advanced_options_table_data" style="display: none;">
											</div>

										</div> <!-- week wise advanced -->
									</div>
								</div>
	                        </div>
	                        <input type="button" name="next" class="next action-button first_step invisible" 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">
									<div class="col-12">
										<ul class="list-group list-group-flush process_log" id="process_log"></ul>
										<div class="csr_spinner" style="display: none;">
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
										</div>
									</div>
								</div>
							</div>
							<input type="button" name="next" class="next action-button token_type_label_btn" value="Review New CSR Holders Data" style="display: none;" disabled /> <input type="button" name="previous" class="previous action-button-previous" value="Previous" style="display: none;" />
						</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 text-center import_update_response"></div>
									<div class="col-12 text-center distribution_section_table" style="display:none;">
										<p class="text-left total_import_label"></p>
										<table id="new_delivery_plan_distribution_table" data-toolbar="false" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="true" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" class="table table-bordered" data-side-pagination="server" data-page-list="[10, 20, 50, 100]" data-response-handler="responseNewDeliveryPlanImportHandler">
											<thead>
												<tr>
												<th data-field="id" class="id"><?php _e('#',CIP_TXTDOMAIN); ?></th>
												<th data-field="username" data-sortable="true" data-filter-control="input" class="username"><?php echo __('Username',CIP_TXTDOMAIN); ?></th>
												<th data-field="reference" data-sortable="true" data-filter-control="input" class="reference"><?php echo __('Reference Number',CIP_TXTDOMAIN); ?></th>
												<th data-field="eth_address" data-sortable="true" data-filter-control="input" class="eth_address"><?php echo __('CSR wallet address',CIP_TXTDOMAIN); ?></th>
												<th data-field="csr_amount_initial" data-sortable="true" data-filter-control="input" class="csr_amount_initial"><?php echo __('CSR Amount Initial',CIP_TXTDOMAIN); ?></th>
												<th data-field="first_name" data-sortable="true" data-filter-control="input" class="first_name"><?php echo __('First name',CIP_TXTDOMAIN); ?></th>
												<th data-field="last_name" data-sortable="true" data-filter-control="input" class="last_name"><?php echo __('Last name',CIP_TXTDOMAIN); ?></th>
												<th data-field="created" data-sortable="true" data-filter-control="input" class="created"><?php echo __('Created',CIP_TXTDOMAIN); ?></th>
												<th data-field="csr_price" data-sortable="csr_price" data-filter-control="input" class="csr_price"><?php echo __('CSR Price',CIP_TXTDOMAIN); ?></th>
												<th data-field="email" data-sortable="true" data-filter-control="input" class="email"><?php echo __('Email',CIP_TXTDOMAIN); ?></th>
												<th data-field="distribution_status" data-sortable="true" data-filter-control="input" class="distribution_status"><?php echo __('Distribution Status',CIP_TXTDOMAIN); ?></th>
												<!-- <th data-field="member_status" data-sortable="true" data-filter-control="input" class="member_status"><?php echo __('Member Status',CIP_TXTDOMAIN); ?></th> -->
												<th data-field="pool_ref" data-sortable="true" data-filter-control="input" class="pool_ref"><?php echo __('Pool Reference ',CIP_TXTDOMAIN); ?></th>
												</tr>
											</thead>
											<tbody></tbody>
										</table>
									</div>
								</div>
	                        </div>
							<input type="button" name="next" class="next action-button" value="Split Delivery Data" /> <input type="button" name="previous" class="previous action-button-previous back_disable" 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">
									<div class="col-12">
										<ul class="list-group list-group-flush process_split_log" id="process_split_log"></ul>
										<div class="csr_split_spinner" style="display: none;">
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
										</div>
									</div>
								</div>
	                        </div>
							<input type="button" name="next" class="next action-button" value="Review Delivery Data" />
							<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 justify-content-center">
									<div class="col-12 text-center import_update_response"></div>
									<div class="col-12 text-center distribution_10_section_table" style="display:none;">
										<p class="text-left total_distribution_label"></p>
										<table id="new_delivery_plan_distribution_10_table" data-toolbar="false" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="true" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" class="table table-bordered" data-side-pagination="server" data-page-list="[10, 20, 50, 100]" data-response-handler="responseNewDeliveryPlanHandler">
											<thead>
												<tr>
												<th data-field="id" class="id"><?php _e('#',CIP_TXTDOMAIN); ?></th>
												<th data-field="username" data-sortable="true" data-filter-control="input" class="username"><?php echo __('Username',CIP_TXTDOMAIN); ?></th>
												<th data-field="reference" data-sortable="true" data-filter-control="input" class="reference"><?php echo __('Reference Number',CIP_TXTDOMAIN); ?></th>
												<th data-field="eth_address" data-sortable="true" data-filter-control="input" class="eth_address"><?php echo __('CSR wallet address',CIP_TXTDOMAIN); ?></th>
												<th data-field="csr_amount_initial" data-sortable="true" data-filter-control="input" class="csr_amount_initial"><?php echo __('CSR Amount Initial',CIP_TXTDOMAIN); ?></th>
												<th data-field="csr_amount_issued" data-sortable="true" data-filter-control="input" class="csr_amount_issued"><?php echo __('CSR Amount Issued',CIP_TXTDOMAIN); ?></th>
												<th data-field="amount_due" data-sortable="true" data-filter-control="input" class="amount_due"><?php echo __('Amount Due',CIP_TXTDOMAIN); ?></th>
												<th data-field="first_name" data-sortable="true" data-filter-control="input" class="first_name"><?php echo __('First name',CIP_TXTDOMAIN); ?></th>
												<th data-field="last_name" data-sortable="true" data-filter-control="input" class="last_name"><?php echo __('Last name',CIP_TXTDOMAIN); ?></th>
												<th data-field="created" data-sortable="true" data-filter-control="input" class="created"><?php echo __('Created',CIP_TXTDOMAIN); ?></th>
												<th data-field="email" data-sortable="true" data-filter-control="input" class="email"><?php echo __('Email',CIP_TXTDOMAIN); ?></th>
												<th data-field="distribution_status" data-sortable="true" data-filter-control="input" class="distribution_status"><?php echo __('Distribution Status',CIP_TXTDOMAIN); ?></th>
												<!-- <th data-field="corp_approved" data-sortable="true" data-filter-control="input" class="corp_approved"><?php echo __('Corp Approved',CIP_TXTDOMAIN); ?></th> -->
												<th data-field="week_number" data-sortable="true" data-filter-control="input" class="week_number"><?php echo __('Week Number',CIP_TXTDOMAIN); ?></th>
												<!-- <th data-field="member_status" data-sortable="true" data-filter-control="input" class="member_status"><?php echo __('Member Status',CIP_TXTDOMAIN); ?></th> -->
												<th data-field="pool_ref" data-sortable="true" data-filter-control="input" class="pool_ref"><?php echo __('Pool Reference ',CIP_TXTDOMAIN); ?></th>
												<th data-field="source" data-sortable="true" data-filter-control="input" class="source"><?php echo __('Source ',CIP_TXTDOMAIN); ?></th>
												</tr>
											</thead>
											<tbody></tbody>
										</table>
									</div>
								</div>
	                        </div>
							<input type="button" name="next" class="next action-button" value="Review Promotion" />
							<input type="button" name="previous" class="previous action-button-previous back_disable" value="Previous" />
	                    </fieldset>
						<fieldset class="step_5">
	                        <div class="form-card">
	                            <div class="row">
	                                <div class="col-12">
	                                    <h2 class="steps"><?php echo sprintf('Step %s - %s', 6, $total_step); ?></h2>
	                                </div>
	                            </div>
	                            <div class="row justify-content-center">
									<div class="col-12 text-center import_update_response"></div>
									<div class="col-12 text-center distribution_promotion_section_table" style="display:none;">
										<p class="text-left total_distribution_promotion_label"></p>
										<table id="new_delivery_plan_distribution_promotion_table" data-toolbar="false" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="true" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" class="table table-bordered" data-side-pagination="server" data-page-list="[10, 20, 50, 100]" data-response-handler="responseNewDeliveryPlanPromotionHandler">
											<thead>
												<tr>
												<th data-field="id" class="id"><?php _e('#',CIP_TXTDOMAIN); ?></th>
												<th data-field="username" data-sortable="true" data-filter-control="input" class="username"><?php echo __('Username',CIP_TXTDOMAIN); ?></th>
												<th data-field="reference" data-sortable="true" data-filter-control="input" class="reference"><?php echo __('Reference Number',CIP_TXTDOMAIN); ?></th>
												<th data-field="eth_address" data-sortable="true" data-filter-control="input" class="eth_address"><?php echo __('CSR wallet address',CIP_TXTDOMAIN); ?></th>
												<th data-field="csr_amount_initial" data-sortable="true" data-filter-control="input" class="csr_amount_initial"><?php echo __('CSR Amount Initial',CIP_TXTDOMAIN); ?></th>
												<th data-field="csr_amount_issued" data-sortable="true" data-filter-control="input" class="csr_amount_issued"><?php echo __('CSR Amount Issued',CIP_TXTDOMAIN); ?></th>
												<th data-field="amount_due" data-sortable="true" data-filter-control="input" class="amount_due"><?php echo __('Amount Due',CIP_TXTDOMAIN); ?></th>
												<th data-field="first_name" data-sortable="true" data-filter-control="input" class="first_name"><?php echo __('First name',CIP_TXTDOMAIN); ?></th>
												<th data-field="last_name" data-sortable="true" data-filter-control="input" class="last_name"><?php echo __('Last name',CIP_TXTDOMAIN); ?></th>
												<th data-field="created" data-sortable="true" data-filter-control="input" class="created"><?php echo __('Created',CIP_TXTDOMAIN); ?></th>
												<th data-field="email" data-sortable="true" data-filter-control="input" class="email"><?php echo __('Email',CIP_TXTDOMAIN); ?></th>
												<th data-field="distribution_status" data-sortable="true" data-filter-control="input" class="distribution_status"><?php echo __('Distribution Status',CIP_TXTDOMAIN); ?></th>
												<!-- <th data-field="corp_approved" data-sortable="true" data-filter-control="input" class="corp_approved"><?php echo __('Corp Approved',CIP_TXTDOMAIN); ?></th> -->
												<th data-field="week_number" data-sortable="true" data-filter-control="input" class="week_number"><?php echo __('Week Number',CIP_TXTDOMAIN); ?></th>
												<!-- <th data-field="member_status" data-sortable="true" data-filter-control="input" class="member_status"><?php echo __('Member Status',CIP_TXTDOMAIN); ?></th> -->
												<th data-field="pool_ref" data-sortable="true" data-filter-control="input" class="pool_ref"><?php echo __('Pool Reference ',CIP_TXTDOMAIN); ?></th>
												<th data-field="source" data-sortable="true" data-filter-control="input" class="source"><?php echo __('Source ',CIP_TXTDOMAIN); ?></th>
												</tr>
											</thead>
											<tbody></tbody>
										</table>
									</div>
								</div>
	                        </div>
							<input type="button" name="next" class="next action-button" value="Append Data" />
							<input type="button" name="previous" class="previous action-button-previous back_disable" value="Previous" />
	                    </fieldset>
	                    <fieldset class="step_6">
							<?php
								$tableDistribution = $wpdb->prefix.'new_delivery_plan';
								$getDistributions = $wpdb->get_var("SELECT COUNT(id) FROM $tableDistribution WHERE `append_status` = 1");
								$getDistributionsSummary = $wpdb->get_row("SELECT * FROM $tableDistribution WHERE `append_status` = 1 ORDER BY `id` DESC");
								$getDistributionsData = $wpdb->get_results("SELECT * FROM $tableDistribution WHERE `append_status` = 1 AND `csr_amount_issued` > 0");
								$totalRedemptions = 0;
								$totalCsr = 0;
								if( $getDistributionsData ){
									foreach( $getDistributionsData as $distribution ){
										$totalCsr += $distribution->csr_amount_initial;
										$totalRedemptions++;
									}
								}
							?>
	                        <div class="form-card">
	                            <div class="row">
	                                <div class="col-12">
	                                    <h2 class="steps"><?php echo sprintf('Step %s - %s', 7, $total_step); ?></h2>
	                                </div>
	                            </div>
	                            <div class="row justify-content-center">
									<div class="col-12 text-center">
									<h4><?php _e('Append New <span class="token_type_label">CSR25</span> Holders Data', CIP_TXTDOMAIN); ?></h4>
									<div class="summary_data_at_append_step">
										<?php if( $getDistributions > 0 && $getDistributionsSummary->import_by && $getDistributionsSummary->import_date ){
											$userData = get_user_by( 'id', $getDistributionsSummary->import_by );
											if( $userData ){
												echo '<p>'. sprintf( __('Data imported by : %s', CIP_TXTDOMAIN), $userData->user_login ) .'</p>';
											}
											$import_date = '—';
											try {
												$import_date_obj = DateTime::createFromFormat('Y-m-d H:i:s', $getDistributionsSummary->import_date);
												$import_date = $import_date_obj->format('d/m/Y H:i');
											} catch (\Throwable $th) {
												$import_date = '—';
											}
											echo '<p>'. sprintf( __('Import date : %s', CIP_TXTDOMAIN), $import_date ) .'</p>';
										} ?>
									</div>
									<button type="button" class="btn btn-outline-primary append_new_delivery_plan_csr_holders_data_button"><?php _e('Confirm Append Data',CIP_TXTDOMAIN); ?></button>
									<button type="button" class="btn btn-outline-primary append_new_delivery_plan_cancel"><?php _e('Cancel',CIP_TXTDOMAIN); ?></button>
									</div>
									<div class="col-12">
										<ul class="list-group list-group-flush process_split_append_log" id="process_split_append_log"></ul>
										<div class="csr_split_append_spinner" style="display: none;">
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
										</div>
									</div>
									<div class="col-12">
										<ul class="list-group list-group-flush process_split_append_user_status_log" id="process_split_append_user_status_log"></ul>
										<div class="csr_split_append_user_status_spinner" style="display: none;">
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
											<div class="spinner-grow spinner-grow-sm text-primary"></div>
										</div>
									</div>
								</div>
	                        </div>
							<input type="button" name="next" class="next action-button finish_step d-none invisible" value="Next" />
							<input type="button" name="previous" class="previous action-button-previous" value="Previous" />
	                    </fieldset>
						<fieldset class="step_7">
	                        <div class="form-card">
	                            <div class="row">
	                                <div class="col-12">
	                                    <h2 class="steps"><?php echo sprintf('Step %s - %s', 8, $total_step); ?></h2>
	                                </div>
	                            </div>
								<div class="row">
									<div class="col-12">
										<h4 class="text-center"><strong><i class="fa fa-check-circle"></i> <?php echo __('New delivery plan wizard completed.', CIP_TXTDOMAIN); ?></strong></h4>
										<p class="text-center append_response fw-bold"></p>
										<a class="btn button action-button" href="<?php echo get_permalink( 9099 ); ?>"><?php echo __('Okay', CIP_TXTDOMAIN); ?></a>
									</div>
	                            </div>
	                        </div>
	                    </fieldset>
	                    <input type="hidden" name="action" value="cip_new_delivery_plan_wizard_act" />
	                    <input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPxYSMNewDeliveryPlanWizardMSYxCIP_'); ?>" />
	                </form>
					<form class="append_new_delivery_plan_csr_holders_data_frm" id="append_new_delivery_plan_csr_holders_data_frm">
						<input type="hidden" name="action" value="append_new_delivery_plan_csr_holders_data_act">
						<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XYAppendNew_csr_HoldersDataYX_'); ?>">
					</form>
					<form class="append_new_delivery_plan_cancel_data_frm" id="append_new_delivery_plan_cancel_data_frm">
						<input type="hidden" name="action" value="cancel_new_delivery_plan_append_process">
						<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XYCancelAppendDataYX_'); ?>">
					</form>
				</div>
			</div>
		</div>
	</div>
	<?php
	$html .= ob_get_clean();
	return $html;
}
//script for new delivery plan wizard
add_action( 'wp_footer', 'scripts_new_delivery_plan_wizard_callback' );
function scripts_new_delivery_plan_wizard_callback(){
	$new_delivery_plan_distribution_url = add_query_arg( [
		'action'	=>	'new_delivery_plan_distribution_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$new_delivery_plan_distribution_10_url = add_query_arg( [
		'action'	=>	'new_delivery_plan_distribution_10_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$new_delivery_plan_distribution_promotion_url = add_query_arg( [
		'action'	=>	'new_delivery_plan_distribution_promotion_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
?>
<script>
jQuery(document).ready(function($){
	if( $('.new_delivery_plan_wizard').length > 0 ){
		var notifyErrorOpt = {position:"top",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
		var notifyErrorBottomOpt = {position:"bottom",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
		var block_config_ndp = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };
		var current_fs_ndp, next_fs_ndp, previous_fs_ndp; //fieldsets
		var opacity_ndp;
		var current_ndp = 1;
		var steps_ndp = $(".new_delivery_plan_wizard fieldset").length;
		var $form_ndp = $('.new_delivery_plan_wizard');
		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 = "";
		setProgressBarNdp(current_ndp);
		$(".new_delivery_plan_wizard .next").click(function(){
			var this_next = $(this);
			current_fs_ndp = $(this).closest('fieldset');
			next_fs_ndp = $(this).closest('fieldset').next();
			// console.log( current_ndp );
			if( current_ndp == 1 ){ //importing or updating user
				var th_csv_file = $('body').find('.new_delivery_plan_wizard input[name="th_csv_file"]').val();
				if( typeof th_csv_file  === "undefined" || th_csv_file == "" ){
					$(this).notify( 'Please choose file', notifyErrorOpt );
					return false;
				}
				var advanced_weekly_wizard_option = $("input[name='advanced_weekly_wizard_option']:checked").val();

				var week_wise_advanced = $("input[name='week_wise_advanced']:checked").val();

				var pool_reference = $('.new_delivery_plan_wizard input[name="pool_reference"]').val();
				if( pool_reference == "" ){
					$('.new_delivery_plan_wizard input[name="pool_reference"]').notify( 'Pool reference is required', notifyErrorOpt );
					return false;
				}

				if( week_wise_advanced == 'normal' ){
					
					if( advanced_weekly_wizard_option != 'advanced' ){
						var csr_segmentation = $('.new_delivery_plan_wizard input[name="csr_segmentation"]').val();
						if( csr_segmentation == "" ){
							$('.new_delivery_plan_wizard input[name="csr_segmentation"]').notify( 'CSR Segmentation is required', notifyErrorOpt );
							return false;
						}
						if( !jQuery.isNumeric( csr_segmentation )  ){
							$('.new_delivery_plan_wizard input[name="csr_segmentation"]').notify( 'Please enter valid CSR Segmentation', notifyErrorOpt );
							return false;
						}
						if( csr_segmentation != "" && parseInt( csr_segmentation ) < 10 ){
							$('.new_delivery_plan_wizard input[name="csr_segmentation"]').notify( 'Minimum CSR Segmentation is 10', notifyErrorOpt );
							return false;
						}
						var primary_number_of_deliveries = $('.new_delivery_plan_wizard select[name="primary_number_of_deliveries"]').val();
						if( primary_number_of_deliveries == "" ){
							$('.new_delivery_plan_wizard select[name="primary_number_of_deliveries"]').notify( 'Primary CSR: Number of deliveries is required', notifyErrorOpt );
							return false;
						}
						if( !jQuery.isNumeric( primary_number_of_deliveries )  ){
							$('.new_delivery_plan_wizard select[name="primary_number_of_deliveries"]').notify( 'Primary CSR: Please enter valid Number of deliveries', notifyErrorOpt );
							return false;
						}
						if( primary_number_of_deliveries != "" && parseInt( primary_number_of_deliveries ) < 1 ){
							$('.new_delivery_plan_wizard select[name="primary_number_of_deliveries"]').notify( 'Primary CSR: Minimum Number of deliveries is 1', notifyErrorOpt );
							return false;
						}
						if( primary_number_of_deliveries != "" && parseInt( primary_number_of_deliveries ) > 10 ){
							$('.new_delivery_plan_wizard select[name="primary_number_of_deliveries"]').notify( 'Primary CSR: Maximim Number of deliveries is 10', notifyErrorOpt );
							return false;
						}
						var primary_delivery_interval = $('.new_delivery_plan_wizard select[name="primary_delivery_interval"]').val();
						if( primary_delivery_interval == "" ){
							$('.new_delivery_plan_wizard select[name="primary_delivery_interval"]').notify( 'Primary CSR: Delivery interval is required', notifyErrorOpt );
							return false;
						}
						if( !jQuery.isNumeric( primary_delivery_interval )  ){
							$('.new_delivery_plan_wizard select[name="primary_delivery_interval"]').notify( 'Primary CSR: Please enter valid Delivery interval', notifyErrorOpt );
							return false;
						}
						if( primary_delivery_interval != "" && parseInt( primary_delivery_interval ) < 1 ){
							$('.new_delivery_plan_wizard select[name="primary_delivery_interval"]').notify( 'Primary CSR: Minimum Delivery interval is 1', notifyErrorOpt );
							return false;
						}
						if( primary_delivery_interval != "" && parseInt( primary_delivery_interval ) > 10 ){
							$('.new_delivery_plan_wizard select[name="primary_delivery_interval"]').notify( 'Primary CSR: Maximim Delivery interval is 10', notifyErrorOpt );
							return false;
						}
						var primary_delivery_start_week = $('.new_delivery_plan_wizard input[name="primary_delivery_start_week"]').val();
						if( primary_delivery_start_week == "" ){
							$('.new_delivery_plan_wizard input[name="primary_delivery_start_week"]').notify( 'Primary CSR: Delivery start week is required', notifyErrorOpt );
							return false;
						}
						if( !jQuery.isNumeric( primary_delivery_start_week )  ){
							$('.new_delivery_plan_wizard input[name="primary_delivery_start_week"]').notify( 'Primary CSR: Please enter valid Delivery start week', notifyErrorOpt );
							return false;
						}
						if( primary_delivery_start_week != "" && parseInt( primary_delivery_start_week ) < 0 ){
							$('.new_delivery_plan_wizard input[name="primary_delivery_start_week"]').notify( 'Primary CSR: Minimum Delivery start week is 0', notifyErrorOpt );
							return false;
						}
						if( primary_delivery_start_week != "" && parseInt( primary_delivery_start_week ) > 200 ){
							$('.new_delivery_plan_wizard input[name="primary_delivery_start_week"]').notify( 'Primary CSR: Maximim Delivery start week is 200', notifyErrorOpt );
							return false;
						}
						var promotion_type = $('.new_delivery_plan_wizard select[name="promotion_type"]').val();
						var bonus_percentage = $('.new_delivery_plan_wizard input[name="bonus_percentage"]').val();
						var discount_percentage = $('.new_delivery_plan_wizard input[name="discount_percentage"]').val();
						if( promotion_type == 'bonus' ){
							if( bonus_percentage == "" ){
								$('.new_delivery_plan_wizard input[name="bonus_percentage"]').notify( 'Bonus Percentage is required', notifyErrorOpt );
								return false;
							}
							if( !jQuery.isNumeric( bonus_percentage )  ){
								$('.new_delivery_plan_wizard input[name="bonus_percentage"]').notify( 'Please enter valid Bonus Percentage', notifyErrorOpt );
								return false;
							}
							if( bonus_percentage != "" && parseInt( bonus_percentage ) < 1 ){
								$('.new_delivery_plan_wizard input[name="bonus_percentage"]').notify( 'Minimum Bonus Percentage is 1', notifyErrorOpt );
								return false;
							}
						}else if( promotion_type == 'discount' ){
							if( discount_percentage == "" ){
								$('.new_delivery_plan_wizard input[name="discount_percentage"]').notify( 'Discount Percentage is required', notifyErrorOpt );
								return false;
							}
							if( !jQuery.isNumeric( discount_percentage )  ){
								$('.new_delivery_plan_wizard input[name="discount_percentage"]').notify( 'Please enter valid Discount Percentage', notifyErrorOpt );
								return false;
							}
							if( discount_percentage != "" && parseInt( discount_percentage ) < 1 ){
								$('.new_delivery_plan_wizard input[name="discount_percentage"]').notify( 'Minimum Discount Percentage is 1', notifyErrorOpt );
								return false;
							}
							if( discount_percentage != "" && parseInt( discount_percentage ) > 99 ){
								$('.new_delivery_plan_wizard input[name="discount_percentage"]').notify( 'Maximum Discount Percentage is 99', notifyErrorOpt );
								return false;
							}
						}
						if( promotion_type == 'bonus' || promotion_type == 'discount' ){
							var promotion_number_of_deliveries = $('.new_delivery_plan_wizard select[name="promotion_number_of_deliveries"]').val();
							if( promotion_number_of_deliveries == "" ){
								$('.new_delivery_plan_wizard select[name="promotion_number_of_deliveries"]').notify( 'Promotion CSR: Number of deliveries is required', notifyErrorOpt );
								return false;
							}
							if( !jQuery.isNumeric( promotion_number_of_deliveries )  ){
								$('.new_delivery_plan_wizard select[name="promotion_number_of_deliveries"]').notify( 'Promotion CSR: Please enter valid Number of deliveries', notifyErrorOpt );
								return false;
							}
							if( promotion_number_of_deliveries != "" && parseInt( promotion_number_of_deliveries ) < 1 ){
								$('.new_delivery_plan_wizard select[name="promotion_number_of_deliveries"]').notify( 'Promotion CSR: Minimum Number of deliveries is 1', notifyErrorOpt );
								return false;
							}
							if( promotion_number_of_deliveries != "" && parseInt( promotion_number_of_deliveries ) > 10 ){
								$('.new_delivery_plan_wizard select[name="promotion_number_of_deliveries"]').notify( 'Promotion CSR: Maximim Number of deliveries is 10', notifyErrorOpt );
								return false;
							}
							var promotion_delivery_interval = $('.new_delivery_plan_wizard select[name="promotion_delivery_interval"]').val();
							if( promotion_delivery_interval == "" ){
								$('.new_delivery_plan_wizard select[name="promotion_delivery_interval"]').notify( 'Promotion CSR: Delivery interval is required', notifyErrorOpt );
								return false;
							}
							if( !jQuery.isNumeric( promotion_delivery_interval )  ){
								$('.new_delivery_plan_wizard select[name="promotion_delivery_interval"]').notify( 'Promotion CSR: Please enter valid Delivery interval', notifyErrorOpt );
								return false;
							}
							if( promotion_delivery_interval != "" && parseInt( promotion_delivery_interval ) < 1 ){
								$('.new_delivery_plan_wizard select[name="promotion_delivery_interval"]').notify( 'Promotion CSR: Minimum Delivery interval is 1', notifyErrorOpt );
								return false;
							}
							if( promotion_delivery_interval != "" && parseInt( promotion_delivery_interval ) > 10 ){
								$('.new_delivery_plan_wizard select[name="promotion_delivery_interval"]').notify( 'Promotion CSR: Maximim Delivery interval is 10', notifyErrorOpt );
								return false;
							}
							var promotion_delivery_start_week = $('.new_delivery_plan_wizard input[name="promotion_delivery_start_week"]').val();
							if( promotion_delivery_start_week == "" ){
								$('.new_delivery_plan_wizard input[name="promotion_delivery_start_week"]').notify( 'Promotion CSR: Delivery start week is required', notifyErrorOpt );
								return false;
							}
							if( !jQuery.isNumeric( promotion_delivery_start_week )  ){
								$('.new_delivery_plan_wizard input[name="promotion_delivery_start_week"]').notify( 'Promotion CSR: Please enter valid Delivery start week', notifyErrorOpt );
								return false;
							}
							if( promotion_delivery_start_week != "" && parseInt( promotion_delivery_start_week ) < 0 ){
								$('.new_delivery_plan_wizard input[name="promotion_delivery_start_week"]').notify( 'Promotion CSR: Minimum Delivery start week is 0', notifyErrorOpt );
								return false;
							}
							if( promotion_delivery_start_week != "" && parseInt( promotion_delivery_start_week ) > 200 ){
								$('.new_delivery_plan_wizard input[name="promotion_delivery_start_week"]').notify( 'Promotion CSR: Maximim Delivery start week is 200', notifyErrorOpt );
								return false;
							}
						}
					}

					// advanced option
					var advanced_weekly_wizard_option = $("input[name='advanced_weekly_wizard_option']:checked").val();
					if( advanced_weekly_wizard_option == 'advanced' ){
						var isAdvancedError = false;
						$('.csrSegmentation').each(function(index,data) {
							var csrSegmentation = $(this).val();
							if( csrSegmentation == "" ){
								isAdvancedError = true;
								$('.advanced_options_table_data table').notify( 'CSR Segmentation is required', notifyErrorBottomOpt );
								return false;
							}
							if( !jQuery.isNumeric( csrSegmentation )  ){
								isAdvancedError = true;
								$('.advanced_options_table_data table').notify( 'Please enter valid CSR Segmentation', notifyErrorBottomOpt );
								return false;
							}
							if( csrSegmentation != "" && parseInt( csrSegmentation ) < 10 ){
								isAdvancedError = true;
								$('.advanced_options_table_data table').notify( 'Minimum CSR Segmentation is 10', notifyErrorBottomOpt );
								return false;
							}
						});
						if( !isAdvancedError ){
							$('.primaryDeliveryStartWeek').each(function(index,data) {
								var primaryDeliveryStartWeek = $(this).val();
								if( primaryDeliveryStartWeek == "" ){
									isAdvancedError = true;
									$('.advanced_options_table_data table').notify( 'Primary CSR: Delivery start week is required', notifyErrorBottomOpt );
									return false;
								}
								if( !jQuery.isNumeric( primaryDeliveryStartWeek )  ){
									isAdvancedError = true;
									$('.advanced_options_table_data table').notify( 'Primary CSR: Please enter valid Delivery start week', notifyErrorBottomOpt );
									return false;
								}
								if( primaryDeliveryStartWeek != "" && parseInt( primaryDeliveryStartWeek ) < 0 ){
									isAdvancedError = true;
									$('.advanced_options_table_data table').notify( 'Primary CSR: Minimum Delivery start week is 0', notifyErrorBottomOpt );
									return false;
								}
								if( primaryDeliveryStartWeek != "" && parseInt( primaryDeliveryStartWeek ) > 200 ){
									isAdvancedError = true;
									$('.advanced_options_table_data table').notify( 'Primary CSR: Maximim Delivery start week is 200', notifyErrorBottomOpt );
									return false;
								}
							});
						}
						if( !isAdvancedError ){
							$('.promotionType').each(function(index,data) {
								var promotionType = $(this).val();
								var promotionTypeIndex = $(this).attr('data-index');
								var promotionPercentage = $('.promotionPercentage[data-index='+ promotionTypeIndex +']').val();
								if( promotionType == 'bonus' ){
									if( promotionPercentage == "" ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Promotion Percentage is required', notifyErrorBottomOpt );
										return false;
									}
									if( !jQuery.isNumeric( promotionPercentage )  ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Please enter valid Promotion Percentage', notifyErrorBottomOpt );
										return false;
									}
									if( promotionPercentage != "" && parseInt( promotionPercentage ) < 1 ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Minimum Promotion Percentage is 1', notifyErrorBottomOpt );
										return false;
									}
								}else if( promotionType == 'discount' ){
									if( promotionPercentage == "" ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Promotion Percentage is required', notifyErrorBottomOpt );
										return false;
									}
									if( !jQuery.isNumeric( promotionPercentage )  ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Please enter valid Promotion Percentage', notifyErrorBottomOpt );
										return false;
									}
									if( promotionPercentage != "" && parseInt( promotionPercentage ) < 1 ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Minimum Promotion Percentage is 1', notifyErrorBottomOpt );
										return false;
									}
									if( promotionPercentage != "" && parseInt( promotionPercentage ) > 99 ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Maximum Promotion Percentage is 99', notifyErrorBottomOpt );
										return false;
									}
								}
							});
						}
						if( !isAdvancedError ){
							$('.promotionType').each(function(index,data) {
								var promotionType = $(this).val();
								var promotionTypeIndex = $(this).attr('data-index');
								var promotionDeliveryStartWeek = $('.promotionDeliveryStartWeek[data-index='+ promotionTypeIndex +']').val();
								if( promotionType == 'bonus' || promotionType == 'discount' ){
									if( promotionDeliveryStartWeek == "" ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Promotion CSR: Delivery start week is required', notifyErrorBottomOpt );
										return false;
									}
									if( !jQuery.isNumeric( promotionDeliveryStartWeek )  ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Promotion CSR: Please enter valid Delivery start week', notifyErrorBottomOpt );
										return false;
									}
									if( promotionDeliveryStartWeek != "" && parseInt( promotionDeliveryStartWeek ) < 0 ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Promotion CSR: Minimum Delivery start week is 0', notifyErrorBottomOpt );
										return false;
									}
									if( promotionDeliveryStartWeek != "" && parseInt( promotionDeliveryStartWeek ) > 200 ){
										isAdvancedError = true;
										$('.advanced_options_table_data table').notify( 'Promotion CSR: Maximim Delivery start week is 200', notifyErrorBottomOpt );
										return false;
									}
								}
							});
						}
						if( isAdvancedError ){
							return false;
						}
					}

				}else{	//week wise option selected

					var week_wise_advanced_weekly_wizard_option = $("input[name='week_wise_advanced_weekly_wizard_option']:checked").val();
					if( week_wise_advanced_weekly_wizard_option != 'advanced' ){
						var csr_segmentation = $('.new_delivery_plan_wizard input[name="csr_segmentation"]').val();
						if( csr_segmentation == "" ){
							$('.new_delivery_plan_wizard input[name="csr_segmentation"]').notify( 'CSR Segmentation is required', notifyErrorOpt );
							return false;
						}
						if( !jQuery.isNumeric( csr_segmentation )  ){
							$('.new_delivery_plan_wizard input[name="csr_segmentation"]').notify( 'Please enter valid CSR Segmentation', notifyErrorOpt );
							return false;
						}
						if( csr_segmentation != "" && parseInt( csr_segmentation ) < 10 ){
							$('.new_delivery_plan_wizard input[name="csr_segmentation"]').notify( 'Minimum CSR Segmentation is 10', notifyErrorOpt );
							return false;
						}
						
						var week_wise_primary_number_of_deliveries = $('.new_delivery_plan_wizard select[name="week_wise_primary_number_of_deliveries"]').val();
						if( week_wise_primary_number_of_deliveries == "" ){
							$('.new_delivery_plan_wizard select[name="week_wise_primary_number_of_deliveries"]').notify( 'Primary CSR: Number of deliveries is required', notifyErrorOpt );
							return false;
						}
						if( !jQuery.isNumeric( week_wise_primary_number_of_deliveries )  ){
							$('.new_delivery_plan_wizard select[name="week_wise_primary_number_of_deliveries"]').notify( 'Primary CSR: Please enter valid Number of deliveries', notifyErrorOpt );
							return false;
						}
						if( week_wise_primary_number_of_deliveries != "" && parseInt( week_wise_primary_number_of_deliveries ) < 1 ){
							$('.new_delivery_plan_wizard select[name="week_wise_primary_number_of_deliveries"]').notify( 'Primary CSR: Minimum Number of deliveries is 1', notifyErrorOpt );
							return false;
						}
						if( week_wise_primary_number_of_deliveries != "" && parseInt( week_wise_primary_number_of_deliveries ) > 10 ){
							$('.new_delivery_plan_wizard select[name="primary_number_of_deliveries"]').notify( 'Primary CSR: Maximim Number of deliveries is 10', notifyErrorOpt );
							return false;
						}
						


						var totalWeekWiseRedemptionPercentage = 0;
						var weekWisePrimaryIndexTableSectionElem = $('body').find('.week_wise_primary_index_table_section');
						for( var i = 1; i <= week_wise_primary_number_of_deliveries; i++ ){
							var thisElement = $( '.week_wise_primary_index_' + i + '.show' );
							var thisWeekWiseWeekIndex = thisElement.find('.week_wise_week_index').val();
							var thisWeekWiseRedemptionPercentage = thisElement.find('.week_wise_redemption_percentage').val();

							totalWeekWiseRedemptionPercentage += parseInt( thisWeekWiseRedemptionPercentage );

							if( thisWeekWiseWeekIndex == "" ){
								weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Delivery start week number is required', notifyErrorOpt );
								return false;
								break;
							}
							if( !jQuery.isNumeric( thisWeekWiseWeekIndex )  ){
								weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Please enter valid Delivery start week', notifyErrorOpt );
								return false;
								break;
							}
							if( thisWeekWiseWeekIndex != "" && parseInt( thisWeekWiseWeekIndex ) < 0 ){
								weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Minimum Delivery start week is 0', notifyErrorOpt );
								return false;
								break;
							}
							if( thisWeekWiseWeekIndex != "" && parseInt( thisWeekWiseWeekIndex ) > 200 ){
								weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Maximim Delivery start week is 200', notifyErrorOpt );
								return false;
								break;
							}
							//======================//
							if( thisWeekWiseRedemptionPercentage == "" ){
								weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Redemption percentage is required', notifyErrorOpt );
								return false;
								break;
							}
							if( !jQuery.isNumeric( thisWeekWiseRedemptionPercentage )  ){
								weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Please enter valid redemption percentage', notifyErrorOpt );
								return false;
								break;
							}
							if( thisWeekWiseRedemptionPercentage != "" && parseInt( thisWeekWiseRedemptionPercentage ) < 1 ){
								weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Minimum redemption percentage is 1', notifyErrorOpt );
								return false;
								break;
							}
							if( thisWeekWiseRedemptionPercentage != "" && parseInt( thisWeekWiseRedemptionPercentage ) > 100 ){
								weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Maximim redemption percentage is 100', notifyErrorOpt );
								return false;
								break;
							}
						}

						if( totalWeekWiseRedemptionPercentage != 100 ){
							weekWisePrimaryIndexTableSectionElem.notify( 'Primary CSR: Invalid redemption percentage.', notifyErrorOpt );
							return false;
						}

						var week_wise_promotion_type = $('.new_delivery_plan_wizard select[name="week_wise_promotion_type"]').val();
						var week_wise_bonus_percentage = $('.new_delivery_plan_wizard input[name="week_wise_bonus_percentage"]').val();
						var week_wise_discount_percentage = $('.new_delivery_plan_wizard input[name="week_wise_discount_percentage"]').val();
						if( week_wise_promotion_type == 'bonus' ){
							if( week_wise_bonus_percentage == "" ){
								$('.new_delivery_plan_wizard input[name="week_wise_bonus_percentage"]').notify( 'Bonus Percentage is required', notifyErrorOpt );
								return false;
							}
							if( !jQuery.isNumeric( week_wise_bonus_percentage )  ){
								$('.new_delivery_plan_wizard input[name="week_wise_bonus_percentage"]').notify( 'Please enter valid Bonus Percentage', notifyErrorOpt );
								return false;
							}
							if( week_wise_bonus_percentage != "" && parseInt( week_wise_bonus_percentage ) < 1 ){
								$('.new_delivery_plan_wizard input[name="week_wise_bonus_percentage"]').notify( 'Minimum Bonus Percentage is 1', notifyErrorOpt );
								return false;
							}
						}else if( week_wise_promotion_type == 'discount' ){
							if( week_wise_discount_percentage == "" ){
								$('.new_delivery_plan_wizard input[name="week_wise_discount_percentage"]').notify( 'Discount Percentage is required', notifyErrorOpt );
								return false;
							}
							if( !jQuery.isNumeric( week_wise_discount_percentage )  ){
								$('.new_delivery_plan_wizard input[name="week_wise_discount_percentage"]').notify( 'Please enter valid Discount Percentage', notifyErrorOpt );
								return false;
							}
							if( week_wise_discount_percentage != "" && parseInt( week_wise_discount_percentage ) < 1 ){
								$('.new_delivery_plan_wizard input[name="week_wise_discount_percentage"]').notify( 'Minimum Discount Percentage is 1', notifyErrorOpt );
								return false;
							}
							if( week_wise_discount_percentage != "" && parseInt( week_wise_discount_percentage ) > 99 ){
								$('.new_delivery_plan_wizard input[name="week_wise_discount_percentage"]').notify( 'Maximum Discount Percentage is 99', notifyErrorOpt );
								return false;
							}
						}

						if( week_wise_promotion_type == 'bonus' || week_wise_promotion_type == 'discount' ){
							var week_wise_promotion_number_of_deliveries = $('.new_delivery_plan_wizard select[name="week_wise_promotion_number_of_deliveries"]').val();
							if( week_wise_promotion_number_of_deliveries == "" ){
								$('.new_delivery_plan_wizard select[name="week_wise_promotion_number_of_deliveries"]').notify( 'Promotion CSR: Number of deliveries is required', notifyErrorOpt );
								return false;
							}
							if( !jQuery.isNumeric( week_wise_promotion_number_of_deliveries )  ){
								$('.new_delivery_plan_wizard select[name="week_wise_promotion_number_of_deliveries"]').notify( 'Promotion CSR: Please enter valid Number of deliveries', notifyErrorOpt );
								return false;
							}
							if( week_wise_promotion_number_of_deliveries != "" && parseInt( week_wise_promotion_number_of_deliveries ) < 1 ){
								$('.new_delivery_plan_wizard select[name="week_wise_promotion_number_of_deliveries"]').notify( 'Promotion CSR: Minimum Number of deliveries is 1', notifyErrorOpt );
								return false;
							}
							if( week_wise_promotion_number_of_deliveries != "" && parseInt( week_wise_promotion_number_of_deliveries ) > 10 ){
								$('.new_delivery_plan_wizard select[name="week_wise_promotion_number_of_deliveries"]').notify( 'Promotion CSR: Maximim Number of deliveries is 10', notifyErrorOpt );
								return false;
							}
							
							var weekWisePromotionIndexTableSection = $('body').find('.week_wise_promotion_index_table_section');
							var totalWeekWisePromotionRedemptionPercentage = 0;
							for( var i = 1; i <= week_wise_promotion_number_of_deliveries; i++ ){
								var thisElement = $( '.week_wise_promotion_index_' + i + '.show' );
								var thisWeekWisePromotionWeekIndex = thisElement.find('.week_wise_promotion_week_index').val();
								var thisWeekWisePromotionRedemptionPercentage = thisElement.find('.week_wise_promotion_redemption_percentage').val();

								totalWeekWisePromotionRedemptionPercentage += parseInt( thisWeekWisePromotionRedemptionPercentage );

								if( thisWeekWisePromotionWeekIndex == "" ){
									weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Delivery start week number is required', notifyErrorOpt );
									return false;
									break;
								}
								if( !jQuery.isNumeric( thisWeekWisePromotionWeekIndex )  ){
									weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Please enter valid Delivery start week', notifyErrorOpt );
									return false;
									break;
								}
								if( thisWeekWisePromotionWeekIndex != "" && parseInt( thisWeekWisePromotionWeekIndex ) < 0 ){
									weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Minimum Delivery start week is 0', notifyErrorOpt );
									return false;
									break;
								}
								if( thisWeekWisePromotionWeekIndex != "" && parseInt( thisWeekWisePromotionWeekIndex ) > 200 ){
									weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Maximim Delivery start week is 200', notifyErrorOpt );
									return false;
									break;
								}
								//======================//
								if( thisWeekWisePromotionRedemptionPercentage == "" ){
									weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Redemption percentage is required', notifyErrorOpt );
									return false;
									break;
								}
								if( !jQuery.isNumeric( thisWeekWisePromotionRedemptionPercentage )  ){
									weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Please enter valid redemption percentage', notifyErrorOpt );
									return false;
									break;
								}
								if( thisWeekWisePromotionRedemptionPercentage != "" && parseInt( thisWeekWisePromotionRedemptionPercentage ) < 1 ){
									weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Minimum redemption percentage is 1', notifyErrorOpt );
									return false;
									break;
								}
								if( thisWeekWisePromotionRedemptionPercentage != "" && parseInt( thisWeekWisePromotionRedemptionPercentage ) > 100 ){
									weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Maximim redemption percentage is 100', notifyErrorOpt );
									return false;
									break;
								}
							}

							if( totalWeekWisePromotionRedemptionPercentage != 100 ){
								weekWisePromotionIndexTableSection.notify( 'Promotion CSR: Invalid redemption percentage.', notifyErrorOpt );
								return false;
							}
							
						}
					}

					//week wise advanced option
					var week_wise_advanced_weekly_wizard_option = $("input[name='week_wise_advanced_weekly_wizard_option']:checked").val();
					if( week_wise_advanced_weekly_wizard_option == 'advanced' ){
						var isAdvancedError = false;
						$('.week_wise_advanced_options_table_data .csrSegmentation').each(function(index,data) {
							var csrSegmentation = $(this).val();
							if( csrSegmentation == "" ){
								isAdvancedError = true;
								$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'CSR Segmentation is required', notifyErrorBottomOpt );
								return false;
							}
							if( !jQuery.isNumeric( csrSegmentation )  ){
								isAdvancedError = true;
								$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Please enter valid CSR Segmentation', notifyErrorBottomOpt );
								return false;
							}
							if( csrSegmentation != "" && parseInt( csrSegmentation ) < 10 ){
								isAdvancedError = true;
								$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Minimum CSR Segmentation is 10', notifyErrorBottomOpt );
								return false;
							}
						});
						if( !isAdvancedError ){
							$('.week_wise_advanced_options_table_data .primaryDeliveryStartWeek').each(function(index,data) {
								var primaryDeliveryStartWeek = $(this).val();
								if( primaryDeliveryStartWeek == "" ){
									isAdvancedError = true;
									$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Primary CSR: Delivery start week is required', notifyErrorBottomOpt );
									return false;
								}
								if( !jQuery.isNumeric( primaryDeliveryStartWeek )  ){
									isAdvancedError = true;
									$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Primary CSR: Please enter valid Delivery start week', notifyErrorBottomOpt );
									return false;
								}
								if( primaryDeliveryStartWeek != "" && parseInt( primaryDeliveryStartWeek ) < 0 ){
									isAdvancedError = true;
									$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Primary CSR: Minimum Delivery start week is 0', notifyErrorBottomOpt );
									return false;
								}
								if( primaryDeliveryStartWeek != "" && parseInt( primaryDeliveryStartWeek ) > 200 ){
									isAdvancedError = true;
									$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Primary CSR: Maximim Delivery start week is 200', notifyErrorBottomOpt );
									return false;
								}
							});
						}
						if( !isAdvancedError ){
							$('.week_wise_advanced_options_table_data .week_wise_advanced_promotionType').each(function(index,data) {
								var promotionType = $(this).val();
								var promotionTypeIndex = $(this).attr('data-index');
								var promotionPercentage = $('.week_wise_advanced_options_table_data .promotionPercentage[data-index='+ promotionTypeIndex +']').val();
								if( promotionType == 'bonus' ){
									if( promotionPercentage == "" ){
										isAdvancedError = true;
										$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Promotion Percentage is required', notifyErrorBottomOpt );
										return false;
									}
									if( !jQuery.isNumeric( promotionPercentage )  ){
										isAdvancedError = true;
										$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Please enter valid Promotion Percentage', notifyErrorBottomOpt );
										return false;
									}
									if( promotionPercentage != "" && parseInt( promotionPercentage ) < 1 ){
										isAdvancedError = true;
										$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Minimum Promotion Percentage is 1', notifyErrorBottomOpt );
										return false;
									}
								}else if( promotionType == 'discount' ){
									if( promotionPercentage == "" ){
										isAdvancedError = true;
										$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Promotion Percentage is required', notifyErrorBottomOpt );
										return false;
									}
									if( !jQuery.isNumeric( promotionPercentage )  ){
										isAdvancedError = true;
										$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Please enter valid Promotion Percentage', notifyErrorBottomOpt );
										return false;
									}
									if( promotionPercentage != "" && parseInt( promotionPercentage ) < 1 ){
										isAdvancedError = true;
										$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Minimum Promotion Percentage is 1', notifyErrorBottomOpt );
										return false;
									}
									if( promotionPercentage != "" && parseInt( promotionPercentage ) > 99 ){
										isAdvancedError = true;
										$('.week_wise_advanced_options_table_data table.week_wise_advanced_weekly_option_html').notify( 'Maximum Promotion Percentage is 99', notifyErrorBottomOpt );
										return false;
									}
								}
							});
						}
						if( !isAdvancedError ){
							
							$('.week_wise_advanced_options_table_data .primaryDeliveries').each(function(index,data) {
								var primaryDeliveries = $(this).val();
								var primaryDeliveriesIndex = $(this).attr('data-index');
								var primaryDeliveriesSectionElement = $('.week_wise_advanced_options_table_data .week_wise_advanced_primary_section[data-index='+ primaryDeliveriesIndex +']');
								
								var totalWeekWiseAdvancedRedemptionPercentage = 0;
								for( var i = 1; i <= primaryDeliveries; i++ ){
									var thisElement = primaryDeliveriesSectionElement.find( '.week_wise_advanced_primary_index_' + i + '.show' );
									var thisWeekWiseAdvancedWeekIndex = thisElement.find('.week_wise_advanced_week_index').val();
									var thisWeekWiseAdvancedRedemptionPercentage = thisElement.find('.week_wise_advanced_redemption_percentage').val();
	
									totalWeekWiseAdvancedRedemptionPercentage += parseInt( thisWeekWiseAdvancedRedemptionPercentage );
	
									if( thisWeekWiseAdvancedWeekIndex == "" ){
										primaryDeliveriesSectionElement.notify( 'Primary CSR: Delivery start week number is required', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
										break;
									}
									if( !jQuery.isNumeric( thisWeekWiseAdvancedWeekIndex )  ){
										primaryDeliveriesSectionElement.notify( 'Primary CSR: Please enter valid Delivery start week', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
										break;
									}
									if( thisWeekWiseAdvancedWeekIndex != "" && parseInt( thisWeekWiseAdvancedWeekIndex ) < 0 ){
										primaryDeliveriesSectionElement.notify( 'Primary CSR: Minimum Delivery start week is 0', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
										break;
									}
									if( thisWeekWiseAdvancedWeekIndex != "" && parseInt( thisWeekWiseAdvancedWeekIndex ) > 200 ){
										primaryDeliveriesSectionElement.notify( 'Primary CSR: Maximim Delivery start week is 200', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
										break;
									}
									//======================//
									if( thisWeekWiseAdvancedRedemptionPercentage == "" ){
										primaryDeliveriesSectionElement.notify( 'Primary CSR: Redemption percentage is required', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
										break;
									}
									if( !jQuery.isNumeric( thisWeekWiseAdvancedRedemptionPercentage )  ){
										primaryDeliveriesSectionElement.notify( 'Primary CSR: Please enter valid redemption percentage', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
										break;
									}
									if( thisWeekWiseAdvancedRedemptionPercentage != "" && parseInt( thisWeekWiseAdvancedRedemptionPercentage ) < 1 ){
										primaryDeliveriesSectionElement.notify( 'Primary CSR: Minimum redemption percentage is 1', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
										break;
									}
									if( thisWeekWiseAdvancedRedemptionPercentage != "" && parseInt( thisWeekWiseAdvancedRedemptionPercentage ) > 100 ){
										primaryDeliveriesSectionElement.notify( 'Primary CSR: Maximim redemption percentage is 100', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
										break;
									}
								}
	
								if( totalWeekWiseAdvancedRedemptionPercentage != 100 ){
									primaryDeliveriesSectionElement.notify( 'Primary CSR: Invalid redemption percentage.', notifyErrorOpt );
									isAdvancedError = true;
									$('html, body').animate({ scrollTop: primaryDeliveriesSectionElement.offset().top - 300 }, 500);
									return false;
								}

							});

						}
						
						if( !isAdvancedError ){
							
							$('.week_wise_advanced_options_table_data .week_wise_advanced_promotionType').each(function(index,data) {
								
								var weekWiseAdvancedPromotionType = $(this).val();
								var weekWiseAdvancedPromotionTypeIndex = $(this).attr('data-index');
								var promotionDeliveries = $('body').find('.week_wise_advanced_promotionDeliveries[data-index='+ weekWiseAdvancedPromotionTypeIndex +']').val();
								var promotionDeliveriesSectionElement = $('.week_wise_advanced_options_table_data .week_wise_advanced_promotion_section[data-index='+ weekWiseAdvancedPromotionTypeIndex +']');

								if( weekWiseAdvancedPromotionType == "bonus" || weekWiseAdvancedPromotionType == "discount" ){

									var totalWeekWiseAdvancedPromotionRedemptionPercentage = 0;
									for( var i = 1; i <= promotionDeliveries; i++ ){
										var thisElement = promotionDeliveriesSectionElement.find( '.week_wise_advanced_promotion_index_' + i + '.show' );
										var thisWeekWiseAdvancedPromotionWeekIndex = thisElement.find('.week_wise_advanced_promotion_week_index').val();
										var thisWeekWiseAdvancedPromotionRedemptionPercentage = thisElement.find('.week_wise_advanced_promotion_redemption_percentage').val();
										
										totalWeekWiseAdvancedPromotionRedemptionPercentage += parseInt( thisWeekWiseAdvancedPromotionRedemptionPercentage );

										if( thisWeekWiseAdvancedPromotionWeekIndex == "" ){
											promotionDeliveriesSectionElement.notify( 'Promotion CSR: Delivery start week number is required', notifyErrorOpt );
											isAdvancedError = true;
											$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
											return false;
											break;
										}
										if( !jQuery.isNumeric( thisWeekWiseAdvancedPromotionWeekIndex )  ){
											promotionDeliveriesSectionElement.notify( 'Promotion CSR: Please enter valid Delivery start week', notifyErrorOpt );
											isAdvancedError = true;
											$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
											return false;
											break;
										}
										if( thisWeekWiseAdvancedPromotionWeekIndex != "" && parseInt( thisWeekWiseAdvancedPromotionWeekIndex ) < 0 ){
											promotionDeliveriesSectionElement.notify( 'Promotion CSR: Minimum Delivery start week is 0', notifyErrorOpt );
											isAdvancedError = true;
											$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
											return false;
											break;
										}
										if( thisWeekWiseAdvancedPromotionWeekIndex != "" && parseInt( thisWeekWiseAdvancedPromotionWeekIndex ) > 200 ){
											promotionDeliveriesSectionElement.notify( 'Promotion CSR: Maximim Delivery start week is 200', notifyErrorOpt );
											isAdvancedError = true;
											$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
											return false;
											break;
										}
										//======================//
										if( thisWeekWiseAdvancedPromotionRedemptionPercentage == "" ){
											promotionDeliveriesSectionElement.notify( 'Promotion CSR: Redemption percentage is required', notifyErrorOpt );
											isAdvancedError = true;
											$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
											return false;
											break;
										}
										if( !jQuery.isNumeric( thisWeekWiseAdvancedPromotionRedemptionPercentage )  ){
											promotionDeliveriesSectionElement.notify( 'Promotion CSR: Please enter valid redemption percentage', notifyErrorOpt );
											isAdvancedError = true;
											$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
											return false;
											break;
										}
										if( thisWeekWiseAdvancedPromotionRedemptionPercentage != "" && parseInt( thisWeekWiseAdvancedPromotionRedemptionPercentage ) < 1 ){
											promotionDeliveriesSectionElement.notify( 'Promotion CSR: Minimum redemption percentage is 1', notifyErrorOpt );
											isAdvancedError = true;
											$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
											return false;
											break;
										}
										if( thisWeekWiseAdvancedPromotionRedemptionPercentage != "" && parseInt( thisWeekWiseAdvancedPromotionRedemptionPercentage ) > 100 ){
											promotionDeliveriesSectionElement.notify( 'Promotion CSR: Maximim redemption percentage is 100', notifyErrorOpt );
											isAdvancedError = true;
											$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
											return false;
											break;
										}
									}
		
									if( totalWeekWiseAdvancedPromotionRedemptionPercentage != 100 ){
										promotionDeliveriesSectionElement.notify( 'Promotion CSR: Invalid redemption percentage.', notifyErrorOpt );
										isAdvancedError = true;
										$('html, body').animate({ scrollTop: promotionDeliveriesSectionElement.offset().top - 300 }, 500);
										return false;
									}
								}


							});

						}
						if( isAdvancedError ){
							return false;
						}
					}

				}

				var data = new FormData( $form_ndp[0] );
				// $form_ndp.block( block_config );
				data.append("fieldmapping", 'yes');
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					timeout		: 0,
					beforeSend	: function(){
						next_fs_ndp.find('.next').hide();
						next_fs_ndp.find('.previous').hide();
						$(".new_delivery_plan_wizard #progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
						next_fs_ndp.show();
						current_fs_ndp.animate({opacity_ndp: 0}, {
							step: function(now) {
								opacity_ndp = 1 - now;
								current_fs_ndp.css({
									'display': 'none',
									'position': 'relative'
								});
								next_fs_ndp.css({'opacity': opacity_ndp});
							},
							duration: 500
						});
						setProgressBarNdp(++current_ndp);
						csr_spinner.show();
						$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Importing data"><i class="fa fa-check-"></i></span>Importing data</li>');
						$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Mapping data started..."><i class="fa fa-check-"></i></span>Mapping data started...</li>');
						$('[data-toggle="tooltip"]').tooltip();
						process_log.scrollTop = process_log.scrollHeight;
					},
					success : async function(response){
						var obj = $.parseJSON(response);
						// console.dir( obj );
						$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Mapping data completed."><i class="fa fa-check-"></i></span>Mapping data completed.</li>');
						if( obj.error == 0 ){
							$('.process_log').append('<li class="list-group-item d-block align-items-center hide"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_log_counter">'+obj.totalmsg+'</div><div class="process_log_counter"></div></li>');
							// console.log( obj );
							var total_line = obj.total_line;
							var promises = [];
							for (let icsv = 0; icsv < 1; icsv++) {
								isError = false;
								var isLast = false;
								if( icsv == ( 1 - 1 ) ){
									isLast = true;
								}
								var data = new FormData( $form_ndp[0] );
								data.append("verification_data", 'yes');
								data.append("verification_id", icsv);
								data.append("isLast", isLast);
								var request = await $.ajax({
									url: cipscript.ajax_url,
									type: 'post',
									data: data,
									processData: false,
									contentType: false,
									timeout: 0,
									async: true,
									success : function(response){
										var obj = $.parseJSON(response);
										// console.log( obj );
										if( obj.error == 0 ){
											$('body').find('.process_log_counter').html(obj.msg);
											if( obj.lastMsg != "" ){
												lastMsg = obj.lastMsg;
												lastMsg_total = obj.totalMsg;
											}
										}else{
											$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
											isError = true;
										}
										$('[data-toggle="tooltip"]').tooltip();
										process_log.scrollTop = process_log.scrollHeight;
									}
								});
								if( isError == true ){
									break;
								}
								promises.push(request);
							}
							Promise.all(promises).then( async function (responseList) {
								// console.dir( responseList );
								$('.process_log').append('<li class="list-group-item d-flex align-items-center hide"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Reference checking completed."><i class="fa fa-check-"></i></span>Reference checking completed.</li>');
								if( lastMsg != "" && !isError ){
									$('.process_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+ lastMsg +'"><i class="fa fa-check-"></i></span>'+ lastMsg +'<div class="total_process_log_counter">'+ lastMsg_total +'</div><div class="userstatus_process_log_counter"></div></li>');
								}
								$('[data-toggle="tooltip"]').tooltip();
								if( isError ){
									next_fs_ndp.find('.next').prop('disabled', true);
									next_fs_ndp.find('.next').hide();
									next_fs_ndp.find('.previous').show();
								}else{
									// console.log( total_line );
									var promisesStatus = [];
									for (let i2csv = 0; i2csv < total_line; i2csv++) {
										isError = false;
										var data = new FormData( $form_ndp[0] );
										data.append("userstatus_check", 'yes');
										data.append("verification_id", i2csv);
										var requestStatus = await $.ajax({
											url: cipscript.ajax_url,
											type: 'post',
											data: data,
											processData: false,
											contentType: false,
											timeout: 0,
											async: true,
											success : function(response){
												var obj = $.parseJSON(response);
												// console.log( obj );
												if( obj.error == 0 ){
													$('body').find('.userstatus_process_log_counter').html(obj.msg);
												}else{
													$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
													isError = true;
												}
												$('[data-toggle="tooltip"]').tooltip();
												process_log.scrollTop = process_log.scrollHeight;
											}
										});
										if( isError == true ){
											break;
										}
										promisesStatus.push(requestStatus);
									}
									Promise.all(promisesStatus).then(function (responseList) {
										// console.dir( responseList );
										$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Importing data completed."><i class="fa fa-check-"></i></span>Importing data completed.</li>');
										$('[data-toggle="tooltip"]').tooltip();
										if( isError ){
											next_fs_ndp.find('.next').prop('disabled', true);
											next_fs_ndp.find('.next').hide();
											next_fs_ndp.find('.previous').show();
										}else{
											next_fs_ndp.find('.next').prop('disabled', false);
											next_fs_ndp.find('.next').show();
											next_fs_ndp.find('.previous').show();
										}
										process_log.scrollTop = process_log.scrollHeight;
										csr_spinner.hide();
									});
								}
								csr_spinner.hide();
							});
						}else{
							$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
							next_fs_ndp.find('.next').prop('disabled', true);
							next_fs_ndp.find('.previous').show();
							csr_spinner.hide();
							process_log.scrollTop = process_log.scrollHeight;
						}
						$('[data-toggle="tooltip"]').tooltip();
						process_log.scrollTop = process_log.scrollHeight;
					}
				});
			}else if( current_ndp == 3 ){ // splitting process starting
				if( !splited ){
					var data = new FormData( $form_ndp[0] ); // splitting process
					data.append("splitting_start", 'yes');
					$.ajax({
						url: cipscript.ajax_url,
						type: 'post',
						data: data,
						processData: false,
						contentType: false,
						timeout: 0,
						beforeSend	: function(){
							next_fs_ndp.find('.next').hide();
							next_fs_ndp.find('.previous').hide();
							$(".new_delivery_plan_wizard #progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
							next_fs_ndp.show();
							current_fs_ndp.animate({opacity_ndp: 0}, {
								step: function(now) {
									opacity_ndp = 1 - now;
									current_fs_ndp.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs_ndp.css({'opacity': opacity_ndp});
								},
								duration: 500
							});
							setProgressBarNdp(++current_ndp);
							csr_split_spinner.show();
						},
						success : async function(response){
							var obj = $.parseJSON(response);
							if( obj.error == 0 ){
								$('.process_split_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_split_log_counter">'+obj.totalmsg+'</div><div class="process_split_log_counter"></div></li>');
								// console.log( obj );
								var promises = [];
								for (let icsv = 1; icsv <= obj.total_paged; icsv++) {
									var isError = false;
									var data = new FormData( $form_ndp[0] );
									data.append("splitting_data", 'yes');
									data.append("page_id", icsv);
									var request = await $.ajax({
										url: cipscript.ajax_url,
										type: 'post',
										data: data,
										processData: false,
										contentType: false,
										timeout: 0,
										async: true,
										success : function(response){
											var obj = $.parseJSON(response);
											// console.log( obj );
											if( obj.error == 0 ){
												$('body').find('.process_split_log_counter').append(obj.msg);
											}else{
												$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
												isError = true;
											}
											$('[data-toggle="tooltip"]').tooltip();
										}
									});
									if( isError == true ){
										csr_split_spinner.hide();
										break;
									}
									promises.push(request);
								}
								Promise.all(promises).then(responseList => {
									// console.dir( responseList );
									$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Splitting deliveries completed."><i class="fa fa-check-"></i></span>Splitting deliveries completed.</li>');
									$('[data-toggle="tooltip"]').tooltip();
									if( isError ){
										next_fs_ndp.find('.next').prop('disabled', true);
										next_fs_ndp.find('.next').hide();
										next_fs_ndp.find('.previous').show();
									}else{
										next_fs_ndp.find('.next').prop('disabled', false);
										next_fs_ndp.find('.next').show();
										next_fs_ndp.find('.previous').show();
										splited = true;
									}
									csr_split_spinner.hide();
								});
							}else{
								$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
								next_fs_ndp.find('.next').prop('disabled', true);
								next_fs_ndp.find('.previous').show();
								csr_split_spinner.hide();
							}
							$('[data-toggle="tooltip"]').tooltip();
						}
					});
				}else{
					$("#progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
					next_fs_ndp.show();
					current_fs_ndp.animate({opacity_ndp: 0}, {
						step: function(now) {
							opacity_ndp = 1 - now;
							current_fs_ndp.css({
								'display': 'none',
								'position': 'relative'
							});
							next_fs_ndp.css({'opacity': opacity_ndp});
						},
						duration: 500
					});
					setProgressBarNdp(++current_ndp);
				}
			}else if( current_ndp == 2 ){
				$(".new_delivery_plan_wizard #progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
				next_fs_ndp.show();
				current_fs_ndp.animate({opacity_ndp: 0}, {
					step: function(now) {
						opacity_ndp = 1 - now;
						current_fs_ndp.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_ndp.css({'opacity': opacity_ndp});
					},
					duration: 500
				});
				setProgressBarNdp(++current_ndp);
				$('.distribution_section_table').show();
				var $tableDistribution = $('#new_delivery_plan_distribution_table');
				$tableDistribution.bootstrapTable('refresh');
			}else if( current_ndp == 4 ){
				$(".new_delivery_plan_wizard #progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
				next_fs_ndp.show();
				current_fs_ndp.animate({opacity_ndp: 0}, {
					step: function(now) {
						opacity_ndp = 1 - now;
						current_fs_ndp.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_ndp.css({'opacity': opacity_ndp});
					},
					duration: 500
				});
				setProgressBarNdp(++current_ndp);
				$('.distribution_10_section_table').show();
				var $tableDistribution_10 = $('#new_delivery_plan_distribution_10_table');
				$tableDistribution_10.bootstrapTable('refresh');
				$('html, body').animate({
					scrollTop: $("#progressbar").offset().top - 100
				}, 1000);
			}else if( current_ndp == 5 ){
				$(".new_delivery_plan_wizard #progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
				next_fs_ndp.show();
				current_fs_ndp.animate({opacity_ndp: 0}, {
					step: function(now) {
						opacity_ndp = 1 - now;
						current_fs_ndp.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_ndp.css({'opacity': opacity_ndp});
					},
					duration: 500
				});
				setProgressBarNdp(++current_ndp);
				$('.distribution_promotion_section_table').show();
				var $tableDistribution_promotion = $('#new_delivery_plan_distribution_promotion_table');
				$tableDistribution_promotion.bootstrapTable('refresh');
				$('html, body').animate({
					scrollTop: $("#progressbar").offset().top - 100
				}, 1000);
			}else if( current_ndp == 6 ){
				setTimeout(() => {
					$(".new_delivery_plan_wizard #progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
					next_fs_ndp.show();
					current_fs_ndp.animate({opacity_ndp: 0}, {
						step: function(now) {
							opacity_ndp = 1 - now;
							current_fs_ndp.css({
								'display': 'none',
								'position': 'relative'
							});
							next_fs_ndp.css({'opacity': opacity_ndp});
						},
						duration: 500
					});
					setProgressBarNdp(++current_ndp);
				}, 100);
			}else{
				$(".new_delivery_plan_wizard #progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
				next_fs_ndp.show();
				current_fs_ndp.animate({opacity_ndp: 0}, {
					step: function(now) {
						opacity_ndp = 1 - now;
						current_fs_ndp.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_ndp.css({'opacity': opacity_ndp});
					},
					duration: 500
				});
				setProgressBarNdp(++current_ndp);
			}
		});
		$(".new_delivery_plan_wizard .previous").click(function(){
			current_fs_ndp = $(this).closest('fieldset');
			previous_fs_ndp = $(this).closest('fieldset').prev();
			// console.log( current_ndp );
			if( current_ndp == 2 ){
				$('.process_log').html('');
				$(".new_delivery_plan_wizard input[name='th_csv_file']").val('');
			}
			if( current_ndp == 6 ){
				$('.distribution_10_section_table').show();
				var $tableDistribution_10 = $('#new_delivery_plan_distribution_10_table');
				$tableDistribution_10.bootstrapTable('refresh');
				$('html, body').animate({
					scrollTop: $("#progressbar").offset().top - 100
				}, 1000);
			}
			if( current_ndp == 7 ){
				$('.distribution_promotion_section_table').show();
				var $tableDistribution_promotion = $('#new_delivery_plan_distribution_promotion_table');
				$tableDistribution_promotion.bootstrapTable('refresh');
				$('html, body').animate({
					scrollTop: $("#progressbar").offset().top - 100
				}, 1000);
			}
			if( current_ndp == 4 ){
				$('.distribution_section_table').show();
				var $tableDistribution = $('#new_delivery_plan_distribution_table');
				$tableDistribution.bootstrapTable('refresh');
				$('html, body').animate({
					scrollTop: $("#progressbar").offset().top - 100
				}, 1000);
			}
			//Remove class active
			$(".new_delivery_plan_wizard #progressbar li").eq($("fieldset").index(current_fs_ndp)).removeClass("active");
			//show the previous fieldset
			previous_fs_ndp.show();
			//hide the current fieldset with style
			current_fs_ndp.animate({opacity_ndp: 0}, {
				step: function(now) {
					// for making fielset appear animation
					opacity_ndp = 1 - now;
					current_fs_ndp.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs_ndp.css({'opacity': opacity_ndp});
				},
				duration: 500
			});
			setProgressBarNdp(--current_ndp);
		});
		function setProgressBarNdp(curStep){
			var percent = parseFloat(100 / steps_ndp) * curStep;
			percent = percent.toFixed();
			$(".new_delivery_plan_wizard .progress-bar").css("width",percent+"%")
		}
		$(".new_delivery_plan_wizard input[name='th_csv_file']").on("change", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			var pool_reference = $('input[name="pool_reference"]').val();
			if($.inArray(this_ext, ['csv']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid csv file', notifyErrorOpt );
				$(this).val('');
				$('.new_delivery_plan_wizard .next.first_step').addClass('invisible');
				$('.new_delivery_plan_wizard .pool_ref_toogle').slideUp();
				$('.new_delivery_plan_wizard input[name="pool_reference"]').val('');
				$('.advanced_options_table_data').hide();
				$('.week_wise_advanced_options_table_data').hide();
				$(".new_delivery_plan_wizard input[name='advanced_weekly_wizard_option']").prop('checked', false);
			}else{
				var $form = $('.new_delivery_plan_wizard');
				var data = new FormData( $form[0] );
				var poolRefToogle = $('.new_delivery_plan_wizard .pool_ref_toogle');
				data.append("findPoolFromFile", 'yes');
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					timeout		: 0,
					beforeSend	: function(){
						$form.block( block_config );
					},
					success : async function(response){
						var obj = $.parseJSON(response);
						// console.dir( response );
						poolRefToogle.slideDown();
						$('.new_delivery_plan_wizard .next.first_step').removeClass('invisible');
						$form.unblock();
						if( obj.error == 0 ){
							$('.new_delivery_plan_wizard input[name="pool_reference"]').val( obj.poolRefPopulate );
							$('.advanced_options_table_data').html( obj.advancedWeeklyOptionHtml );
							$('.week_wise_advanced_options_table_data').html( obj.weekWiseAdvancedWeeklyOptionHtml );
						}
					}
				});
			}
		});
		$(".new_delivery_plan_wizard input[name='advanced_weekly_wizard_option']").on("change", function(e){
			if( $("input[name='advanced_weekly_wizard_option']:checked").val() == 'advanced' ){
				$('.advanced_options_table_data').show();
				var csr_segmentation = $('input[name=csr_segmentation]').val();
				$('input.csrSegmentation').val( csr_segmentation );
				var primary_number_of_deliveries = $('select[name=primary_number_of_deliveries]').val();
				$('select.primaryDeliveries option[value="'+primary_number_of_deliveries+'"]').prop('selected', true);
				var primary_delivery_interval = $('select[name=primary_delivery_interval]').val();
				if( primary_number_of_deliveries == 1 ){
					primary_delivery_interval = 1;
				}
				$('select.primaryDeliveryInterval option[value="'+primary_delivery_interval+'"]').prop('selected', true);
				var primary_delivery_start_week = $('input[name=primary_delivery_start_week]').val();
				$('input.primaryDeliveryStartWeek').val( primary_delivery_start_week );
				var promotion_type = $('select[name=promotion_type]').val();
				$('select.promotionType option[value="'+promotion_type+'"]').prop('selected', true);
				if( promotion_type == 'bonus' ){
					var bonus_percentage = $('input[name=bonus_percentage]').val();
				}else if( promotion_type == 'discount' ){
					var bonus_percentage = $('input[name=discount_percentage]').val();
				}else{
					var bonus_percentage = "";
				}
				$('input.promotionPercentage').val( bonus_percentage );
				var promotion_number_of_deliveries = $('select[name=promotion_number_of_deliveries]').val();
				$('select.promotionDeliveries option[value="'+promotion_number_of_deliveries+'"]').prop('selected', true);
				var promotion_delivery_interval = $('select[name=promotion_delivery_interval]').val();
				if( promotion_number_of_deliveries == 1 ){
					promotion_delivery_interval = 1;
				}
				$('select.promotionDeliveryInterval option[value="'+promotion_delivery_interval+'"]').prop('selected', true);
				var promotion_delivery_start_week = $('input[name=promotion_delivery_start_week]').val();
				$('input.promotionDeliveryStartWeek').val( promotion_delivery_start_week );
			}else{
				$('.advanced_options_table_data').hide();
			}
		});
		$(".new_delivery_plan_wizard select[name='promotion_type']").on("change", function(e){
			if( $(this).val() == 'bonus' ){
				$('.bonus_section_fields').show();
				$('.discount_section_fields').hide();
				$('.promotion_toggle_section').show();
			}else if( $(this).val() == 'discount' ){
				$('.bonus_section_fields').hide();
				$('.discount_section_fields').show();
				$('.promotion_toggle_section').show();
			}else{
				$('.bonus_section_fields').hide();
				$('.discount_section_fields').hide();
				$('.promotion_toggle_section').hide();
			}
		});
		$(".new_delivery_plan_wizard select[name='primary_number_of_deliveries']").on("change", function(e){
			if( $(this).val() == '1' ){
				$('.primary_delivery_interval_toggle').hide();
			}else{
				$('.primary_delivery_interval_toggle').show();
			}
		});
		$(".new_delivery_plan_wizard select[name='promotion_number_of_deliveries']").on("change", function(e){
			if( $(this).val() == '1' ){
				$('.promotion_delivery_interval_toggle').hide();
			}else{
				$('.promotion_delivery_interval_toggle').show();
			}
		});
		$('body').on("input", "#csr_segmentation, .csrSegmentation, #primary_delivery_start_week, .primaryDeliveryStartWeek, #bonus_percentage, .promotionPercentage, #discount_percentage, #promotion_delivery_start_week, .promotionDeliveryStartWeek, .week_wise_advanced_week_index, .week_wise_advanced_redemption_percentage, .week_wise_advanced_promotion_week_index, .week_wise_advanced_promotion_redemption_percentage", 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);
		});
		$("#pool_reference").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);
		});
		var new_delivery_plan_distribution_url = "<?php echo $new_delivery_plan_distribution_url ?>";
		if( $('#new_delivery_plan_distribution_table').length > 0 ){
			var $tableDistribution = $('#new_delivery_plan_distribution_table');
			$tableDistribution.bootstrapTable({
				method: 'post',
				contentType: 'application/x-www-form-urlencoded',
				url: new_delivery_plan_distribution_url,
				queryParams: function (p) {
					return {
						columnfilter: p.filter,
						limit: p.limit,
						offset: p.offset,
						sort: p.sort,
						order: p.order,
					};
				},
				stickyHeader: false,
				onPostBody: function (){
					if( $('body').find('.modelpop_notes').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}
				}
			});
		}
		var new_delivery_plan_distribution_10_url = "<?php echo $new_delivery_plan_distribution_10_url ?>";
		if( $('#new_delivery_plan_distribution_10_table').length > 0 ){
			var $tableDistribution10 = $('#new_delivery_plan_distribution_10_table');
			$tableDistribution10.bootstrapTable({
				method: 'post',
				contentType: 'application/x-www-form-urlencoded',
				url: new_delivery_plan_distribution_10_url,
				queryParams: function (p) {
					return {
						columnfilter: p.filter,
						limit: p.limit,
						offset: p.offset,
						sort: p.sort,
						order: p.order,
					};
				},
				stickyHeader: false,
				onPostBody: function (){
					if( $('body').find('.modelpop_notes').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}
				}
			});
		}
		var new_delivery_plan_distribution_promotion_url = "<?php echo $new_delivery_plan_distribution_promotion_url ?>";
		if( $('#new_delivery_plan_distribution_promotion_table').length > 0 ){
			var $tableDistributionpromotion = $('#new_delivery_plan_distribution_promotion_table');
			$tableDistributionpromotion.bootstrapTable({
				method: 'post',
				contentType: 'application/x-www-form-urlencoded',
				url: new_delivery_plan_distribution_promotion_url,
				queryParams: function (p) {
					return {
						columnfilter: p.filter,
						limit: p.limit,
						offset: p.offset,
						sort: p.sort,
						order: p.order,
					};
				},
				stickyHeader: false,
				onPostBody: function (){
					if( $('body').find('.modelpop_notes').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}
				}
			});
		}
		$('body').on('click', '.append_new_delivery_plan_csr_holders_data_button', function(){
			$form = $(this).closest('fieldset');
			buttonAppend = $('.append_new_delivery_plan_csr_holders_data_button');
			buttonCancelAppend = $('.append_new_delivery_plan_cancel');
			buttonAppend.prop('disabled', true);
			buttonCancelAppend.prop('disabled', true);
			var csr_split_spinner = $('.csr_split_append_spinner');
			var csr_split_user_status_spinner = $('.csr_split_append_user_status_spinner');
			$formAppend = $('#append_new_delivery_plan_csr_holders_data_frm');
			var data = $('#append_new_delivery_plan_csr_holders_data_frm').serialize();
			data = data + '&get_append_data=yes';
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, async function(response) {
				var obj = JSON.parse( response );
				// console.dir( obj );
				if( obj.error == 0 ){
					$('.process_split_append_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_split_append_log_counter">'+obj.totalmsg+'</div><div class="process_split_append_log_counter"></div></li>');
					// console.log( obj );
					var promisesAppend = [];
					var promisesUserStatus = [];
					for (let icsv = 1; icsv <= obj.total_paged; icsv++) {
						var isError = false;
						var data = new FormData( $formAppend[0] );
						data.append("appending_data", 'yes');
						data.append("page_id", icsv);
						data.append("total_paged", obj.total_paged);
						var requestAppend = await $.ajax({
							url: cipscript.ajax_url,
							type: 'post',
							data: data,
							processData: false,
							contentType: false,
							timeout: 0,
							async: true,
							success : async function(response){
								var obj = $.parseJSON(response);
								// console.log( obj );
								if( obj.error == 0 ){
									$('body').find('.process_split_append_log_counter').append(obj.msg);
									if( obj.isLastPage == 'yes' ){
										//Append completer, after check user status and update status loop start
										setTimeout(() => {
											$('.finish_step').trigger('click');
										}, 3000);
									}
								}else{
									$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
									isError = true;
								}
								$('[data-toggle="tooltip"]').tooltip();
							}
						});
						if( isError == true ){
							csr_split_spinner.hide();
							buttonAppend.prop('disabled', false);
							buttonCancelAppend.prop('disabled', false);
							break;
						}
						promisesAppend.push(requestAppend);
					}
					Promise.all(promisesAppend).then(responseList => {
						// console.dir( responseList );
						$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Appending deliveries completed."><i class="fa fa-check-"></i></span>Appending deliveries completed.</li>');
						$('[data-toggle="tooltip"]').tooltip();
						if( isError ){
							buttonAppend.prop('disabled', false);
							buttonCancelAppend.prop('disabled', false);
						}else{
						}
						csr_split_spinner.hide();
					});
				}else{
					$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
					csr_split_spinner.hide();
					buttonAppend.prop('disabled', false);
					buttonCancelAppend.prop('disabled', false);
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
				}
				$form.unblock();
			});
			return false;
		});
		$('body').on('click', '.append_new_delivery_plan_cancel', function(){
			Swal({
			title: 'Are you sure?',
			text: "Are you sure you want to cancel",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
			}).then((result) => {
			if (result.value) {
					$form = $(this).closest('fieldset');
					var data = $('#append_new_delivery_plan_cancel_data_frm').serialize();
					$form.block( block_config );
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						// console.dir( obj );
						if( obj.error == 0 ){
							window.location.href = cipscript.current_page;
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();
					});
			}
			});
			return false;
		});
		if( cipscript.isNewDeliveryPlanDistributionData == 1 ){
			go_to_five_step_new_delivery_plan();
			$('.back_disable').hide();
		}
		function go_to_five_step_new_delivery_plan(){
			for (let step = 1; step < 7; step++) {
				var $next_button = $('.step_'+(step - 1 )).find('.next');
				var current_fs_ndp = $next_button.parent();
				var next_fs_ndp = $next_button.parent().next();
				$("#progressbar li").eq( $("fieldset").index(next_fs_ndp) ).addClass("active");
				next_fs_ndp.show();
				current_fs_ndp.css({
					'display': 'none',
					'position': 'relative'
				});
				next_fs_ndp.css({'opacity': opacity_ndp});
				setProgressBarNdp(++current_ndp);
			}
		}
		$(".new_delivery_plan_wizard select[name=token]").on("change", function(e){
			if( $(this).val() == 'CSR25' ){
				$('.token_type_label').html('CSR25');
			}else{
				$('.token_type_label').html('CSR');
			}
			if( $('.new_delivery_plan_wizard input[name=th_csv_file]').val() != "" ){
				$('.new_delivery_plan_wizard input[name=th_csv_file]').val('').trigger('change');
			}
		});

		$(".new_delivery_plan_wizard input[name=week_wise_advanced]").on("change", function(e){
			if( $("input[name=week_wise_advanced]:checked").val() == 'week_wise' ){
				$(".week_wise_normal_section").hide();
				$(".week_wise_advanced_section").show();
			}else{
				$(".week_wise_normal_section").show();
				$(".week_wise_advanced_section").hide();
			}
		});

		$(".new_delivery_plan_wizard select[name=week_wise_primary_number_of_deliveries]").on("change", function(e){
			var thisValue = $(this).val();
			for( var i = 1; i <= 10; i++ ){
				if( i <= thisValue ){
					$('.week_wise_primary_index_' + i).removeClass('hide').addClass('show').find('input').attr('disabled', false);
				}else{
					$('.week_wise_primary_index_' + i).addClass('hide').removeClass('show').find('input').attr('disabled', true);
				}
			}
		});
		
		$(".new_delivery_plan_wizard select[name='week_wise_promotion_type']").on("change", function(e){
			if( $(this).val() == 'bonus' ){
				$('.week_wise_bonus_section_fields').show();
				$('.week_wise_discount_section_fields').hide();
				$('.week_wise_promotion_toggle_section').show();
			}else if( $(this).val() == 'discount' ){
				$('.week_wise_bonus_section_fields').hide();
				$('.week_wise_discount_section_fields').show();
				$('.week_wise_promotion_toggle_section').show();
			}else{
				$('.week_wise_bonus_section_fields').hide();
				$('.week_wise_discount_section_fields').hide();
				$('.week_wise_promotion_toggle_section').hide();
			}
		});
		$(".new_delivery_plan_wizard select[name=week_wise_promotion_number_of_deliveries]").on("change", function(e){
			var thisValue = $(this).val();
			for( var i = 1; i <= 10; i++ ){
				if( i <= thisValue ){
					$('.week_wise_promotion_index_' + i).removeClass('hide').addClass('show').find('input').attr('disabled', false);
				}else{
					$('.week_wise_promotion_index_' + i).addClass('hide').removeClass('show').find('input').attr('disabled', true);
				}
			}
		});
		
		$('body').on("input", ".week_wise_week_index, .week_wise_redemption_percentage, .week_wise_promotion_week_index, .week_wise_promotion_redemption_percentage, #week_wise_bonus_percentage, #week_wise_discount_percentage", 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);
		});

		$(".new_delivery_plan_wizard input[name='week_wise_advanced_weekly_wizard_option']").on("change", function(e){
			if( $("input[name='week_wise_advanced_weekly_wizard_option']:checked").val() == 'advanced' ){
				$('.week_wise_advanced_options_table_data').show();

				var csr_segmentation = $('input[name=csr_segmentation]').val();
				$('input.csrSegmentation').val( csr_segmentation );

				var week_wise_primary_number_of_deliveries = $('select[name=week_wise_primary_number_of_deliveries]').val();
				$('select.primaryDeliveries option[value="'+week_wise_primary_number_of_deliveries+'"]').prop('selected', true).trigger('change');

				var week_wise_promotion_type = $('select[name=week_wise_promotion_type]').val();
				$('select.week_wise_advanced_promotionType option[value="'+week_wise_promotion_type+'"]').prop('selected', true).trigger('change');

				if( week_wise_promotion_type == 'bonus' ){
					var bonus_percentage = $('input[name=week_wise_bonus_percentage]').val();
				}else if( week_wise_promotion_type == 'discount' ){
					var bonus_percentage = $('input[name=week_wise_discount_percentage]').val();
				}else{
					var bonus_percentage = "";
				}
				$('input.promotionPercentage').val( bonus_percentage );
				
				var week_wise_promotion_number_of_deliveries = $('select[name=week_wise_promotion_number_of_deliveries]').val();
				$('select.promotionDeliveries option[value="'+week_wise_promotion_number_of_deliveries+'"]').prop('selected', true).trigger('change');
				
				for( var i = 1; i <= week_wise_primary_number_of_deliveries; i++ ){
					var thisElement = $( '.week_wise_primary_index_' + i + '.show' );
					var thisWeekWiseWeekIndex = thisElement.find('.week_wise_week_index').val();
					var thisWeekWiseRedemptionPercentage = thisElement.find('.week_wise_redemption_percentage').val();
					
					var weekWiseAdvancedPrimaryElement = $( '.week_wise_advanced_primary_index_' + i + '.show' );
					weekWiseAdvancedPrimaryElement.find('.week_wise_advanced_week_index').val( thisWeekWiseWeekIndex );
					weekWiseAdvancedPrimaryElement.find('.week_wise_advanced_redemption_percentage').val( thisWeekWiseRedemptionPercentage );
				}
				
				for( var i = 1; i <= week_wise_promotion_number_of_deliveries; i++ ){
					var thisElement = $( '.week_wise_promotion_index_' + i + '.show' );
					var thisWeekWisePromotionWeekIndex = thisElement.find('.week_wise_promotion_week_index').val();
					var thisWeekWisePromotionRedemptionPercentage = thisElement.find('.week_wise_promotion_redemption_percentage').val();
					
					var weekWiseAdvancedPromotionElement = $( '.week_wise_advanced_promotion_index_' + i + '.show' );
					weekWiseAdvancedPromotionElement.find('.week_wise_advanced_promotion_week_index').val( thisWeekWisePromotionWeekIndex );
					weekWiseAdvancedPromotionElement.find('.week_wise_advanced_promotion_redemption_percentage').val( thisWeekWisePromotionRedemptionPercentage );
				}

			}else{
				$('.week_wise_advanced_options_table_data').hide(); 
			}
		});

		$('body').on("change",".new_delivery_plan_wizard .week_wise_advanced_primarydeliveries", function(e){
			var thisIndex = $(this).attr('data-index');
			var thisValue = $(this).val();
			var thisElement = $('.week_wise_advanced_primary_section[data-index="'+ thisIndex +'"]');
			for( var i = 1; i <= 10; i++ ){
				if( i <= thisValue ){
					thisElement.find('.week_wise_advanced_primary_index_' + i).removeClass('hide').addClass('show').find('input').attr('disabled', false);
				}else{
					thisElement.find('.week_wise_advanced_primary_index_' + i).addClass('hide').removeClass('show').find('input').attr('disabled', true);
				}
			}
		});
		$('body').on("change",".new_delivery_plan_wizard .week_wise_advanced_promotionType", function(e){
			var thisIndex = $(this).attr('data-index');
			var thisValue = $(this).val();
			var thisElement = $('.week_wise_advanced_promotion_section[data-index="'+ thisIndex +'"]');
			if( thisValue == 'bonus' || thisValue == 'discount' ){
				thisElement.show();
			}else{
				thisElement.hide();
			}
			$('body').find('.new_delivery_plan_wizard .week_wise_advanced_promotionDeliveries[data-index="'+ thisIndex +'"]').trigger('change');
		});
		$('body').on("change",".new_delivery_plan_wizard .week_wise_advanced_promotionDeliveries", function(e){
			var thisIndex = $(this).attr('data-index');
			var thisValue = $(this).val();
			var thisElement = $('.week_wise_advanced_promotion_section[data-index="'+ thisIndex +'"]');
			for( var i = 1; i <= 10; i++ ){
				if( i <= thisValue ){
					thisElement.find('.week_wise_advanced_promotion_index_' + i).removeClass('hide').addClass('show').find('input').attr('disabled', false);
				}else{
					thisElement.find('.week_wise_advanced_promotion_index_' + i).addClass('hide').removeClass('show').find('input').attr('disabled', true);
				}
			}
		});

	}
});
function responseNewDeliveryPlanImportHandler(res){
	if( res.total_import_label ){
		$('.total_import_label').show().html( res.total_import_label );
	}else{
		$('.total_import_label').hide();
	}
	return res;
}
function responseNewDeliveryPlanHandler(res){
	if( res.total_issued_label ){
		$('.total_distribution_label').show().html( res.total_issued_label );
	}else{
		$('.total_distribution_label').hide();
	}
	return res;
}
function responseNewDeliveryPlanPromotionHandler(res){
	if( res.total_issued_label ){
		$('.total_distribution_promotion_label').show().html( res.total_issued_label );
	}else{
		$('.total_distribution_promotion_label').hide();
	}
	return res;
}
</script><?php
}
add_action('wp_ajax_cip_new_delivery_plan_wizard_act','cip_new_delivery_plan_wizard_act_callback');
function cip_new_delivery_plan_wizard_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_' ) ){
		if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['findPoolFromFile'] ) && $_POST['findPoolFromFile'] == 'yes' ) ){ // fetch pool ref
			global $wpdb;
			$fileName = $_FILES['th_csv_file']['name'];
			$pathFileName = pathinfo($fileName, PATHINFO_FILENAME);
			$pathFileExt = pathinfo($fileName, PATHINFO_EXTENSION);
			$underscroePos = strrpos( $pathFileName, "_" );
			$yearWeekextract = substr( $pathFileName, $underscroePos+1 );
			$fileNameWithoutNumber = substr( $fileName, 0, $underscroePos );
			$poolRefPopulate = "";
			if( $fileNameWithoutNumber == 'CSR_redemptions_week' && ctype_digit( $yearWeekextract ) ){
				$year = mb_substr($yearWeekextract, 0, 4);
				$weekNumber = mb_substr($yearWeekextract, 4);
				// $poolRefPopulate = sprintf( __('Week-%s-of-%s', CIP_TXTDOMAIN), $weekNumber, $year );
				$poolRefPopulate = sprintf( __('PNP-%s-%s', CIP_TXTDOMAIN), $year, $weekNumber );
			}else if( $fileNameWithoutNumber == 'CSR_bonus_week' && ctype_digit( $yearWeekextract ) ){
				$year = mb_substr($yearWeekextract, 0, 4);
				$weekNumber = mb_substr($yearWeekextract, 4);
				$poolRefPopulate = sprintf( __('BNS-%s-%s', CIP_TXTDOMAIN), $year, $weekNumber );
			}
			if( $_POST['token'] == 'CSR25' ){
			}else{
				$responseCsrPrice = amplivo_api_send_requests( [], 'get-csr-price-changes');
				$tableDeliveryCsrPrice = $wpdb->prefix.'delivery_csr_price';
				$delete = $wpdb->query("TRUNCATE TABLE `".$tableDeliveryCsrPrice."`");
				if( $responseCsrPrice['success'] == true ){
					$responseDatas = $responseCsrPrice['result'];
					if( $responseDatas ){
						foreach( $responseDatas as $responseData ){
							$insertData = [ 'csr_price' => $responseData['csr_price'], 'start_date' => $responseData['start_date'], 'type' => $responseData['type'], 'status' => $responseData['status'] ];
							$wpdb->insert( $tableDeliveryCsrPrice, $insertData );
						}
					}
				}
			}
			$createdDateArray = array();
			$advancedWeeklyOptionHtml = '<table class="table table-bordered table-hover mt-2"><tr class="advanced_tr_heading">
			<td>Date</td>
			<td>Pool Reference</td>
			<td style="width: 5%;"><span class="token_type_label">'. $_POST['token'] .'</span> Segmentation</td>
			<td style="width: 7%;">Primary deliveries</td>
			<td style="width: 7%;">Primary delivery interval</td>
			<td style="width: 7%;">Primary delivery start week</td>
			<td style="width: 9%;">Promotion type</td>
			<td style="width: 5%;">Promotion %</td>
			<td style="width: 5%;">Promotion deliveries</td>
			<td style="width: 5%;">Promotion delivery interval</td>
			<td style="width: 5%;">Promotion delivery start week</td>
			</tr>';
			
			$weekWiseAdvancedWeeklyOptionHtml = '<table class="table table-bordered table-hover mt-2 week_wise_advanced_weekly_option_html">
			<tr class="advanced_tr_heading">
				<td>Date</td>
				<td>Pool Reference</td>
				<td style="width: 12%;"><span class="token_type_label">'. $_POST['token'] .'</span> Segmentation</td>
				<td style="width: 12%;">Primary deliveries</td>
				<td style="width: 11%;">Promotion type</td>
				<td style="width: 9%;">Promotion %</td>
				<td style="width: 13%;">Promotion deliveries</td>
			</tr>';
			$advancedWeeklyOptionHtmlInner = "";
			$weekWiseAdvancedWeeklyOptionHtmlInner = "";
			$csvFile = $_FILES['th_csv_file']['tmp_name'];
			if( ($handle = fopen($csvFile, 'r')) !== false ){
				$file_content = file( $csvFile , FILE_SKIP_EMPTY_LINES);
   				$total_line = count($file_content) - 1;
				$flag = true;
				$countError = 0;
				while (($rowData = fgetcsv($handle, 0)) !== false) {
					if( $flag ){
						$csvdata = array_map('str_getcsv', file( $csvFile ));
						unset( $csvdata[0] );
						if( $csvdata ){
							foreach( $csvdata as $key => $rowData ){
								$rowCounter = $key;
								$created = ( $rowData[ 7 ] != "" ) ? $rowData[ 7 ] : '';
								if( empty( $created ) || DateTime::createFromFormat('d/m/Y', $created) === false ){
									$out = array( "error" => 1,'msg' => __('Error : Created date is empty or invalid format',CIP_TXTDOMAIN), 'msg2' => __('Error : Created date is empty or invalid format',CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}
								$createdDateArray[] = $created;
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Error : empty data in file',CIP_TXTDOMAIN), 'msg2' => __('Error : empty data in file',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$flag = false;
						continue;
					}
					$rowError = false;
				}
				fclose($handle);
			}
			ob_start();
			$createdDateArray = array_unique( $createdDateArray );
			usort($createdDateArray, function($aDate, $bDate) {
				$dateA = DateTime::createFromFormat('d/m/Y', $aDate);
				$dateB = DateTime::createFromFormat('d/m/Y', $bDate);
				return $dateA <=> $dateB;
			});
			if( !empty( $createdDateArray ) ){
				$index = 1;
				foreach( $createdDateArray as $createdDateValue ){
				?><tr>
					<td><input class="form-control mb-0 createdDate" type="text" name="createdDate[]" value="<?php echo $createdDateValue; ?>" readonly/></td>
					<td><input class="form-control mb-0" type="text" value="<?php echo $poolRefPopulate; ?>" readonly/></td>
					<td><input class="form-control mb-0 csrSegmentation" type="text" name="csrSegmentation[]" min="10" value="100" required/></td>
					<td><select class="form-control mb-0 primaryDeliveries" name="primaryDeliveries[]">
							<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
							<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
							<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
							<option value="4"><?php _e('4', CIP_TXTDOMAIN); ?></option>
							<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
							<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
							<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
							<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
							<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
							<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
					</select></td>
					<td><select class="form-control mb-0 primaryDeliveryInterval" name="primaryDeliveryInterval[]" required>
						<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
						<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
						<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
						<option value="4" selected><?php _e('4', CIP_TXTDOMAIN); ?></option>
						<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
						<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
						<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
						<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
						<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
						<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
					</select></td>
					<td><input class="form-control mb-0 primaryDeliveryStartWeek" type="text" name="primaryDeliveryStartWeek[]" min="0" max="200" value="40" placeholder="<?php _e('Default will be 40', CIP_TXTDOMAIN); ?>" required /></td>
					<td>
					<select class="form-control mb-0 promotionType" name="promotionType[]" data-index="<?php echo $index; ?>">
						<option value="none"><?php _e('None', CIP_TXTDOMAIN); ?></option>
						<option value="bonus"><?php _e('Bonus', CIP_TXTDOMAIN); ?></option>
						<option value="discount"><?php _e('Discount', CIP_TXTDOMAIN); ?></option>
					</select>
					</td>
					<td><input class="form-control mb-0 promotionPercentage" type="text" name="promotionPercentage[]" min="0" data-index="<?php echo $index; ?>" /></td>
					<td><select class="form-control mb-0 promotionDeliveries" name="promotionDeliveries[]" required>
						<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
						<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
						<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
						<option value="4"><?php _e('4', CIP_TXTDOMAIN); ?></option>
						<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
						<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
						<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
						<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
						<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
						<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
					</select></td>
					<td><select class="form-control mb-0 promotionDeliveryInterval" name="promotionDeliveryInterval[]" required>
						<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
						<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
						<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
						<option value="4" selected><?php _e('4', CIP_TXTDOMAIN); ?></option>
						<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
						<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
						<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
						<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
						<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
						<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
					</select></td>
					<td><input class="form-control mb-0 promotionDeliveryStartWeek" type="text" name="promotionDeliveryStartWeek[]" min="0" max="200" value="80" placeholder="<?php _e('Default will be 80', CIP_TXTDOMAIN); ?>" data-index="<?php echo $index; ?>" required /></td>
				</tr><?php
				$index++;
				}
			}
			$advancedWeeklyOptionHtmlInner .= ob_get_clean();
			$advancedWeeklyOptionHtml .= $advancedWeeklyOptionHtmlInner . '</table>';

			//Week Wise Advanced
			ob_start();
			if( !empty( $createdDateArray ) ){
				$index = 1;
				foreach( $createdDateArray as $createdDateValue ){
				?>
				<tr>
					<td><input class="form-control mb-0 createdDate" type="text" name="week_wise_createdDate[]" value="<?php echo $createdDateValue; ?>" readonly/></td>
					<td><input class="form-control mb-0" type="text" value="<?php echo $poolRefPopulate; ?>" readonly/></td>
					<td><input class="form-control mb-0 csrSegmentation" type="text" name="week_wise_csrSegmentation[]" min="10" value="100" required/></td>
					<td><select class="form-control mb-0 primaryDeliveries week_wise_advanced_primarydeliveries" data-index="<?php echo $index; ?>" name="week_wise_advanced_primaryDeliveries[]">
						<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
						<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
						<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
						<option value="4"><?php _e('4', CIP_TXTDOMAIN); ?></option>
						<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
						<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
						<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
						<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
						<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
						<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
					</select></td>
					<td>
					<select class="form-control mb-0 week_wise_advanced_promotionType" name="week_wise_advanced_promotionType[]" data-index="<?php echo $index; ?>">
						<option value="none"><?php _e('None', CIP_TXTDOMAIN); ?></option>
						<option value="bonus"><?php _e('Bonus', CIP_TXTDOMAIN); ?></option>
						<option value="discount"><?php _e('Discount', CIP_TXTDOMAIN); ?></option>
					</select>
					</td>
					<td><input class="form-control mb-0 promotionPercentage" type="text" name="week_wise_advanced_promotionPercentage[]" min="0" data-index="<?php echo $index; ?>" /></td>
					<td><select class="form-control mb-0 promotionDeliveries week_wise_advanced_promotionDeliveries" name="week_wise_advanced_promotionDeliveries[]" data-index="<?php echo $index; ?>" required>
						<option value="1"><?php _e('1', CIP_TXTDOMAIN); ?></option>
						<option value="2"><?php _e('2', CIP_TXTDOMAIN); ?></option>
						<option value="3"><?php _e('3', CIP_TXTDOMAIN); ?></option>
						<option value="4"><?php _e('4', CIP_TXTDOMAIN); ?></option>
						<option value="5"><?php _e('5', CIP_TXTDOMAIN); ?></option>
						<option value="6"><?php _e('6', CIP_TXTDOMAIN); ?></option>
						<option value="7"><?php _e('7', CIP_TXTDOMAIN); ?></option>
						<option value="8"><?php _e('8', CIP_TXTDOMAIN); ?></option>
						<option value="9"><?php _e('9', CIP_TXTDOMAIN); ?></option>
						<option value="10"><?php _e('10', CIP_TXTDOMAIN); ?></option>
					</select></td>
					</td>
				</tr>
				<tr>
					<td colspan="7">
						<div class="row">
							<div class="col-6 week_wise_advanced_primary_section" data-index="<?php echo $index; ?>">
								<h5>Primary</h5>
								<table class="table table-bordered table-hover mt-2">
									<tr>
										<th>#</th>
										<th>Start Week Number</th>
										<th>Redemption percentage</th>
									</tr>
									<?php for( $i=1; $i <= 10; $i++ ){
										$isShowClass = ( $i == 1 ) ? 'show' : 'hide';
										$isDisable = ( $i == 1 ) ? '' : 'disabled';
									?>
									<tr class="week_wise_advanced_primary_week_loop week_wise_advanced_primary_index_<?php echo $i; ?> <?php echo $isShowClass; ?> ">
										<td><?php echo $i; ?></td>
										<td><input type="text" name="week_wise_advanced_start_week_index_<?php echo $index; ?>[]" class="week_wise_advanced_week_index mb-0 form-control" <?php echo $isDisable; ?> /></td>
										<td><input type="text" name="week_wise_advanced_redemption_percentage_<?php echo $index; ?>[]" class="week_wise_advanced_redemption_percentage mb-0 form-control" <?php echo $isDisable; ?> /></td>
									</tr>
									<?php } ?>
								</table>
							</div>
							<div class="col-6 week_wise_advanced_promotion_section" data-index="<?php echo $index; ?>" style="display: none;">
								<h5>Promotion</h5>
								<table class="table table-bordered table-hover mt-2">
									<tr>
										<th>#</th>
										<th>Start Week Number</th>
										<th>Redemption percentage</th>
									</tr>
									<?php for( $i=1; $i <= 10; $i++ ){
										$isShowClass = ( $i == 1 ) ? 'show' : 'hide';
										$isDisable = ( $i == 1 ) ? '' : 'disabled';
									?>
									<tr class="week_wise_advanced_promotion_week_loop week_wise_advanced_promotion_index_<?php echo $i; ?> <?php echo $isShowClass; ?> ">
										<td><?php echo $i; ?></td>
										<td><input type="text" name="week_wise_advanced_promotion_start_week_index_<?php echo $index; ?>[]" class="week_wise_advanced_promotion_week_index mb-0 form-control" <?php echo $isDisable; ?> /></td>
										<td><input type="text" name="week_wise_advanced_promotion_redemption_percentage_<?php echo $index; ?>[]" class="week_wise_advanced_promotion_redemption_percentage mb-0 form-control" <?php echo $isDisable; ?> /></td>
									</tr>
									<?php } ?>
								</table>
							</div>
						</div>
					</td>
				</tr>
				<?php
				$index++;
				}
			}
			$weekWiseAdvancedWeeklyOptionHtmlInner .= ob_get_clean();
			$weekWiseAdvancedWeeklyOptionHtml .= $weekWiseAdvancedWeeklyOptionHtmlInner . '</table>';

			$out = array( "error" => 0,'msg' => 'Pool reference fetched', 'poolRefPopulate' => $poolRefPopulate, 'advancedWeeklyOptionHtml' => $advancedWeeklyOptionHtml, 'weekWiseAdvancedWeeklyOptionHtml' => $weekWiseAdvancedWeeklyOptionHtml );
			echo wp_json_encode( $out );
			exit;
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['fieldmapping'] ) && $_POST['fieldmapping'] == 'yes' ) ){ // field mapping
			global $table_prefix, $wpdb;
			$tableNewDeliveryPlan = $wpdb->prefix.'new_delivery_plan';
			$tableNewDeliveryPlanTemp = $wpdb->prefix.'new_delivery_plan_temp';
			$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
			$deleteTemp = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
			$csvFile = $_FILES['th_csv_file']['tmp_name'];
			if( ($handle = fopen($csvFile, 'r')) !== false ){
				$file_content = file( $csvFile , FILE_SKIP_EMPTY_LINES);
   				$total_line = count($file_content) - 1;
				$flag = true;
				$countError = 0;
				if( str_contains($_POST['pool_reference'], 'BNS') ){
					$poolReferencePattern  = "/^BNS-[0-9]{4}-[0-9]{2}$/i";
				}else{
					$poolReferencePattern  = "/^PNP-[0-9]{4}-[0-9]{2}$/i";
				}
				if( !preg_match($poolReferencePattern, $_POST['pool_reference']) ){
					$out = array( "error" => 1,'msg' => __('Error : Not valid format of pool reference',CIP_TXTDOMAIN), 'msg2' => __('Error : Not valid format of pool reference',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				while (($rowData = fgetcsv($handle, 0)) !== false) {
					if( $flag ){
						$columnsArr = ['id','username','reference_number','csr_wallet_address','csr_initial','first_name','last_name','created_date','email','source'];
						foreach( $columnsArr as $key => $columnName ){
							if( strtolower($columnName) == strtolower($rowData[ $key] ) ){
								//continue column matched
							}else{
								//error, column not matched
								$out = array( "error" => 1,'msg' => __('Error : column mismatch',CIP_TXTDOMAIN), 'msg2' => __('Error : column mismatch',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}
						$csvdata = array_map('str_getcsv', file( $csvFile ));
						unset( $csvdata[0] );
						if( $csvdata ){
							foreach( $csvdata as $key => $rowData ){
								$rowCounter = $key;
								$username = ( $rowData[ 1 ] != "" ) ? $rowData[ 1 ] : '';
								$reference = ( $rowData[ 2 ] != "" ) ? $rowData[ 2 ] : '';
								$eth_address = ( $rowData[ 3 ] != "" ) ? $rowData[ 3 ] : '';
								$csr_amount_initial = ( $rowData[ 4 ] != "" ) ? str_replace( ',', '', $rowData[ 4 ]) + 0 : '';
								$first_name = ( $rowData[ 5 ] != "" ) ? $rowData[ 5 ] : '';
								$last_name = ( $rowData[ 6 ] != "" ) ? $rowData[ 6 ] : '';
								$created = ( $rowData[ 7 ] != "" ) ? $rowData[ 7 ] : '';
								$email = ( $rowData[ 8 ] != "" ) ? $rowData[ 8 ] : '';
								$source = ( $rowData[ 9 ] != "" ) ? $rowData[ 9 ] : '';
								$validationError = [];
								if( !filter_var($email, FILTER_VALIDATE_EMAIL) ){
									$rowError = true;
									$validationError[] = __('Email is invalid ',CIP_TXTDOMAIN);
								}
								if( empty( $username ) ){
									$rowError = true;
									$validationError[] = __('Username is empty',CIP_TXTDOMAIN);
								}
								if( $csr_amount_initial == "" && $csr_amount_initial < 0 ){
									$rowError = true;
									$validationError[] = __('csr_initial is empty',CIP_TXTDOMAIN);
								}
								if( !is_int( $csr_amount_initial ) ){
									$rowError = true;
									$validationError[] = __('csr_initial is invalid',CIP_TXTDOMAIN);
								}
								if( empty( $created ) || DateTime::createFromFormat('d/m/Y', $created) === false ){
									$rowError = true;
									$validationError[] = __('Created date is empty or invalid format',CIP_TXTDOMAIN);
								}
								if( $source != 'purchase' && $source != 'bonus' ){
									$rowError = true;
									$validationError[] = __('Source is invalid',CIP_TXTDOMAIN);
								}
								$referencePattern  = "/^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$/i";
								if( empty( $reference ) || !preg_match( $referencePattern, $reference ) ){
									$rowError = true;
									$validationError[] = __('Reference is empty or invalid format',CIP_TXTDOMAIN);
								}
								if( !empty( $eth_address ) && AddressValidator::isValid( $eth_address ) !== AddressValidator::ADDRESS_VALID ){
									$rowError = true;
									$validationError[] = __('Address is invalid',CIP_TXTDOMAIN);
								}
								if( $rowError === true ){
									$log_msg = getOrdinal( $rowCounter ) . ' row :: ' . $reference . ' :: failed : ' . implode(', ', $validationError).'<br/>';
									$countError++;
									$error = 1;
									$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s',CIP_TXTDOMAIN), $log_msg ), 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Error : empty data in file',CIP_TXTDOMAIN), 'msg2' => __('Error : empty data in file',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$csvdata = array_chunk( $csvdata, 100 );
						$_SESSION['csvNewDeliveryPlanArray'] = $csvdata;
						$new_total_line = count( $csvdata );
						$out = array( "error" => 0,'msg' => __('Reference checking started...',CIP_TXTDOMAIN), 'msg2' => __('Reference checking started...',CIP_TXTDOMAIN), 'total_line' => $new_total_line, 'totalmsg' => sprintf( __('%s row\'s to process', CIP_TXTDOMAIN),$total_line ) );
						echo wp_json_encode( $out );
						exit;
						$flag = false;
						continue;
					}
					$rowError = false;
				}
				fclose($handle);
			}
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['verification_data'] ) && $_POST['verification_data'] == 'yes' ) ){ // verification process
			global $table_prefix, $wpdb;
			$tableNewDeliveryPlanTemp = $table_prefix.'new_delivery_plan_temp';
			$tableNewDeliveryPlan = $table_prefix . 'new_delivery_plan';
			$tableTokenHolder = $table_prefix . 'token_holder';
			$csvFile = $_FILES['th_csv_file']['tmp_name'];
			$pool_reference = $_POST['pool_reference'];
			$fileName = $_FILES['th_csv_file']['name'];
			$pathFileName = pathinfo($fileName, PATHINFO_FILENAME);
			$pathFileExt = pathinfo($fileName, PATHINFO_EXTENSION);
			$underscroePos = strrpos( $pathFileName, "_" );
			$yearWeekextract = substr( $pathFileName, $underscroePos+1 );
			$fileNameWithoutNumber = substr( $fileName, 0, $underscroePos );
			$week_number = "";
			if( $fileNameWithoutNumber == 'CSR_redemptions_week' && ctype_digit( $yearWeekextract ) ){
				$week_number = mb_substr($yearWeekextract, 4);
			}
			$csr_segmentation = 100;
			if( isset( $_POST['csr_segmentation'] ) && $_POST['csr_segmentation'] >= 10 ){
				$csr_segmentation = $_POST['csr_segmentation'];
			}
			$file_content = file( $csvFile , FILE_SKIP_EMPTY_LINES);
			$total_line = count($file_content) - 1;
			$countError = 0;
			// if( ($handle = fopen($csvFile, 'r')) !== false ){
			if( isset( $_SESSION['csvNewDeliveryPlanArray'] ) && !empty( $_SESSION['csvNewDeliveryPlanArray'] ) ){
				$csvArray = $_SESSION['csvNewDeliveryPlanArray'];
				$splitting_id = $_POST['verification_id'];
				$splittedParts = $csvArray[ $splitting_id ];
				if( !empty( $splittedParts ) && is_array( $splittedParts ) ){
					$importNoticeMsg = sprintf( __('%s row reference checked', CIP_TXTDOMAIN), getOrdinal( $rowCounter ) );
					$msg2 = sprintf( __('%s row reference checked',CIP_TXTDOMAIN), getOrdinal( $rowCounter ) );
					$lastMsg = "";
					$totalMsg = "";
					if( isset( $_POST['isLast'] ) && $_POST['isLast'] == true ){
						$lastMsg = __('Importing data started...', CIP_TXTDOMAIN);
						$totalMsg = sprintf( __('%s row\'s to process', CIP_TXTDOMAIN),$total_line );
					}
					$out = array( "error" => 0, 'msg' => $importNoticeMsg, 'totalCount' => $total_line, 'msg2' => $msg2 , 'lastMsg' => $lastMsg , 'totalMsg' => $totalMsg );
				}
			}
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['userstatus_check'] ) && $_POST['userstatus_check'] == 'yes' ) ){ // userstatus_check process
			global $table_prefix, $wpdb;
			$tableNewDeliveryPlanTemp = $table_prefix.'new_delivery_plan_temp';
			$tableNewDeliveryPlan = $table_prefix . 'new_delivery_plan';
			$tableTokenHolder = $table_prefix . 'token_holder';
			$tableDeliveryCsrPrice = $wpdb->prefix.'delivery_csr_price';
			$countError = 0;
			$countSuccess = 0;
			$csvFile = $_FILES['th_csv_file']['tmp_name'];
			$pool_reference = $_POST['pool_reference'];
			$fileName = $_FILES['th_csv_file']['name'];
			$pathFileName = pathinfo($fileName, PATHINFO_FILENAME);
			$pathFileExt = pathinfo($fileName, PATHINFO_EXTENSION);
			$underscroePos = strrpos( $pathFileName, "_" );
			$yearWeekextract = substr( $pathFileName, $underscroePos+1 );
			$fileNameWithoutNumber = substr( $fileName, 0, $underscroePos );
			if( str_contains($pool_reference, 'BNS') ){
				$weekPos = strripos( $_POST['pool_reference'], "-" );
				$weekNumber = mb_substr( $_POST['pool_reference'], $weekPos+1, 2 );
				$yearPos = stripos( $_POST['pool_reference'], "-" );
				$yearNumber = mb_substr( $_POST['pool_reference'], $yearPos+1, 4 );
			}else{
				$weekPos = strripos( $_POST['pool_reference'], "-" );
				$weekNumber = mb_substr( $_POST['pool_reference'], $weekPos+1, 2 );
				$yearPos = stripos( $_POST['pool_reference'], "-" );
				$yearNumber = mb_substr( $_POST['pool_reference'], $yearPos+1, 4 );
			}
			$file_content = file( $csvFile , FILE_SKIP_EMPTY_LINES);
			$total_line = count($file_content) - 1;
			$csr_segmentation = 100;
			if( isset( $_POST['csr_segmentation'] ) && $_POST['csr_segmentation'] >= 10 ){
				$csr_segmentation = $_POST['csr_segmentation'];
			}

			$week_wise_advanced = ( isset( $_POST['week_wise_advanced'] ) ) ? $_POST['week_wise_advanced'] : 'normal';

			if( $week_wise_advanced == 'week_wise' ){ // week wise delivery

				$primary_number_of_deliveries = ( isset( $_POST['week_wise_primary_number_of_deliveries'] ) ) ? $_POST['week_wise_primary_number_of_deliveries'] : 1;
				$primary_delivery_interval = NULL;
				$primary_delivery_start_week = NULL;
				
				$primary_week_wise_array = [];
				if( isset( $_POST['week_wise_start_week_index'] ) && !empty( $_POST['week_wise_start_week_index'] ) ){
					foreach( $_POST['week_wise_start_week_index'] as $index => $week_wise_start_week_index ){
						$primary_week_wise_array[] = array(
							'week_wise_start_week_index'		=>	$_POST['week_wise_start_week_index'][$index],
							'week_wise_redemption_percentage'	=>	$_POST['week_wise_redemption_percentage'][$index]
						);
					}
				}
				$primary_week_wise = json_encode( $primary_week_wise_array );

				$promotion_type = ( isset( $_POST['week_wise_promotion_type'] ) ) ? $_POST['week_wise_promotion_type'] : 'none';
				$bonus_percentage = ( isset( $_POST['week_wise_bonus_percentage'] ) ) ? $_POST['week_wise_bonus_percentage'] : 0;
				$discount_percentage = ( isset( $_POST['week_wise_discount_percentage'] ) ) ? $_POST['week_wise_discount_percentage'] : 1;

				$promotion_number_of_deliveries = ( isset( $_POST['week_wise_promotion_number_of_deliveries'] ) ) ? $_POST['week_wise_promotion_number_of_deliveries'] : 1;
				$promotion_delivery_interval = NULL;
				$promotion_delivery_start_week = NULL;

				$promotion_week_wise_array = [];
				if( isset( $_POST['week_wise_promotion_start_week_index'] ) && !empty( $_POST['week_wise_promotion_start_week_index'] ) ){
					foreach( $_POST['week_wise_promotion_start_week_index'] as $index => $week_wise_promotion_start_week_index ){
						$promotion_week_wise_array[] = array(
							'week_wise_promotion_start_week_index'		=>	$_POST['week_wise_promotion_start_week_index'][$index],
							'week_wise_promotion_redemption_percentage'	=>	$_POST['week_wise_promotion_redemption_percentage'][$index]
						);
					}
				}
				$promotion_week_wise = json_encode( $promotion_week_wise_array );
				
				// advanced option
				$weekWiseAdvancedWeeklyOptionsValue = array();
				if( isset( $_POST['week_wise_advanced_weekly_wizard_option'] ) && $_POST['week_wise_advanced_weekly_wizard_option'] == 'advanced' ){
					if( is_array( $_POST['week_wise_createdDate'] ) ){
						foreach( $_POST['week_wise_createdDate'] as $key => $createdDate ){

							$index = $key + 1;

							$start_week_index_name = 'week_wise_advanced_start_week_index_' . $index;
							$redemption_percentage_index_name = 'week_wise_advanced_redemption_percentage_' . $index;

							$primary_week_wise_array = [];
							
							$primary_delivery_start_week = 40;
							$promotion_delivery_start_week = 80;

							if( isset( $_POST[ $start_week_index_name ] ) && !empty( $_POST[ $start_week_index_name ] ) ){
								foreach( $_POST[ $start_week_index_name ] as $index_inner => $week_wise_start_week_index ){
									$primary_week_wise_array[] = array(
										'week_wise_start_week_index'		=>	$_POST[ $start_week_index_name ][$index_inner],
										'week_wise_redemption_percentage'	=>	$_POST[ $redemption_percentage_index_name ][$index_inner]
									);
									if( $index_inner == 0 ){
										$primary_delivery_start_week = $_POST[ $start_week_index_name ][$index_inner];
									}
								}
							}
							$primary_week_wise = json_encode( $primary_week_wise_array );


							$start_week_promotion_index_name = 'week_wise_advanced_promotion_start_week_index_' . $index;
							$promotion_redemption_percentage_index_name = 'week_wise_advanced_promotion_redemption_percentage_' . $index;

							$promotion_week_wise_array = [];
							if( isset( $_POST[ $start_week_promotion_index_name ] ) && !empty( $_POST[ $start_week_promotion_index_name ] ) ){
								foreach( $_POST[ $start_week_promotion_index_name ] as $index_inner => $week_wise_start_week_index ){
									$promotion_week_wise_array[] = array(
										'week_wise_promotion_start_week_index'		=>	$_POST[ $start_week_promotion_index_name ][$index_inner],
										'week_wise_promotion_redemption_percentage'	=>	$_POST[ $promotion_redemption_percentage_index_name ][$index_inner]
									);
									if( $index_inner == 0 ){
										$promotion_delivery_start_week = $_POST[ $start_week_promotion_index_name ][$index_inner];
									}
								}
							}
							$promotion_week_wise = json_encode( $promotion_week_wise_array );


							$weekWiseAdvancedWeeklyOptionsValue[ $createdDate ] = array(
								'created'							=>	$createdDate,
								'csr_segmentation'					=>	$_POST['week_wise_csrSegmentation'][ $key ],
								'primary_number_of_deliveries'		=>	$_POST['week_wise_advanced_primaryDeliveries'][ $key ],
								'primary_delivery_interval'			=>	NULL,
								'primary_delivery_start_week'		=>	$primary_delivery_start_week,
								'primary_week_wise'					=> 	$primary_week_wise,
								'promotion_type'					=>	$_POST['week_wise_advanced_promotionType'][ $key ],
								'bonus_percentage'					=>	$_POST['week_wise_advanced_promotionPercentage'][ $key ],
								'discount_percentage'				=>	$_POST['week_wise_advanced_promotionPercentage'][ $key ],
								'promotion_number_of_deliveries'	=>	$_POST['week_wise_advanced_promotionDeliveries'][ $key ],
								'promotion_delivery_interval'		=>	NULL,
								'promotion_delivery_start_week'		=>	$promotion_delivery_start_week,
								'promotion_week_wise'				=>	$promotion_week_wise,
							);
						}
					}
				}

			}else{	//normal delivery

				$primary_number_of_deliveries = ( isset( $_POST['primary_number_of_deliveries'] ) ) ? $_POST['primary_number_of_deliveries'] : 1;
				$primary_delivery_interval = ( isset( $_POST['primary_delivery_interval'] ) ) ? $_POST['primary_delivery_interval'] : 4;
				$primary_delivery_start_week = ( isset( $_POST['primary_delivery_start_week'] ) ) ? $_POST['primary_delivery_start_week'] : 40;
				if( $primary_number_of_deliveries == 1 ){
					$primary_delivery_interval = 1;
				}
				$promotion_type = ( isset( $_POST['promotion_type'] ) ) ? $_POST['promotion_type'] : 'none';
				$bonus_percentage = ( isset( $_POST['bonus_percentage'] ) ) ? $_POST['bonus_percentage'] : 0;
				$discount_percentage = ( isset( $_POST['discount_percentage'] ) ) ? $_POST['discount_percentage'] : 1;
				$promotion_number_of_deliveries = ( isset( $_POST['promotion_number_of_deliveries'] ) ) ? $_POST['promotion_number_of_deliveries'] : 1;
				$promotion_delivery_interval = ( isset( $_POST['promotion_delivery_interval'] ) ) ? $_POST['promotion_delivery_interval'] : 4;
				$promotion_delivery_start_week = ( isset( $_POST['promotion_delivery_start_week'] ) ) ? $_POST['promotion_delivery_start_week'] : 80;
				if( $promotion_number_of_deliveries == 1 ){
					$promotion_delivery_interval = 1;
				}
				// advanced option
				$advancedWeeklyOptionsValue = array();
				if( isset( $_POST['advanced_weekly_wizard_option'] ) && $_POST['advanced_weekly_wizard_option'] == 'advanced' ){
					if( is_array( $_POST['createdDate'] ) ){
						foreach( $_POST['createdDate'] as $key => $createdDate ){
							$advancedWeeklyOptionsValue[ $createdDate ] = array(
								'created'							=>	$createdDate,
								'csr_segmentation'					=>	$_POST['csrSegmentation'][ $key ],
								'primary_number_of_deliveries'		=>	$_POST['primaryDeliveries'][ $key ],
								'primary_delivery_interval'			=>	( $_POST['primaryDeliveries'][ $key ] == 1 ) ? 1 : $_POST['primaryDeliveryInterval'][ $key ],
								'primary_delivery_start_week'		=>	$_POST['primaryDeliveryStartWeek'][ $key ],
								'promotion_type'					=>	$_POST['promotionType'][ $key ],
								'bonus_percentage'					=>	$_POST['promotionPercentage'][ $key ],
								'discount_percentage'				=>	$_POST['promotionPercentage'][ $key ],
								'promotion_number_of_deliveries'	=>	$_POST['promotionDeliveries'][ $key ],
								'promotion_delivery_interval'		=>	( $_POST['promotionDeliveries'][ $key ] == 1 ) ? 1 : $_POST['promotionDeliveryInterval'][ $key ],
								'promotion_delivery_start_week'		=>	$_POST['promotionDeliveryStartWeek'][ $key ],
							);
						}
					}
				}

			}

			// if( ($handle = fopen($csvFile, 'r')) !== false ){
			if( isset( $_SESSION['csvNewDeliveryPlanArray'] ) && !empty( $_SESSION['csvNewDeliveryPlanArray'] ) ){
				$csvArray = $_SESSION['csvNewDeliveryPlanArray'];
				$splitting_id = $_POST['verification_id'];
				$splittedParts = $csvArray[ $splitting_id ];
				if( !empty( $splittedParts ) && is_array( $splittedParts ) ){
					foreach( $splittedParts as $key => $rowData ){
						$rowCounter = ( $splitting_id * 100 ) + ( $key + 1 );
						$username = ( $rowData[ 1 ] != "" ) ? $rowData[ 1 ] : '';
						$reference = ( $rowData[ 2 ] != "" ) ? $rowData[ 2 ] : '';
						$eth_address = ( $rowData[ 3 ] != "" ) ? $rowData[ 3 ] : '';
						$csr_amount_initial = ( $rowData[ 4 ] != "" ) ? str_replace( ',', '', $rowData[ 4 ]) : 0;
						$first_name = ( $rowData[ 5 ] != "" ) ? $rowData[ 5 ] : '';
						$last_name = ( $rowData[ 6 ] != "" ) ? $rowData[ 6 ] : '';
						$created = ( $rowData[ 7 ] != "" ) ? $rowData[ 7 ] : '';
						$email = ( $rowData[ 8 ] != "" ) ? $rowData[ 8 ] : '';
						$source = ( $rowData[ 9 ] != "" ) ? $rowData[ 9 ] : '';
						$member_status = "active";
						$validationError = [];

						if( $week_wise_advanced == 'week_wise' ){
							// advanced option
							if( isset( $_POST['week_wise_advanced_weekly_wizard_option'] ) && $_POST['week_wise_advanced_weekly_wizard_option'] == 'advanced' && !empty( $weekWiseAdvancedWeeklyOptionsValue ) ){
								$advancedOption = $weekWiseAdvancedWeeklyOptionsValue[ $created ];
								if( isset( $weekWiseAdvancedWeeklyOptionsValue[ $created ] ) && !empty( $weekWiseAdvancedWeeklyOptionsValue[ $created ] ) ){
									$csr_segmentation = ( isset( $advancedOption['csr_segmentation'] ) ) ? $advancedOption['csr_segmentation'] : 100;
									$primary_number_of_deliveries = ( isset( $advancedOption['primary_number_of_deliveries'] ) ) ? $advancedOption['primary_number_of_deliveries'] : 1;
									$primary_delivery_interval = NULL;
									$primary_delivery_start_week = ( isset( $advancedOption['primary_delivery_start_week'] ) ) ? $advancedOption['primary_delivery_start_week'] : 40;
									$primary_week_wise = ( isset( $advancedOption['primary_week_wise'] ) ) ? $advancedOption['primary_week_wise'] : NULL;
									
									$promotion_type = ( isset( $advancedOption['promotion_type'] ) ) ? $advancedOption['promotion_type'] : 'none';
									$bonus_percentage = ( isset( $advancedOption['bonus_percentage'] ) ) ? $advancedOption['bonus_percentage'] : 0;
									$discount_percentage = ( isset( $advancedOption['discount_percentage'] ) ) ? $advancedOption['discount_percentage'] : 1;
									$promotion_number_of_deliveries = ( isset( $advancedOption['promotion_number_of_deliveries'] ) ) ? $advancedOption['promotion_number_of_deliveries'] : 1;
									$promotion_delivery_interval = NULL;
									$promotion_delivery_start_week = ( isset( $advancedOption['promotion_delivery_start_week'] ) ) ? $advancedOption['promotion_delivery_start_week'] : 80;
									$promotion_week_wise = ( isset( $advancedOption['promotion_week_wise'] ) ) ? $advancedOption['promotion_week_wise'] : NULL;
								}
							}
						}else{
							// advanced option
							if( isset( $_POST['advanced_weekly_wizard_option'] ) && $_POST['advanced_weekly_wizard_option'] == 'advanced' && !empty( $advancedWeeklyOptionsValue ) ){
								$advancedOption = $advancedWeeklyOptionsValue[ $created ];
								if( isset( $advancedWeeklyOptionsValue[ $created ] ) && !empty( $advancedWeeklyOptionsValue[ $created ] ) ){
									$csr_segmentation = ( isset( $advancedOption['csr_segmentation'] ) ) ? $advancedOption['csr_segmentation'] : 100;
									$primary_number_of_deliveries = ( isset( $advancedOption['primary_number_of_deliveries'] ) ) ? $advancedOption['primary_number_of_deliveries'] : 1;
									$primary_delivery_interval = ( isset( $advancedOption['primary_delivery_interval'] ) ) ? $advancedOption['primary_delivery_interval'] : 4;
									$primary_delivery_start_week = ( isset( $advancedOption['primary_delivery_start_week'] ) ) ? $advancedOption['primary_delivery_start_week'] : 40;
									if( $primary_number_of_deliveries == 1 ){
										$primary_delivery_interval = 1;
									}
									$promotion_type = ( isset( $advancedOption['promotion_type'] ) ) ? $advancedOption['promotion_type'] : 'none';
									$bonus_percentage = ( isset( $advancedOption['bonus_percentage'] ) ) ? $advancedOption['bonus_percentage'] : 0;
									$discount_percentage = ( isset( $advancedOption['discount_percentage'] ) ) ? $advancedOption['discount_percentage'] : 1;
									$promotion_number_of_deliveries = ( isset( $advancedOption['promotion_number_of_deliveries'] ) ) ? $advancedOption['promotion_number_of_deliveries'] : 1;
									$promotion_delivery_interval = ( isset( $advancedOption['promotion_delivery_interval'] ) ) ? $advancedOption['promotion_delivery_interval'] : 4;
									$promotion_delivery_start_week = ( isset( $advancedOption['promotion_delivery_start_week'] ) ) ? $advancedOption['promotion_delivery_start_week'] : 80;
									if( $promotion_number_of_deliveries == 1 ){
										$promotion_delivery_interval = 1;
									}
								}
							}
						}

						if( $_POST['token'] == 'CSR25' ){
							$selling_price_csr25 = ( !empty( get_option('selling_price_csr25') ) ) ? get_option('selling_price_csr25') : 1;
							$csrPrice = 0;
							if( $selling_price_csr25 ){
								$csrPrice = $selling_price_csr25;
							}
						}else{
							$filterDataObj = DateTime::createFromFormat('d/m/Y', $created);
							$filterData = $filterDataObj->format('Y-m-d');
							$getCsrPriceByDate = $wpdb->get_row("SELECT `csr_price` FROM $tableDeliveryCsrPrice WHERE 1 AND DATE_FORMAT(`start_date`,'%Y-%m-%d') <= '".$filterData."' AND `status` != 'deleted' ORDER BY `start_date` DESC LIMIT 1");
							$csrPrice = 0;
							if( $getCsrPriceByDate ){
								$csrPrice = $getCsrPriceByDate->csr_price;
							}
						}
						if( !$csrPrice ){
							$error = 1;
							$countError++;
							if( $_POST['token'] != 'CSR25' ){
								$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
							}
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row, CSR Price not found',CIP_TXTDOMAIN), getOrdinal( $rowCounter ) ), 'totalCount' => $total_line, 'msg2' => 'An error occurred' );
							echo wp_json_encode( $out );
							exit;
						}
						$distribution_status = "Pending";
						if( $eth_address != "") {
							$security_hold_check = $wpdb->get_row("SELECT id,corp_approved FROM $tableTokenHolder WHERE `eth_address` = '".$eth_address."' AND `username` = '".$username."' AND ( `corp_approved` = 'Security Hold' OR `corp_approved` = 'Hold' ) LIMIT 1");
							if( $security_hold_check ){
								$distribution_status = $security_hold_check->corp_approved;
							}
						}else if( empty( $eth_address ) ){
							// $distribution_status = 'Missing CSR address';
							$distribution_status = 'Pending';
						}
						setlocale(LC_ALL, "en_US.utf8");
						$normal_first_name = iconv('UTF-8', 'ASCII//TRANSLIT', wp_strip_all_tags( $first_name ) );
						$normal_last_name = iconv('UTF-8', 'ASCII//TRANSLIT', wp_strip_all_tags( $last_name ) );
						$new_pool_reference = sprintf( 'PNP-%s-%s', $yearNumber, sprintf("%02d", $weekNumber) );
						$data = [
							'username'						=>	wp_strip_all_tags( $username ),
							'reference'						=>	wp_strip_all_tags( $reference ),
							'eth_address'					=>	wp_strip_all_tags( $eth_address ),
							'csr_amount_initial'			=>	ceil( wp_strip_all_tags( $csr_amount_initial ) ),
							'first_name'					=>	ucwords( strtolower( $normal_first_name ) ),
							'last_name'						=>	ucwords( strtolower( $normal_last_name ) ),
							'created'						=>	$created,
							'email'							=>	wp_strip_all_tags( $email ),
							'csr_amount_issued'				=>	0,
							'amount_due'					=>	0,
							'distribution_status'			=>	$distribution_status,
							'member_status'					=>	$member_status,
							// 'pool_ref'						=>	$pool_reference,
							'pool_ref'						=>	$new_pool_reference,
							'source'						=>	$source,
							'week_number'					=>	$weekNumber,
							'year_number'					=>	$yearNumber,
							'csr_segmentation'				=>	$csr_segmentation,
							'week_wise_advanced'			=>	$week_wise_advanced,
							'csr_price'						=>	$csrPrice,
							'import_by'						=>	get_current_user_id(),
							'import_date'					=>	date_i18n( 'Y-m-d H:i:s' ),
							'primary_number_of_deliveries'	=>	$primary_number_of_deliveries,
							'primary_delivery_interval'		=>	$primary_delivery_interval,
							'primary_delivery_start_week'	=>	$primary_delivery_start_week,
							'promotion_type'				=>	$promotion_type,
							'bonus_percentage'				=>	$bonus_percentage,
							'discount_percentage'			=>	$discount_percentage,
							'promotion_number_of_deliveries'=>	$promotion_number_of_deliveries,
							'promotion_delivery_interval'	=>	$promotion_delivery_interval,
							'promotion_delivery_start_week'	=>	$promotion_delivery_start_week,
							'token'							=>	( $_POST['token'] == 'CSR25' ) ? 'CSR25' : 'CSR',
							'primary_week_wise'				=>	$primary_week_wise,
							'promotion_week_wise'			=>	$promotion_week_wise
						];
						$inserting = $wpdb->insert( $tableNewDeliveryPlanTemp, $data );
						if( $inserting ){
							$countSuccess++;
						}else{
							$error = 1;
							$countError++;
							$errorText = $wpdb->last_error;
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $rowCounter ) ), 'totalCount' => $total_line, 'msg2' => $errorText );
							echo wp_json_encode( $out );
							exit;
						}
					}
					$importNoticeMsg = sprintf( __('%s row imported', CIP_TXTDOMAIN), getOrdinal( $rowCounter ) );
					$msg2 = sprintf( __('%s row imported',CIP_TXTDOMAIN), getOrdinal( $rowCounter ) );
					$out = array( "error" => 0, 'msg' => $importNoticeMsg, 'totalCount' => $total_line, 'msg2' => $msg2 );
					if( $rowCounter == $total_line ){
						$user_type = 'sm';
						$log_type = 'new_delivery_plan_file_import';
						$logs = sprintf( __('Import delivery plan of week %s, file name:%s, segmentation:%s at %s', CIP_TXTDOMAIN), $yearNumber.'/'.$weekNumber, $fileName, $csr_segmentation, date_i18n('d/m/Y H:i:s') );
						create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
					}
				}
			}
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['splitting_start'] ) && $_POST['splitting_start'] == 'yes' ) ){ //splitting count loop
			global $table_prefix, $wpdb;
			$tableNewDeliveryPlanTemp = $table_prefix.'new_delivery_plan_temp';
			$tableNewDeliveryPlan = $table_prefix . 'new_delivery_plan';
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableNewDeliveryPlanTemp WHERE 1");
			$per_page = 100;
			$total_paged = ceil( $total_items / $per_page );
			$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
			$out = array( "error" => 0, 'total_items' => $total_items, 'total_paged' => $total_paged,'msg' => __('Splitting deliveries started...',CIP_TXTDOMAIN), 'msg2' => __('Splitting deliveries started...',CIP_TXTDOMAIN), 'totalmsg' => sprintf( __('%s row\'s to process', CIP_TXTDOMAIN),$total_items ) );
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['splitting_data'] ) && $_POST['splitting_data'] == 'yes' ) ){ // splitting start
			global $table_prefix, $wpdb;
			$tableNewDeliveryPlanTemp = $table_prefix.'new_delivery_plan_temp';
			$tableNewDeliveryPlan = $table_prefix . 'new_delivery_plan';
			$tableTokenHolder = $table_prefix . 'token_holder';
			//==================================================//
			$csvFile = $_FILES['th_csv_file']['tmp_name'];
			$pool_reference = $_POST['pool_reference'];
			$per_page = 100;
			$paged = isset( $_POST['page_id'] ) ? max( 0, intval( $_POST['page_id'] -1 ) * $per_page ) : 0;
			$error = 0;
			$rowDataCount= 0;
			$countError = 0;
			$countSuccess = 0;
			$insertingCount = 1;
			$rowDataCount = 0;
			$getTempDatas = $wpdb->get_results("SELECT * FROM $tableNewDeliveryPlanTemp WHERE 1 LIMIT ".$per_page." OFFSET ".$paged."");
			if( $getTempDatas ){
				$totalNumberWeek = 52;
				$primary_number_of_deliveries = ( isset( $_POST['primary_number_of_deliveries'] ) ) ? $_POST['primary_number_of_deliveries'] : 1;
				$primary_delivery_interval = ( isset( $_POST['primary_delivery_interval'] ) ) ? $_POST['primary_delivery_interval'] : 4;
				$primary_delivery_start_week = ( isset( $_POST['primary_delivery_start_week'] ) ) ? $_POST['primary_delivery_start_week'] : 40;
				if( $primary_number_of_deliveries == 1 ){
					$primary_delivery_interval = 1;
				}
				//Primary CSR
				foreach( $getTempDatas as $getTempData ){
					$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
					$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
					$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
					$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? ceil( str_replace( ',', '', $getTempData->csr_amount_initial) ) : 0;
					$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
					$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
					$created_formatted = ( $getTempData->created != "" ) ? $getTempData->created : '';
					$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
					$source = ( $getTempData->source != "" ) ? $getTempData->source : '';
					$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
					$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
					$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
					$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
					$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';
					$token = ( $getTempData->token != "" ) ? $getTempData->token : 'CSR';
					$new_pool_reference = sprintf( 'PNP-%s-%s', $year_number, sprintf("%02d", $week_number) );
					$redemptionWeek = $week_number;
					$redemptionYear = $year_number;
					$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
					$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
					$validationError = [];

					$week_wise_advanced = ( $getTempData->week_wise_advanced != "" ) ? $getTempData->week_wise_advanced : 'normal';
					if( $week_wise_advanced == 'week_wise' ){

						$primary_number_of_deliveries = ( isset( $getTempData->primary_number_of_deliveries ) ) ? $getTempData->primary_number_of_deliveries : 1;
						$primary_delivery_interval = NULL;
						$primary_delivery_start_week = NULL;
						
						$primary_week_wise_arr = json_decode($getTempData->primary_week_wise, true);

						$total_primary_redemption_percentage = 0;
						if( !empty( $primary_week_wise_arr ) ){
							foreach( $primary_week_wise_arr as $key => $primary_week_wise_data ){
								$primary_delivery_start_week = $primary_week_wise_data['week_wise_start_week_index'];
								$primary_redemption_percentage = $primary_week_wise_data['week_wise_redemption_percentage'];
								$total_primary_redemption_percentage += $primary_redemption_percentage;
							}
						}
						if( $total_primary_redemption_percentage != 100 ){
							$out = array( "error" => 1, 'msg' => __('Primary CSR : Invalid redemption percentage',CIP_TXTDOMAIN), 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

						if( $csr_amount_initial <= $csr_segmentation ){

							$primary_delivery_start_week = ( isset( $getTempData->primary_delivery_start_week ) ) ? $getTempData->primary_delivery_start_week : 40;

							if( $primary_delivery_start_week > 0 ){
								for( $week_i=0; $week_i < $primary_delivery_start_week; $week_i++ ){
									$week_number = $week_number + 1;
									if( $week_number > $totalNumberWeek ){
										$week_number = $week_number - $totalNumberWeek;
										$year_number = $year_number + 1;
									}else{
										$year_number = $year_number;
									}
								}
							}

							$admNo = $reference.'-000';
							$newAdmNo = ++$admNo;
							$amount_due = $csr_amount_initial;
							if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
								$corp_approved_10 = $distribution_status;
							}else{
								$corp_approved_10 = 'Pending';
							}
							$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
							if( $distribution_status == 'Security Hold' ){
								$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
							}
							$notes_external_10 = notes_trim_pipe( $notes_external_10 );
							$data = [
								'username'					=>	wp_strip_all_tags( $username ),
								'reference'					=>	wp_strip_all_tags( 'PNP-' .$newAdmNo ),
								'eth_address'				=>	wp_strip_all_tags( $eth_address ),
								'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
								'first_name'				=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
								'last_name'					=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
								'created'					=>	$created_formatted,
								'email'						=>	wp_strip_all_tags( $email ),
								'csr_amount_issued'			=>	0,
								'amount_due'				=>	$amount_due,
								'distribution_status'		=>	$distribution_status,
								'member_status'				=>	$member_status,
								'corp_approved'				=>	$corp_approved_10,
								'notes_external'			=>	$notes_external_10,
								'pool_ref'					=>	$new_pool_reference,
								'source'					=>	$source,
								'week_number'				=>	$year_number.'/'.sprintf("%02d", $week_number),
								'csr_segmentation'			=>	$csr_segmentation,
								'import_by'					=>	$import_by,
								'import_date'				=>	$import_date,
								'csr_type'					=>	'primary',
								'token'						=>	$token
							];
							$inserting = $wpdb->insert( $tableNewDeliveryPlan, $data );
							if( $inserting ){
								$countSuccess++;
							}else{
								$error = 1;
								$countError++;
								$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
								$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
								$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}else{

							if( !empty( $primary_week_wise_arr ) ){
								$csr_amount_pending = $csr_amount_initial;
								$totalCalculated = 0;
								$newAdmNo = "";
								foreach( $primary_week_wise_arr as $key => $primary_week_wise_data ){
									$primary_delivery_start_week = $primary_week_wise_data['week_wise_start_week_index'];
									$primary_redemption_percentage = $primary_week_wise_data['week_wise_redemption_percentage'];
	
									$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
									$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
	
									for( $week_i=0; $week_i < $primary_delivery_start_week; $week_i++ ){
										$week_number = $week_number + 1;
										if( $week_number > $totalNumberWeek ){
											$week_number = $week_number - $totalNumberWeek;
											$year_number = $year_number + 1;
										}else{
											$year_number = $year_number;
										}
									}
									
									if ($key === count($primary_week_wise_arr) - 1) {
										$amount_due = $csr_amount_initial - $totalCalculated;
									} else {
										$value = floor($csr_amount_initial * ($primary_redemption_percentage / 100));
										$amount_due = $value;
										$totalCalculated += $value;
									}
									
									
									if( $key == 0 ){
										$admNo = $reference.'-000';
									}else{
										$admNo = $newAdmNo;
									}
									$newAdmNo = ++$admNo;
									if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
										$corp_approved_10 = $distribution_status;
									}else{
										$corp_approved_10 = 'Pending';
									}
									
									$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);
									$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
									if( $distribution_status == 'Security Hold' ){
										$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
									}
									$notes_external_10 = notes_trim_pipe( $notes_external_10 );
									$data = [
										'username'					=>	wp_strip_all_tags( $username ),
										'reference'					=>	wp_strip_all_tags( 'PNP-' .$newAdmNo ),
										'eth_address'				=>	wp_strip_all_tags( $eth_address ),
										'csr_amount_initial'		=>	$csr_amount_initial,
										'first_name'				=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
										'last_name'					=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
										'created'					=>	$created_formatted,
										'email'						=>	wp_strip_all_tags( $email ),
										'csr_amount_issued'			=>	0,
										'amount_due'				=>	$amount_due,
										'distribution_status'		=>	$distribution_status,
										'member_status'				=>	$member_status,
										'corp_approved'				=>	$corp_approved_10,
										'notes_external'			=>	$notes_external_10,
										'pool_ref'					=>	$new_pool_reference,
										'source'					=>	$source,
										'week_number'				=>	$new_week_number,
										'csr_segmentation'			=>	$csr_segmentation,
										'import_by'					=>	$import_by,
										'import_date'				=>	$import_date,
										'csr_type'					=>	'primary',
										'token'						=>	$token
									];
									$csr_amount_pending = $csr_amount_pending - $amount_due;
									$inserting = $wpdb->insert( $tableNewDeliveryPlan, $data );
									if( $inserting ){
										$countSuccess++;
									}else{
										$error = 1;
										$countError++;
										$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
										$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
										$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
										echo wp_json_encode( $out );
										exit;
									}
	
								}
							}

						}


					}else{
						
						// advanced option
						if( isset( $_POST['advanced_weekly_wizard_option'] ) && $_POST['advanced_weekly_wizard_option'] == 'advanced' ){
							$primary_number_of_deliveries = ( isset( $getTempData->primary_number_of_deliveries ) ) ? $getTempData->primary_number_of_deliveries : 1;
							$primary_delivery_interval = ( isset( $getTempData->primary_delivery_interval ) ) ? $getTempData->primary_delivery_interval : 4;
							$primary_delivery_start_week = ( isset( $getTempData->primary_delivery_start_week ) ) ? $getTempData->primary_delivery_start_week : 40;
							if( $primary_number_of_deliveries == 1 ){
								$primary_delivery_interval = 1;
							}
						}
						if( $primary_delivery_start_week > 0 ){
							for( $week_i=0; $week_i < $primary_delivery_start_week; $week_i++ ){
								$week_number = $week_number + 1;
								if( $week_number > $totalNumberWeek ){
									$week_number = $week_number - $totalNumberWeek;
									$year_number = $year_number + 1;
								}else{
									$year_number = $year_number;
								}
							}
						}
						if( $csr_amount_initial <= $csr_segmentation ){
							$admNo = $reference.'-000';
							$newAdmNo = ++$admNo;
							$amount_due = $csr_amount_initial;
							if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
								$corp_approved_10 = $distribution_status;
							}else{
								$corp_approved_10 = 'Pending';
							}
							$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
							if( $distribution_status == 'Security Hold' ){
								$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
							}
							$notes_external_10 = notes_trim_pipe( $notes_external_10 );
							$data = [
								'username'					=>	wp_strip_all_tags( $username ),
								'reference'					=>	wp_strip_all_tags( 'PNP-' .$newAdmNo ),
								'eth_address'				=>	wp_strip_all_tags( $eth_address ),
								'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
								'first_name'				=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
								'last_name'					=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
								'created'					=>	$created_formatted,
								'email'						=>	wp_strip_all_tags( $email ),
								'csr_amount_issued'			=>	0,
								'amount_due'				=>	$amount_due,
								'distribution_status'		=>	$distribution_status,
								'member_status'				=>	$member_status,
								'corp_approved'				=>	$corp_approved_10,
								'notes_external'			=>	$notes_external_10,
								// 'pool_ref'					=>	$pool_reference,
								'pool_ref'					=>	$new_pool_reference,
								'source'					=>	$source,
								'week_number'				=>	$year_number.'/'.sprintf("%02d", $week_number),
								'csr_segmentation'			=>	$csr_segmentation,
								'import_by'					=>	$import_by,
								'import_date'				=>	$import_date,
								'csr_type'					=>	'primary',
								'token'						=>	$token
							];
							$inserting = $wpdb->insert( $tableNewDeliveryPlan, $data );
							if( $inserting ){
								$countSuccess++;
							}else{
								$error = 1;
								$countError++;
								$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
								$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
								$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}else{
							$csr_amount_pending = $csr_amount_initial;
							$newAdmNo = "";
							for( $i=0; $i < $primary_number_of_deliveries; $i++ ){
								$amount_due = $csr_amount_pending / ( $primary_number_of_deliveries - $i );
								$amount_due = ceil( $amount_due );
								if( $i == 0 ){
									$admNo = $reference.'-000';
								}else{
									$admNo = $newAdmNo;
								}
								$newAdmNo = ++$admNo;
								if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
									$corp_approved_10 = $distribution_status;
								}else{
									$corp_approved_10 = 'Pending';
								}
								if( $week_number > $totalNumberWeek ){
									$week_number = $week_number - $totalNumberWeek;
									$year_number = $year_number + 1;
								}else{
									$year_number = $year_number;
								}
								$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);
								$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
								if( $distribution_status == 'Security Hold' ){
									$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
								}
								$notes_external_10 = notes_trim_pipe( $notes_external_10 );
								$data = [
									'username'					=>	wp_strip_all_tags( $username ),
									'reference'					=>	wp_strip_all_tags( 'PNP-' .$newAdmNo ),
									'eth_address'				=>	wp_strip_all_tags( $eth_address ),
									'csr_amount_initial'		=>	$csr_amount_initial,
									// 'csr_amount_initial'		=>	$csr_amount_pending,
									'first_name'				=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
									'last_name'					=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
									'created'					=>	$created_formatted,
									'email'						=>	wp_strip_all_tags( $email ),
									'csr_amount_issued'			=>	0,
									'amount_due'				=>	$amount_due,
									'distribution_status'		=>	$distribution_status,
									'member_status'				=>	$member_status,
									'corp_approved'				=>	$corp_approved_10,
									'notes_external'			=>	$notes_external_10,
									// 'pool_ref'					=>	$pool_reference,
									'pool_ref'					=>	$new_pool_reference,
									'source'					=>	$source,
									'week_number'				=>	$new_week_number,
									'csr_segmentation'			=>	$csr_segmentation,
									'import_by'					=>	$import_by,
									'import_date'				=>	$import_date,
									'csr_type'					=>	'primary',
									'token'						=>	$token
								];
								$csr_amount_pending = $csr_amount_pending - $amount_due;
								$inserting = $wpdb->insert( $tableNewDeliveryPlan, $data );
								if( $inserting ){
									$countSuccess++;
								}else{
									$error = 1;
									$countError++;
									$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
									$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
									$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}
								// $week_number++;
								$week_number = $week_number + $primary_delivery_interval;
							}
						}

					}

					$rowDataCount = $getTempData->id;
				}
				
				//Promotion CSR
				$promotion_type = ( isset( $_POST['promotion_type'] ) ) ? $_POST['promotion_type'] : 'none';
				$bonus_percentage = ( isset( $_POST['bonus_percentage'] ) ) ? $_POST['bonus_percentage'] : 0;
				$discount_percentage = ( isset( $_POST['discount_percentage'] ) ) ? $_POST['discount_percentage'] : 1;
				$promotion_number_of_deliveries = ( isset( $_POST['promotion_number_of_deliveries'] ) ) ? $_POST['promotion_number_of_deliveries'] : 1;
				$promotion_delivery_interval = ( isset( $_POST['promotion_delivery_interval'] ) ) ? $_POST['promotion_delivery_interval'] : 4;
				$promotion_delivery_start_week = ( isset( $_POST['promotion_delivery_start_week'] ) ) ? $_POST['promotion_delivery_start_week'] : 80;
				if( $promotion_number_of_deliveries == 1 ){
					$promotion_delivery_interval = 1;
				}
				$allowBonusDiscount = false;

				if( isset( $_POST['week_wise_advanced'] ) && $_POST['week_wise_advanced'] == 'week_wise' ){ // week wise delivery

					$promotion_type = ( isset( $_POST['week_wise_promotion_type'] ) ) ? $_POST['week_wise_promotion_type'] : 'none';
					// advanced option
					if( isset( $_POST['week_wise_advanced_weekly_wizard_option'] ) && $_POST['week_wise_advanced_weekly_wizard_option'] == 'advanced' ){
						$allowBonusDiscount = true;
					}else if( $promotion_type == 'bonus' || $promotion_type == 'discount' ){
						$allowBonusDiscount = true;
					}
				}else{	// normal delivery
					// advanced option
					if( isset( $_POST['advanced_weekly_wizard_option'] ) && $_POST['advanced_weekly_wizard_option'] == 'advanced' ){
						$allowBonusDiscount = true;
					}else if( $promotion_type == 'bonus' || $promotion_type == 'discount' ){
						$allowBonusDiscount = true;
					}
				}

				if( $allowBonusDiscount ){
					foreach( $getTempDatas as $getTempData ){

						$week_wise_advanced = ( $getTempData->week_wise_advanced != "" ) ? $getTempData->week_wise_advanced : 'normal';
						if( $week_wise_advanced == 'week_wise' ){ // week wise bonus
							
							$promotion_type = ( isset( $getTempData->promotion_type ) ) ? $getTempData->promotion_type : 'none';
							$bonus_percentage = ( isset( $getTempData->bonus_percentage ) ) ? $getTempData->bonus_percentage : 0;
							$discount_percentage = ( isset( $getTempData->discount_percentage ) ) ? $getTempData->discount_percentage : 1;
							$promotion_number_of_deliveries = ( isset( $getTempData->promotion_number_of_deliveries ) ) ? $getTempData->promotion_number_of_deliveries : 1;
							$promotion_delivery_interval = NULL;
							$promotion_delivery_start_week = ( isset( $getTempData->promotion_delivery_start_week ) ) ? $getTempData->promotion_delivery_start_week : 80;

							
							if( $promotion_type == 'bonus' || $promotion_type == 'discount' ){

								$promotion_week_wise_arr = json_decode($getTempData->promotion_week_wise, true);

								$total_promotion_redemption_percentage = 0;
								if( !empty( $promotion_week_wise_arr ) ){
									foreach( $promotion_week_wise_arr as $key => $promotion_week_wise_data ){
										$promotion_delivery_start_week = $promotion_week_wise_data['week_wise_promotion_start_week_index'];
										$promotion_redemption_percentage = $promotion_week_wise_data['week_wise_promotion_redemption_percentage'];
										$total_promotion_redemption_percentage += $promotion_redemption_percentage;
									}
								}
								if( $total_promotion_redemption_percentage != 100 ){
									$out = array( "error" => 1, 'msg' => __('Promotion CSR : Invalid redemption percentage',CIP_TXTDOMAIN), 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}

								$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
								$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
								$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
								$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? ceil( str_replace( ',', '', $getTempData->csr_amount_initial) ) : 0;
								$refPrefix = "";
								$externalNoteBonusDiscount = "";
								if( $promotion_type == 'bonus' ){
									$bonus_amount = $csr_amount_initial * $bonus_percentage / 100;
									$csr_amount_initial = ceil( $bonus_amount );
									$refPrefix = "BNS-";
									$externalNoteBonusDiscount = $bonus_percentage."% bonus";
								}else if( $promotion_type == 'discount' ){
									$csr_price = $getTempData->csr_price;
									$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 );
									$refPrefix = "DIS-";
									$externalNoteBonusDiscount = $discount_percentage."% discount";
								}
								$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
								$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
								$created_formatted = ( $getTempData->created != "" ) ? $getTempData->created : '';
								$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
								$source = ( $getTempData->source != "" ) ? $getTempData->source : '';
								$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
								$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
								$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
								$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
								$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';
								$token = ( $getTempData->token != "" ) ? $getTempData->token : 'CSR';
								$redemptionWeek = $week_number;
								$redemptionYear = $year_number;
								if( $promotion_type == 'bonus' ){
									$new_pool_reference = sprintf( 'BNS-%s-%s', $year_number, sprintf("%02d", $week_number) );
								}else if( $promotion_type == 'discount' ){
									$new_pool_reference = sprintf( 'DIS-%s-%s', $year_number, sprintf("%02d", $week_number) );
								}
								$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
								$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
								$validationError = [];
								if( $csr_amount_initial <= $csr_segmentation ){
									
									$promotion_delivery_start_week = ( isset( $getTempData->promotion_delivery_start_week ) ) ? $getTempData->promotion_delivery_start_week : 80;

									if( $promotion_delivery_start_week > 0 ){
										for( $week_i=0; $week_i < $promotion_delivery_start_week; $week_i++ ){
											$week_number = $week_number + 1;
											if( $week_number > $totalNumberWeek ){
												$week_number = $week_number - $totalNumberWeek;
												$year_number = $year_number + 1;
											}else{
												$year_number = $year_number;
											}
										}
									}

									$admNo = $reference.'-000';
									$newAdmNo = ++$admNo;
									$amount_due = $csr_amount_initial;
									if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
										$corp_approved_10 = $distribution_status;
									}else{
										$corp_approved_10 = 'Pending';
									}
									$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - '. $externalNoteBonusDiscount .' provided for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
									if( $distribution_status == 'Security Hold' ){
										$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
									}
									$notes_external_10 = notes_trim_pipe( $notes_external_10 );
									$data = [
										'username'					=>	wp_strip_all_tags( $username ),
										'reference'					=>	wp_strip_all_tags( $refPrefix . $newAdmNo ),
										'eth_address'				=>	wp_strip_all_tags( $eth_address ),
										'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
										'first_name'				=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
										'last_name'					=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
										'created'					=>	$created_formatted,
										'email'						=>	wp_strip_all_tags( $email ),
										'csr_amount_issued'			=>	0,
										'amount_due'				=>	$amount_due,
										'distribution_status'		=>	$distribution_status,
										'member_status'				=>	$member_status,
										'corp_approved'				=>	$corp_approved_10,
										'notes_external'			=>	$notes_external_10,
										'pool_ref'					=>	$new_pool_reference,
										'source'					=>	$promotion_type,
										'week_number'				=>	$year_number.'/'.sprintf("%02d", $week_number),
										'csr_segmentation'			=>	$csr_segmentation,
										'import_by'					=>	$import_by,
										'import_date'				=>	$import_date,
										'csr_type'					=>	'promotion',
										'token'						=>	$token
									];
									$inserting = $wpdb->insert( $tableNewDeliveryPlan, $data );
									if( $inserting ){
										$countSuccess++;
									}else{
										$error = 1;
										$countError++;
										$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
										$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
										$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
										echo wp_json_encode( $out );
										exit;
									}
								}else{

									if( !empty( $promotion_week_wise_arr ) ){
										$csr_amount_pending = $csr_amount_initial;
										$totalCalculated = 0;
										$newAdmNo = "";
										foreach( $promotion_week_wise_arr as $key => $promotion_week_wise_data ){
											$promotion_delivery_start_week = $promotion_week_wise_data['week_wise_promotion_start_week_index'];
											$promotion_redemption_percentage = $promotion_week_wise_data['week_wise_promotion_redemption_percentage'];
											
											$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
											$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';


											if( $promotion_delivery_start_week > 0 ){
												for( $week_i=0; $week_i < $promotion_delivery_start_week; $week_i++ ){
													$week_number = $week_number + 1;
													if( $week_number > $totalNumberWeek ){
														$week_number = $week_number - $totalNumberWeek;
														$year_number = $year_number + 1;
													}else{
														$year_number = $year_number;
													}
												}
											}

											if ($key === count($promotion_week_wise_arr) - 1) {
												$amount_due = $csr_amount_initial - $totalCalculated;
											} else {
												$value = floor($csr_amount_initial * ($promotion_redemption_percentage / 100));
												$amount_due = $value;
												$totalCalculated += $value;
											}

											if( $key == 0 ){
												$admNo = $reference.'-000';
											}else{
												$admNo = $newAdmNo;
											}
											$newAdmNo = ++$admNo;
											if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
												$corp_approved_10 = $distribution_status;
											}else{
												$corp_approved_10 = 'Pending';
											}
											
											$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);
											$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - '. $externalNoteBonusDiscount .' provided for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
											if( $distribution_status == 'Security Hold' ){
												$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
											}
											$notes_external_10 = notes_trim_pipe( $notes_external_10 );
											$data = [
												'username'					=>	wp_strip_all_tags( $username ),
												'reference'					=>	wp_strip_all_tags( $refPrefix . $newAdmNo ),
												'eth_address'				=>	wp_strip_all_tags( $eth_address ),
												'csr_amount_initial'		=>	$csr_amount_initial,
												'first_name'				=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
												'last_name'					=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
												'created'					=>	$created_formatted,
												'email'						=>	wp_strip_all_tags( $email ),
												'csr_amount_issued'			=>	0,
												'amount_due'				=>	$amount_due,
												'distribution_status'		=>	$distribution_status,
												'member_status'				=>	$member_status,
												'corp_approved'				=>	$corp_approved_10,
												'notes_external'			=>	$notes_external_10,
												'pool_ref'					=>	$new_pool_reference,
												'source'					=>	$promotion_type,
												'week_number'				=>	$new_week_number,
												'csr_segmentation'			=>	$csr_segmentation,
												'import_by'					=>	$import_by,
												'import_date'				=>	$import_date,
												'csr_type'					=>	'promotion',
												'token'						=>	$token
											];
											$csr_amount_pending = $csr_amount_pending - $amount_due;
											$inserting = $wpdb->insert( $tableNewDeliveryPlan, $data );
											if( $inserting ){
												$countSuccess++;
											}else{
												$error = 1;
												$countError++;
												$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
												$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
												$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
												echo wp_json_encode( $out );
												exit;
											}

										}
									}

								}
								$rowDataCountPromotion = $getTempData->id;
							}

						}else{ // normal bonus

							// advanced option
							if( isset( $_POST['advanced_weekly_wizard_option'] ) && $_POST['advanced_weekly_wizard_option'] == 'advanced' ){
								$promotion_type = ( isset( $getTempData->promotion_type ) ) ? $getTempData->promotion_type : 'none';
								$bonus_percentage = ( isset( $getTempData->bonus_percentage ) ) ? $getTempData->bonus_percentage : 0;
								$discount_percentage = ( isset( $getTempData->discount_percentage ) ) ? $getTempData->discount_percentage : 1;
								$promotion_number_of_deliveries = ( isset( $getTempData->promotion_number_of_deliveries ) ) ? $getTempData->promotion_number_of_deliveries : 1;
								$promotion_delivery_interval = ( isset( $getTempData->promotion_delivery_interval ) ) ? $getTempData->promotion_delivery_interval : 4;
								$promotion_delivery_start_week = ( isset( $getTempData->promotion_delivery_start_week ) ) ? $getTempData->promotion_delivery_start_week : 80;
								if( $promotion_number_of_deliveries == 1 ){
									$promotion_delivery_interval = 1;
								}
							}
							if( $promotion_type == 'bonus' || $promotion_type == 'discount' ){
								$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
								$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
								$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
								$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? ceil( str_replace( ',', '', $getTempData->csr_amount_initial) ) : 0;
								$refPrefix = "";
								$externalNoteBonusDiscount = "";
								if( $promotion_type == 'bonus' ){
									$bonus_amount = $csr_amount_initial * $bonus_percentage / 100;
									$csr_amount_initial = ceil( $bonus_amount );
									$refPrefix = "BNS-";
									$externalNoteBonusDiscount = $bonus_percentage."% bonus";
								}else if( $promotion_type == 'discount' ){
									$csr_price = $getTempData->csr_price;
									$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 );
									$refPrefix = "DIS-";
									$externalNoteBonusDiscount = $discount_percentage."% discount";
								}
								$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
								$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
								$created_formatted = ( $getTempData->created != "" ) ? $getTempData->created : '';
								$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
								$source = ( $getTempData->source != "" ) ? $getTempData->source : '';
								$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
								$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
								$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
								$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
								$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';
								$token = ( $getTempData->token != "" ) ? $getTempData->token : 'CSR';
								$redemptionWeek = $week_number;
								$redemptionYear = $year_number;
								if( $promotion_type == 'bonus' ){
									$new_pool_reference = sprintf( 'BNS-%s-%s', $year_number, sprintf("%02d", $week_number) );
								}else if( $promotion_type == 'discount' ){
									$new_pool_reference = sprintf( 'DIS-%s-%s', $year_number, sprintf("%02d", $week_number) );
								}
								$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
								$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
								$validationError = [];
								if( $promotion_delivery_start_week > 0 ){
									for( $week_i=0; $week_i < $promotion_delivery_start_week; $week_i++ ){
										$week_number = $week_number + 1;
										if( $week_number > $totalNumberWeek ){
											$week_number = $week_number - $totalNumberWeek;
											$year_number = $year_number + 1;
										}else{
											$year_number = $year_number;
										}
									}
								}
								if( $csr_amount_initial <= $csr_segmentation ){
									$admNo = $reference.'-000';
									$newAdmNo = ++$admNo;
									$amount_due = $csr_amount_initial;
									if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
										$corp_approved_10 = $distribution_status;
									}else{
										$corp_approved_10 = 'Pending';
									}
									$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - '. $externalNoteBonusDiscount .' provided for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
									if( $distribution_status == 'Security Hold' ){
										$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
									}
									$notes_external_10 = notes_trim_pipe( $notes_external_10 );
									$data = [
										'username'					=>	wp_strip_all_tags( $username ),
										'reference'					=>	wp_strip_all_tags( $refPrefix . $newAdmNo ),
										'eth_address'				=>	wp_strip_all_tags( $eth_address ),
										'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
										'first_name'				=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
										'last_name'					=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
										'created'					=>	$created_formatted,
										'email'						=>	wp_strip_all_tags( $email ),
										'csr_amount_issued'			=>	0,
										'amount_due'				=>	$amount_due,
										'distribution_status'		=>	$distribution_status,
										'member_status'				=>	$member_status,
										'corp_approved'				=>	$corp_approved_10,
										'notes_external'			=>	$notes_external_10,
										// 'pool_ref'					=>	$pool_reference,
										'pool_ref'					=>	$new_pool_reference,
										'source'					=>	$promotion_type,
										'week_number'				=>	$year_number.'/'.sprintf("%02d", $week_number),
										'csr_segmentation'			=>	$csr_segmentation,
										'import_by'					=>	$import_by,
										'import_date'				=>	$import_date,
										'csr_type'					=>	'promotion',
										'token'						=>	$token
									];
									$inserting = $wpdb->insert( $tableNewDeliveryPlan, $data );
									if( $inserting ){
										$countSuccess++;
									}else{
										$error = 1;
										$countError++;
										$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
										$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
										$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
										echo wp_json_encode( $out );
										exit;
									}
								}else{
									$csr_amount_pending = $csr_amount_initial;
									$newAdmNo = "";
									for( $i=0; $i < $promotion_number_of_deliveries; $i++ ){
										$amount_due = $csr_amount_pending / ( $promotion_number_of_deliveries - $i );
										$amount_due = ceil( $amount_due );
										if( $i == 0 ){
											$admNo = $reference.'-000';
										}else{
											$admNo = $newAdmNo;
										}
										$newAdmNo = ++$admNo;
										if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
											$corp_approved_10 = $distribution_status;
										}else{
											$corp_approved_10 = 'Pending';
										}
										if( $week_number > $totalNumberWeek ){
											$week_number = $week_number - $totalNumberWeek;
											$year_number = $year_number + 1;
										}else{
											$year_number = $year_number;
										}
										$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);
										$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - '. $externalNoteBonusDiscount .' provided for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
										if( $distribution_status == 'Security Hold' ){
											$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
										}
										$notes_external_10 = notes_trim_pipe( $notes_external_10 );
										$data = [
											'username'					=>	wp_strip_all_tags( $username ),
											'reference'					=>	wp_strip_all_tags( $refPrefix . $newAdmNo ),
											'eth_address'				=>	wp_strip_all_tags( $eth_address ),
											'csr_amount_initial'		=>	$csr_amount_initial,
											// 'csr_amount_initial'		=>	$csr_amount_pending,
											'first_name'				=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
											'last_name'					=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
											'created'					=>	$created_formatted,
											'email'						=>	wp_strip_all_tags( $email ),
											'csr_amount_issued'			=>	0,
											'amount_due'				=>	$amount_due,
											'distribution_status'		=>	$distribution_status,
											'member_status'				=>	$member_status,
											'corp_approved'				=>	$corp_approved_10,
											'notes_external'			=>	$notes_external_10,
											// 'pool_ref'					=>	$pool_reference,
											'pool_ref'					=>	$new_pool_reference,
											'source'					=>	$promotion_type,
											'week_number'				=>	$new_week_number,
											'csr_segmentation'			=>	$csr_segmentation,
											'import_by'					=>	$import_by,
											'import_date'				=>	$import_date,
											'csr_type'					=>	'promotion',
											'token'						=>	$token
										];
										$csr_amount_pending = $csr_amount_pending - $amount_due;
										$inserting = $wpdb->insert( $tableNewDeliveryPlan, $data );
										if( $inserting ){
											$countSuccess++;
										}else{
											$error = 1;
											$countError++;
											$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
											$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
											$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
											echo wp_json_encode( $out );
											exit;
										}
										// $week_number++;
										$week_number = $week_number + $promotion_delivery_interval;
									}
								}
								$rowDataCountPromotion = $getTempData->id;
							}

						}

					}
				}
				$getProceedCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableNewDeliveryPlan WHERE 1 ");
				if( $promotion_type == 'bonus' || $promotion_type == 'discount' ){
					$importNoticeMsg = sprintf( __('%s rows of Primary delivery processed<br/>%s rows of Promotion delivery processed<br/>%s records inserted<br/>', CIP_TXTDOMAIN), $rowDataCount, $rowDataCount, $getProceedCount );
				}else{
					$importNoticeMsg = sprintf( __('%s rows of Primary delivery processed<br/>%s records inserted<br/>', CIP_TXTDOMAIN), $rowDataCount, $getProceedCount );
				}
				// $msg2 = sprintf( __('%s row splitting process complete',CIP_TXTDOMAIN), getOrdinal( $splitting_id ) );
				$out = array( "error" => 0, 'msg' => $importNoticeMsg, 'totalCount' => $rowDataCount );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_new_delivery_plan_distribution_loader','cip_new_delivery_plan_distribution_loader_cb');
function cip_new_delivery_plan_distribution_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'new_delivery_plan_temp';
	$user_id = get_current_user_id();
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName");
	$total_items_summery = $wpdb->get_var("SELECT COUNT(id) FROM $tableName");
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	$filter_qry = "";
	$total_import_label = "";
	$total_import = 0;
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 $filter_qry ORDER BY `id` asc");
	}
	$total_import_items = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 ORDER BY `id` asc");
	$tokenTypeText = "CSR";
	if( $total_import_items ){
		foreach( $total_import_items as $total_import_item ){
			$total_import += $total_import_item->csr_amount_initial;
			$tokenTypeText = $total_import_item->token;
		}
	}
	$unique_addresses = $wpdb->get_var("SELECT COUNT(DISTINCT (`eth_address`)) FROM $tableName WHERE 1 AND `eth_address` != ''");
	if( $total_import ){
		$total_import_label = sprintf( __('<b>%s</b><br/>Total '.$tokenTypeText.' wallet address : %s<br/> Total '.$tokenTypeText.' : %s<br/>Unique '.$tokenTypeText.' wallet addresses : %s', CIP_TXTDOMAIN), __('Import Summary',CIP_TXTDOMAIN),$total_items_summery, number_format($total_import), $unique_addresses );
	}
	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	global $defaultColumnsArr;
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'				=>	__('username', CIP_TXTDOMAIN),
				'reference'				=>	__('reference', CIP_TXTDOMAIN),
				'eth_address'			=>	__('eth_address', CIP_TXTDOMAIN),
				'csr_amount_initial'	=>	__('csr_amount_initial', CIP_TXTDOMAIN),
				'csr_amount_issued'		=>	__('csr_amount_issued', CIP_TXTDOMAIN),
				'amount_due'			=>	__('amount_due', CIP_TXTDOMAIN),
				'first_name'			=>	__('first_name', CIP_TXTDOMAIN),
				'last_name'				=>	__('last_name', CIP_TXTDOMAIN),
				'created'				=>	__('created', CIP_TXTDOMAIN),
				'csr_price'				=>	__('csr_price', CIP_TXTDOMAIN),
				'email'					=>	__('email', CIP_TXTDOMAIN),
				'distribution_status'	=>	__('distribution_status', CIP_TXTDOMAIN),
				'member_status'			=>	__('member_status', CIP_TXTDOMAIN),
				'corp_approved'			=>	__('corp_approved', CIP_TXTDOMAIN),
				'notes_external'		=>	__('notes_external', CIP_TXTDOMAIN),
				'pool_ref'				=>	__('pool_ref', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					if( $columnKey == 'eth_address' ){
						if( !empty( $columnsDataVal ) ){
							// $columnsDataValMask = substr($columnsDataVal, 0, 6) . '...' . substr($columnsDataVal, -6);
							$columnsDataVal = '<a href="https://etherscan.io/address/'. $columnsDataVal . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$columnsDataVal.'" >'. $columnsDataVal . '</a>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'csr_amount_initial' || $columnKey == 'csr_amount_issued' || $columnKey == 'amount_due' ){
						$columnsDataVal = number_format( $columnsDataVal );
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'					=>	$total_items,
		'rows'					=>	$rows,
		'total_import_label'	=>	$total_import_label
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_new_delivery_plan_distribution_10_loader','cip_new_delivery_plan_distribution_10_loader_cb');
function cip_new_delivery_plan_distribution_10_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'new_delivery_plan';
	$user_id = get_current_user_id();
	$csr_type_filter = " AND `csr_type` = 'primary'";
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0 $csr_type_filter");
	$total_items_summery = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0 $csr_type_filter");
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	$filter_qry = "";
	$total_issued = 0;
	$total_issued_label = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0 $csr_type_filter $filter_qry ORDER BY `id` asc");
	}
	$total_issued_items = $wpdb->get_results("SELECT `amount_due` FROM $tableName WHERE `amount_due` > 0 $csr_type_filter ORDER BY `id` asc");
	$getTokenType = $wpdb->get_row("SELECT `token` FROM $tableName WHERE 1 ORDER BY `id` asc");
	$tokenTypeText = "CSR";
	if( $getTokenType ){
		$tokenTypeText = $getTokenType->token;
	}
	if( $total_issued_items ){
		foreach( $total_issued_items as $total_issued_item ){
			$total_issued += $total_issued_item->amount_due;
		}
	}
	// $unique_addresses = $wpdb->get_var("SELECT COUNT(DISTINCT (`eth_address`)) FROM $tableName WHERE 1 AND `eth_address` != '' $csr_type_filter");
	if( $total_issued ){
		$total_issued_label = sprintf( __('<b>%s</b><br/>Total new '.$tokenTypeText.' records : %s<br/>Total '.$tokenTypeText.' : %s', CIP_TXTDOMAIN), __('Primary Delivery Summary',CIP_TXTDOMAIN),$total_items_summery, number_format($total_issued) );
	}
	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE `amount_due` > 0 $csr_type_filter $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	global $defaultColumnsArr;
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'				=>	__('username', CIP_TXTDOMAIN),
				'reference'				=>	__('reference', CIP_TXTDOMAIN),
				'eth_address'			=>	__('eth_address', CIP_TXTDOMAIN),
				'csr_amount_initial'	=>	__('csr_amount_initial', CIP_TXTDOMAIN),
				'csr_amount_issued'		=>	__('csr_amount_issued', CIP_TXTDOMAIN),
				'amount_due'			=>	__('amount_due', CIP_TXTDOMAIN),
				'first_name'			=>	__('first_name', CIP_TXTDOMAIN),
				'last_name'				=>	__('last_name', CIP_TXTDOMAIN),
				'created'				=>	__('created', CIP_TXTDOMAIN),
				'email'					=>	__('email', CIP_TXTDOMAIN),
				'distribution_status'	=>	__('distribution_status', CIP_TXTDOMAIN),
				'corp_approved'			=>	__('corp_approved', CIP_TXTDOMAIN),
				'week_number'			=>	__('week_number', CIP_TXTDOMAIN),
				'member_status'			=>	__('member_status', CIP_TXTDOMAIN),
				'pool_ref'				=>	__('pool_ref', CIP_TXTDOMAIN),
				'source'				=>	__('source', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					if( $columnKey == 'eth_address' ){
						if( !empty( $columnsDataVal ) ){
							// $columnsDataValMask = substr($columnsDataVal, 0, 6) . '...' . substr($columnsDataVal, -6);
							$columnsDataVal = '<a href="https://etherscan.io/address/'. $columnsDataVal . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$columnsDataVal.'" >'. $columnsDataVal . '</a>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'csr_amount_initial' || $columnKey == 'csr_amount_issued' || $columnKey == 'amount_due' ){
						$columnsDataVal = number_format( $columnsDataVal );
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		'total_issued_label'	=>	$total_issued_label
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_new_delivery_plan_distribution_promotion_loader','cip_new_delivery_plan_distribution_promotion_loader_cb');
function cip_new_delivery_plan_distribution_promotion_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'new_delivery_plan';
	$user_id = get_current_user_id();
	$csr_type_filter = " AND `csr_type` = 'promotion'";
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0 $csr_type_filter");
	$total_items_summery = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0 $csr_type_filter");
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	$filter_qry = "";
	$total_issued = 0;
	$total_issued_label = "<h5 class='m-0'><b>No promotion data available</b></h5>";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0 $csr_type_filter $filter_qry ORDER BY `id` asc");
	}
	$total_issued_items = $wpdb->get_results("SELECT `amount_due` FROM $tableName WHERE `amount_due` > 0 $csr_type_filter ORDER BY `id` asc");
	$getTokenType = $wpdb->get_row("SELECT `token` FROM $tableName WHERE 1 ORDER BY `id` asc");
	$tokenTypeText = "CSR";
	if( $getTokenType ){
		$tokenTypeText = $getTokenType->token;
	}
	if( $total_issued_items ){
		foreach( $total_issued_items as $total_issued_item ){
			$total_issued += $total_issued_item->amount_due;
		}
	}
	$unique_addresses = $wpdb->get_var("SELECT COUNT(DISTINCT (`eth_address`)) FROM $tableName WHERE 1 AND `eth_address` != '' $csr_type_filter");
	if( $total_issued ){
		$total_issued_label = sprintf( __('<b>%s</b><br/>Total new '.$tokenTypeText.' records : %s<br/> Total '.$tokenTypeText.' : %s', CIP_TXTDOMAIN), __('Promotion Delivery Summary',CIP_TXTDOMAIN),$total_items_summery, number_format($total_issued) );
	}
	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE `amount_due` > 0 $csr_type_filter $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	global $defaultColumnsArr;
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'				=>	__('username', CIP_TXTDOMAIN),
				'reference'				=>	__('reference', CIP_TXTDOMAIN),
				'eth_address'			=>	__('eth_address', CIP_TXTDOMAIN),
				'csr_amount_initial'	=>	__('csr_amount_initial', CIP_TXTDOMAIN),
				'csr_amount_issued'		=>	__('csr_amount_issued', CIP_TXTDOMAIN),
				'amount_due'			=>	__('amount_due', CIP_TXTDOMAIN),
				'first_name'			=>	__('first_name', CIP_TXTDOMAIN),
				'last_name'				=>	__('last_name', CIP_TXTDOMAIN),
				'created'				=>	__('created', CIP_TXTDOMAIN),
				'email'					=>	__('email', CIP_TXTDOMAIN),
				'distribution_status'	=>	__('distribution_status', CIP_TXTDOMAIN),
				'corp_approved'			=>	__('corp_approved', CIP_TXTDOMAIN),
				'week_number'			=>	__('week_number', CIP_TXTDOMAIN),
				'member_status'			=>	__('member_status', CIP_TXTDOMAIN),
				'pool_ref'				=>	__('pool_ref', CIP_TXTDOMAIN),
				'source'				=>	__('source', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					if( $columnKey == 'eth_address' ){
						if( !empty( $columnsDataVal ) ){
							// $columnsDataValMask = substr($columnsDataVal, 0, 6) . '...' . substr($columnsDataVal, -6);
							$columnsDataVal = '<a href="https://etherscan.io/address/'. $columnsDataVal . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$columnsDataVal.'" >'. $columnsDataVal . '</a>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'csr_amount_initial' || $columnKey == 'csr_amount_issued' || $columnKey == 'amount_due' ){
						$columnsDataVal = number_format( $columnsDataVal );
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'					=>	$total_items,
		'rows'					=>	$rows,
		'total_issued_label'	=>	$total_issued_label
	);
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_append_new_delivery_plan_csr_holders_data_act', 'cip_append_new_delivery_plan_csr_holders_data_act_callback' );
function cip_append_new_delivery_plan_csr_holders_data_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYAppendNew_csr_HoldersDataYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableNewDeliveryPlan = $wpdb->prefix.'new_delivery_plan';
		$tableNewDeliveryPlanTemp = $wpdb->prefix.'new_delivery_plan_temp';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		if( isset( $_POST['get_append_data'] ) && $_POST['get_append_data'] == 'yes' ){
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableNewDeliveryPlanTemp WHERE 1 AND `append_status` != 1");
			$per_page = 100;
			$total_paged = ceil( $total_items / $per_page );
			$statusUpdate = $wpdb->query( $wpdb->prepare( "UPDATE $tableNewDeliveryPlan SET `append_status` = %d", 1 ) );
			if( $statusUpdate ){
			}
			$out = array( "error" => 0, 'total_items' => $total_items, 'total_paged' => $total_paged,'msg' => __('Appending deliveries started...',CIP_TXTDOMAIN), 'msg2' => __('Appending deliveries started...',CIP_TXTDOMAIN), 'totalmsg' => sprintf( __('%s row\'s to append', CIP_TXTDOMAIN),$total_items ) );
		}else if( isset( $_POST['appending_data'] ) && $_POST['appending_data'] == 'yes' ){
			$per_page = 100;
			$paged = isset( $_POST['page_id'] ) ? max( 0, intval( $_POST['page_id'] -1 ) * $per_page ) : 0;
			$error = 0;
			$rowDataCount= 0;
			$countError = 0;
			$countSuccess = 0;
			$insertingCount = 1;
			$rowDataCountPromotion = 0;
			$getTempDatas = $wpdb->get_results("SELECT * FROM $tableNewDeliveryPlanTemp WHERE 1 ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."");
			if( $getTempDatas ){
				//Primary CSR
				foreach( $getTempDatas as $getTempData ){
					if( $getTempData->append_status != 1 ){
						$totalNumberWeek = 52;
						$primary_number_of_deliveries = ( isset( $getTempData->primary_number_of_deliveries ) ) ? $getTempData->primary_number_of_deliveries : 1;
						$primary_delivery_interval = ( isset( $getTempData->primary_delivery_interval ) ) ? $getTempData->primary_delivery_interval : 4;
						$primary_delivery_start_week = ( isset( $getTempData->primary_delivery_start_week ) ) ? $getTempData->primary_delivery_start_week : 40;
						if( $primary_number_of_deliveries == 1 ){
							$primary_delivery_interval = 1;
						}
						$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
						$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
						$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
						$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? ceil( str_replace( ',', '', $getTempData->csr_amount_initial) ) : 0;
						$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
						$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
						$created = ( $getTempData->created != "" ) ? $getTempData->created : '';
						$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
						$source = ( $getTempData->source != "" ) ? $getTempData->source : '';
						$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
						$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
						$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
						$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
						$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';
						$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
						$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
						$pool_reference = ( $getTempData->pool_ref != "" ) ? $getTempData->pool_ref : '';
						$token = ( $getTempData->token != "" ) ? $getTempData->token : 'CSR';
						$new_pool_reference = sprintf( 'PNP-%s-%s', $year_number, sprintf("%02d", $week_number) );
						$redemptionWeek = $week_number;
						$redemptionYear = $year_number;

						$primary_week_wise_arr = json_decode($getTempData->primary_week_wise, true);

						$week_wise_advanced = ( $getTempData->week_wise_advanced != "" ) ? $getTempData->week_wise_advanced : 'normal';
						if( $week_wise_advanced == 'week_wise' ){	//week wise delivery
							
							if( $csr_amount_initial <= $csr_segmentation ){

								$primary_delivery_start_week = ( isset( $getTempData->primary_delivery_start_week ) ) ? $getTempData->primary_delivery_start_week : 40;

								if( $primary_delivery_start_week > 0 ){
									for( $week_i=0; $week_i < $primary_delivery_start_week; $week_i++ ){
										$week_number = $week_number + 1;
										if( $week_number > $totalNumberWeek ){
											$week_number = $week_number - $totalNumberWeek;
											$year_number = $year_number + 1;
										}else{
											$year_number = $year_number;
										}
									}
								}

								$admNo = $reference.'-000';
								$newAdmNo = ++$admNo;
								$amount_due = $csr_amount_initial;
								if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
									$corp_approved_10 = $distribution_status;
								}else{
									$corp_approved_10 = 'Pending';
								}
								$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
								if( $distribution_status == 'Security Hold' ){
									$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
								}
								$notes_external_10 = notes_trim_pipe( $notes_external_10 );
								$text_7 = null;
								if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
									$text_7 = 'Pending';
								}
								$data = array(
									'reference'				=>	wp_strip_all_tags( 'PNP-' . $newAdmNo ),
									'eth_address'			=>	wp_strip_all_tags( $eth_address ),
									'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
									'csr_amount_issued'		=>	0,
									'amount_due'			=>	$amount_due,
									'username'				=>	wp_strip_all_tags( $username ),
									'first_name'			=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
									'last_name'				=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
									'redemption_date'		=>	$created,
									'email'					=>	wp_strip_all_tags( $email ),
									'_user_status'			=>	$member_status,
									'pool_ref'				=>	$new_pool_reference,
									'corp_approved'			=>	$corp_approved_10,
									'notes_external'		=>	$notes_external_10,
									'text_7'				=>	$text_7,
									'text_10'				=>	$year_number.'/'.sprintf("%02d", $week_number),
									'text_9'				=>	$source,
									'imported_by'			=>	$import_by,
									'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
									'token'					=>	$token
								);
								$inserting = $wpdb->insert( $tableTokenHolder, $data );
								if( $inserting ){
									$countSuccess++;
									$user_type = 'sm';
									$log_type = 'new_delivery_plan_redemptions_append';
									$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
									create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
									$wpdb->update( $tableNewDeliveryPlanTemp, array( 'append_status' => 1 ), array( 'id' => $getTempData->id ) );
								}else{
									$error = 1;
									$countError++;
									$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
									echo wp_json_encode( $out );
									exit;
								}
							}else{
								if( !empty( $primary_week_wise_arr ) ){

									$csr_amount_pending = $csr_amount_initial;
									$totalCalculated = 0;
									$newAdmNo = "";
									$loopCounter = 0;
									foreach( $primary_week_wise_arr as $key => $primary_week_wise_data ){

										$primary_delivery_start_week = $primary_week_wise_data['week_wise_start_week_index'];
										$primary_redemption_percentage = $primary_week_wise_data['week_wise_redemption_percentage'];

										$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
										$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';

										for( $week_i=0; $week_i < $primary_delivery_start_week; $week_i++ ){
											$week_number = $week_number + 1;
											if( $week_number > $totalNumberWeek ){
												$week_number = $week_number - $totalNumberWeek;
												$year_number = $year_number + 1;
											}else{
												$year_number = $year_number;
											}
										}

										if ($key === count($primary_week_wise_arr) - 1) {
											$amount_due = $csr_amount_initial - $totalCalculated;
										} else {
											$value = floor($csr_amount_initial * ($primary_redemption_percentage / 100));
											$amount_due = $value;
											$totalCalculated += $value;
										}

										if( $key == 0 ){
											$admNo = $reference.'-000';
										}else{
											$admNo = $newAdmNo;
										}
										$newAdmNo = ++$admNo;
										if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
											$corp_approved_10 = $distribution_status;
										}else{
											$corp_approved_10 = 'Pending';
										}
										if( $week_number > $totalNumberWeek ){
											$week_number = $week_number - $totalNumberWeek;
											$year_number = $year_number + 1;
										}else{
											$year_number = $year_number;
										}
										$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);
										$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
										if( $distribution_status == 'Security Hold' ){
											$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
										}
										$notes_external_10 = notes_trim_pipe( $notes_external_10 );
										$text_7 = null;
										if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
											$text_7 = 'Pending';
										}
										$data = array(
											'reference'				=>	wp_strip_all_tags( 'PNP-' .$newAdmNo ),
											'eth_address'			=>	wp_strip_all_tags( $eth_address ),
											'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
											'csr_amount_issued'		=>	0,
											'amount_due'			=>	$amount_due,
											'username'				=>	wp_strip_all_tags( $username ),
											'first_name'			=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
											'last_name'				=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
											'redemption_date'		=>	$created,
											'email'					=>	wp_strip_all_tags( $email ),
											'_user_status'			=>	$member_status,
											'pool_ref'				=>	$new_pool_reference,
											'corp_approved'			=>	$corp_approved_10,
											'notes_external'		=>	$notes_external_10,
											'text_7'				=>	$text_7,
											'text_10'				=>	$new_week_number,
											'text_9'				=>	$source,
											'imported_by'			=>	$import_by,
											'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
											'token'					=>	$token
										);
										$csr_amount_pending = $csr_amount_pending - $amount_due;
										$inserting = $wpdb->insert( $tableTokenHolder, $data );
										if( $inserting ){
											$countSuccess++;
											$loopCounter++;
											$user_type = 'sm';
											$log_type = 'new_delivery_plan_redemptions_append';
											$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
											create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
										}else{
											$error = 1;
											$countError++;
											$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
											echo wp_json_encode( $out );
											exit;
										}
										// $week_number++;
										$week_number = $week_number + $primary_delivery_interval;
									}
									if( $loopCounter == $primary_number_of_deliveries ){
										$wpdb->update( $tableNewDeliveryPlanTemp, array('append_status' => 1), array( 'id' => $getTempData->id ) );
									}
								}
							}

						}else{	//normal delivery

							if( $primary_delivery_start_week > 0 ){
								for( $week_i=0; $week_i < $primary_delivery_start_week; $week_i++ ){
									$week_number = $week_number + 1;
									if( $week_number > $totalNumberWeek ){
										$week_number = $week_number - $totalNumberWeek;
										$year_number = $year_number + 1;
									}else{
										$year_number = $year_number;
									}
								}
							}
							if( $csr_amount_initial <= $csr_segmentation ){
								$admNo = $reference.'-000';
								$newAdmNo = ++$admNo;
								$amount_due = $csr_amount_initial;
								if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
									$corp_approved_10 = $distribution_status;
								}else{
									$corp_approved_10 = 'Pending';
								}
								$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
								if( $distribution_status == 'Security Hold' ){
									$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
								}
								$notes_external_10 = notes_trim_pipe( $notes_external_10 );
								$text_7 = null;
								if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
									$text_7 = 'Pending';
								}
								$data = array(
									'reference'				=>	wp_strip_all_tags( 'PNP-' . $newAdmNo ),
									'eth_address'			=>	wp_strip_all_tags( $eth_address ),
									'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
									'csr_amount_issued'		=>	0,
									'amount_due'			=>	$amount_due,
									'username'				=>	wp_strip_all_tags( $username ),
									'first_name'			=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
									'last_name'				=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
									'redemption_date'		=>	$created,
									'email'					=>	wp_strip_all_tags( $email ),
									'_user_status'			=>	$member_status,
									// 'kyc_status'			=>	$distribution_status,
									// 'pool_ref'				=>	$pool_reference,
									'pool_ref'				=>	$new_pool_reference,
									'corp_approved'			=>	$corp_approved_10,
									'notes_external'		=>	$notes_external_10,
									'text_7'				=>	$text_7,
									'text_10'				=>	$year_number.'/'.sprintf("%02d", $week_number),
									'text_9'				=>	$source,
									'imported_by'			=>	$import_by,
									'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
									'token'					=>	$token
								);
								$inserting = $wpdb->insert( $tableTokenHolder, $data );
								if( $inserting ){
									$countSuccess++;
									$user_type = 'sm';
									$log_type = 'new_delivery_plan_redemptions_append';
									$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
									create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
									$wpdb->update( $tableNewDeliveryPlanTemp, array( 'append_status' => 1 ), array( 'id' => $getTempData->id ) );
								}else{
									$error = 1;
									$countError++;
									$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
									echo wp_json_encode( $out );
									exit;
								}
							}else{
								$csr_amount_pending = $csr_amount_initial;
								$newAdmNo = "";
								$loopCounter = 0;
								for( $i=0; $i < $primary_number_of_deliveries; $i++ ){
									$amount_due = $csr_amount_pending / ( $primary_number_of_deliveries - $i );
									$amount_due = ceil( $amount_due );
									if( $i == 0 ){
										$admNo = $reference.'-000';
									}else{
										$admNo = $newAdmNo;
									}
									$newAdmNo = ++$admNo;
									if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
										$corp_approved_10 = $distribution_status;
									}else{
										$corp_approved_10 = 'Pending';
									}
									if( $week_number > $totalNumberWeek ){
										$week_number = $week_number - $totalNumberWeek;
										$year_number = $year_number + 1;
									}else{
										$year_number = $year_number;
									}
									$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);
									$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
									if( $distribution_status == 'Security Hold' ){
										$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
									}
									$notes_external_10 = notes_trim_pipe( $notes_external_10 );
									$text_7 = null;
									if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
										$text_7 = 'Pending';
									}
									$data = array(
										'reference'				=>	wp_strip_all_tags( 'PNP-' .$newAdmNo ),
										'eth_address'			=>	wp_strip_all_tags( $eth_address ),
										'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
										'csr_amount_issued'		=>	0,
										'amount_due'			=>	$amount_due,
										'username'				=>	wp_strip_all_tags( $username ),
										'first_name'			=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
										'last_name'				=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
										'redemption_date'		=>	$created,
										'email'					=>	wp_strip_all_tags( $email ),
										'_user_status'			=>	$member_status,
										// 'kyc_status'			=>	$distribution_status,
										// 'pool_ref'				=>	$pool_reference,
										'pool_ref'				=>	$new_pool_reference,
										'corp_approved'			=>	$corp_approved_10,
										'notes_external'		=>	$notes_external_10,
										'text_7'				=>	$text_7,
										'text_10'				=>	$new_week_number,
										'text_9'				=>	$source,
										'imported_by'			=>	$import_by,
										'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
										'token'					=>	$token
									);
									$csr_amount_pending = $csr_amount_pending - $amount_due;
									$inserting = $wpdb->insert( $tableTokenHolder, $data );
									if( $inserting ){
										$countSuccess++;
										$loopCounter++;
										$user_type = 'sm';
										$log_type = 'new_delivery_plan_redemptions_append';
										$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
										create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
									}else{
										$error = 1;
										$countError++;
										$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
										echo wp_json_encode( $out );
										exit;
									}
									// $week_number++;
									$week_number = $week_number + $primary_delivery_interval;
								}
								if( $loopCounter == $primary_number_of_deliveries ){
									$wpdb->update( $tableNewDeliveryPlanTemp, array('append_status' => 1), array( 'id' => $getTempData->id ) );
								}
							}

						}

						$rowDataCount = $getTempData->id;
					}
				}
				//Promotion CSR
				foreach( $getTempDatas as $getTempData ){
					if( $getTempData->append_status != 1 ){
						$totalNumberWeek = 52;
						$promotion_type = ( isset( $getTempData->promotion_type ) ) ? $getTempData->promotion_type : 'none';
						$bonus_percentage = ( isset( $getTempData->bonus_percentage ) ) ? $getTempData->bonus_percentage : 0;
						$discount_percentage = ( isset( $getTempData->discount_percentage ) ) ? $getTempData->discount_percentage : 1;
						$promotion_number_of_deliveries = ( isset( $getTempData->promotion_number_of_deliveries ) ) ? $getTempData->promotion_number_of_deliveries : 1;
						$promotion_delivery_interval = ( isset( $getTempData->promotion_delivery_interval ) ) ? $getTempData->promotion_delivery_interval : 4;
						$promotion_delivery_start_week = ( isset( $getTempData->promotion_delivery_start_week ) ) ? $getTempData->promotion_delivery_start_week : 80;
						if( $promotion_number_of_deliveries == 1 ){
							$promotion_delivery_interval = 1;
						}

						$week_wise_advanced = ( $getTempData->week_wise_advanced != "" ) ? $getTempData->week_wise_advanced : 'normal';

						if( $week_wise_advanced == 'week_wise' ){ // week wise bonus
							
							if( $promotion_type == 'bonus' || $promotion_type == 'discount' ){

								$promotion_week_wise_arr = json_decode($getTempData->promotion_week_wise, true);

								$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
								$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
								$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
								$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? ceil( str_replace( ',', '', $getTempData->csr_amount_initial) ) : 0;
								$refPrefix = "";
								$externalNoteBonusDiscount = "";
								if( $promotion_type == 'bonus' ){
									$bonus_amount = $csr_amount_initial * $bonus_percentage / 100;
									$csr_amount_initial = ceil( $bonus_amount );
									$refPrefix = "BNS-";
									$externalNoteBonusDiscount = $bonus_percentage."% bonus";
								}else if( $promotion_type == 'discount' ){
									$csr_price = $getTempData->csr_price;
									$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 );
									$refPrefix = "DIS-";
									$externalNoteBonusDiscount = $discount_percentage."% discount";
								}
								$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
								$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
								$created = ( $getTempData->created != "" ) ? $getTempData->created : '';
								$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
								$source = ( $getTempData->source != "" ) ? $getTempData->source : '';
								$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
								$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
								$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
								$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
								$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';
								$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
								$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
								$pool_reference = ( $getTempData->pool_ref != "" ) ? $getTempData->pool_ref : '';
								$token = ( $getTempData->token != "" ) ? $getTempData->token : 'CSR';
								$redemptionWeek = $week_number;
								$redemptionYear = $year_number;
								if( $promotion_type == 'bonus' ){
									$new_pool_reference = sprintf( 'BNS-%s-%s', $year_number, sprintf("%02d", $week_number) );
								}else if( $promotion_type == 'discount' ){
									$new_pool_reference = sprintf( 'DIS-%s-%s', $year_number, sprintf("%02d", $week_number) );
								}

								if( $csr_amount_initial <= $csr_segmentation ){

									$promotion_delivery_start_week = ( isset( $getTempData->promotion_delivery_start_week ) ) ? $getTempData->promotion_delivery_start_week : 80;

									if( $promotion_delivery_start_week > 0 ){
										for( $week_i=0; $week_i < $promotion_delivery_start_week; $week_i++ ){
											$week_number = $week_number + 1;
											if( $week_number > $totalNumberWeek ){
												$week_number = $week_number - $totalNumberWeek;
												$year_number = $year_number + 1;
											}else{
												$year_number = $year_number;
											}
										}
									}

									$admNo = $reference.'-000';
									$newAdmNo = ++$admNo;
									$amount_due = $csr_amount_initial;
									if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
										$corp_approved_10 = $distribution_status;
									}else{
										$corp_approved_10 = 'Pending';
									}
									$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - '. $externalNoteBonusDiscount .' provided for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
									if( $distribution_status == 'Security Hold' ){
										$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
									}
									$notes_external_10 = notes_trim_pipe( $notes_external_10 );
									$text_7 = null;
									if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
										$text_7 = 'Pending';
									}
									$data = array(
										'reference'				=>	wp_strip_all_tags( $refPrefix . $newAdmNo ),
										'eth_address'			=>	wp_strip_all_tags( $eth_address ),
										'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
										'csr_amount_issued'		=>	0,
										'amount_due'			=>	$amount_due,
										'username'				=>	wp_strip_all_tags( $username ),
										'first_name'			=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
										'last_name'				=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
										'redemption_date'		=>	$created,
										'email'					=>	wp_strip_all_tags( $email ),
										'_user_status'			=>	$member_status,
										'pool_ref'				=>	$new_pool_reference,
										'corp_approved'			=>	$corp_approved_10,
										'notes_external'		=>	$notes_external_10,
										'text_7'				=>	$text_7,
										'text_10'				=>	$year_number.'/'.sprintf("%02d", $week_number),
										'text_9'				=>	$promotion_type,
										'imported_by'			=>	$import_by,
										'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
										'token'					=>	$token
									);
									$inserting = $wpdb->insert( $tableTokenHolder, $data );
									if( $inserting ){
										$countSuccess++;
										$user_type = 'sm';
										$log_type = 'new_delivery_plan_redemptions_append';
										$logs = sprintf( __('Appended promotion record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
										create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
									}else{
										$error = 1;
										$countError++;
										$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
										echo wp_json_encode( $out );
										exit;
									}
								}else{

									if( !empty( $promotion_week_wise_arr ) ){
										
										$csr_amount_pending = $csr_amount_initial;
										$totalCalculated = 0;
										$newAdmNo = "";
										$loopCounter = 0;
										foreach( $promotion_week_wise_arr as $key => $promotion_week_wise_data ){
											
											$promotion_delivery_start_week = $promotion_week_wise_data['week_wise_promotion_start_week_index'];
											$promotion_redemption_percentage = $promotion_week_wise_data['week_wise_promotion_redemption_percentage'];
											
											$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
											$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';

											if( $promotion_delivery_start_week > 0 ){
												for( $week_i=0; $week_i < $promotion_delivery_start_week; $week_i++ ){
													$week_number = $week_number + 1;
													if( $week_number > $totalNumberWeek ){
														$week_number = $week_number - $totalNumberWeek;
														$year_number = $year_number + 1;
													}else{
														$year_number = $year_number;
													}
												}
											}

											if ($key === count($promotion_week_wise_arr) - 1) {
												$amount_due = $csr_amount_initial - $totalCalculated;
											} else {
												$value = floor($csr_amount_initial * ($promotion_redemption_percentage / 100));
												$amount_due = $value;
												$totalCalculated += $value;
											}

											if( $key == 0 ){
												$admNo = $reference.'-000';
											}else{
												$admNo = $newAdmNo;
											}
											$newAdmNo = ++$admNo;
											if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
												$corp_approved_10 = $distribution_status;
											}else{
												$corp_approved_10 = 'Pending';
											}
											
											$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);
											$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - '. $externalNoteBonusDiscount .' provided for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
											if( $distribution_status == 'Security Hold' ){
												$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
											}
											$notes_external_10 = notes_trim_pipe( $notes_external_10 );
											$text_7 = null;
											if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
												$text_7 = 'Pending';
											}
											$data = array(
												'reference'				=>	wp_strip_all_tags( $refPrefix . $newAdmNo ),
												'eth_address'			=>	wp_strip_all_tags( $eth_address ),
												'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
												'csr_amount_issued'		=>	0,
												'amount_due'			=>	$amount_due,
												'username'				=>	wp_strip_all_tags( $username ),
												'first_name'			=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
												'last_name'				=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
												'redemption_date'		=>	$created,
												'email'					=>	wp_strip_all_tags( $email ),
												'_user_status'			=>	$member_status,
												'pool_ref'				=>	$new_pool_reference,
												'corp_approved'			=>	$corp_approved_10,
												'notes_external'		=>	$notes_external_10,
												'text_7'				=>	$text_7,
												'text_10'				=>	$new_week_number,
												'text_9'				=>	$promotion_type,
												'imported_by'			=>	$import_by,
												'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
												'token'					=>	$token
											);
											$csr_amount_pending = $csr_amount_pending - $amount_due;
											$inserting = $wpdb->insert( $tableTokenHolder, $data );
											if( $inserting ){
												$countSuccess++;
												$loopCounter++;
												$user_type = 'sm';
												$log_type = 'new_delivery_plan_redemptions_append';
												$logs = sprintf( __('Appended promotion record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
												create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
											}else{
												$error = 1;
												$countError++;
												$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
												echo wp_json_encode( $out );
												exit;
											}
										}
										if( $loopCounter == $promotion_number_of_deliveries ){
											// $wpdb->update( $tableNewDeliveryPlanTemp, array('append_status' => 1), array( 'id' => $getTempData->id ) );
										}

									}

								}
								$rowDataCountPromotion = $getTempData->id;
							}

						}else{	// normal delivery

							if( $promotion_type == 'bonus' || $promotion_type == 'discount' ){
								$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
								$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
								$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
								$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? ceil( str_replace( ',', '', $getTempData->csr_amount_initial) ) : 0;
								$refPrefix = "";
								$externalNoteBonusDiscount = "";
								if( $promotion_type == 'bonus' ){
									$bonus_amount = $csr_amount_initial * $bonus_percentage / 100;
									$csr_amount_initial = ceil( $bonus_amount );
									$refPrefix = "BNS-";
									$externalNoteBonusDiscount = $bonus_percentage."% bonus";
								}else if( $promotion_type == 'discount' ){
									$csr_price = $getTempData->csr_price;
									$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 );
									$refPrefix = "DIS-";
									$externalNoteBonusDiscount = $discount_percentage."% discount";
								}
								$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
								$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
								$created = ( $getTempData->created != "" ) ? $getTempData->created : '';
								$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
								$source = ( $getTempData->source != "" ) ? $getTempData->source : '';
								$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
								$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
								$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
								$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
								$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';
								$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
								$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
								$pool_reference = ( $getTempData->pool_ref != "" ) ? $getTempData->pool_ref : '';
								$token = ( $getTempData->token != "" ) ? $getTempData->token : 'CSR';
								$redemptionWeek = $week_number;
								$redemptionYear = $year_number;
								if( $promotion_type == 'bonus' ){
									$new_pool_reference = sprintf( 'BNS-%s-%s', $year_number, sprintf("%02d", $week_number) );
								}else if( $promotion_type == 'discount' ){
									$new_pool_reference = sprintf( 'DIS-%s-%s', $year_number, sprintf("%02d", $week_number) );
								}
								if( $promotion_delivery_start_week > 0 ){
									for( $week_i=0; $week_i < $promotion_delivery_start_week; $week_i++ ){
										$week_number = $week_number + 1;
										if( $week_number > $totalNumberWeek ){
											$week_number = $week_number - $totalNumberWeek;
											$year_number = $year_number + 1;
										}else{
											$year_number = $year_number;
										}
									}
								}
								if( $csr_amount_initial <= $csr_segmentation ){
									$admNo = $reference.'-000';
									$newAdmNo = ++$admNo;
									$amount_due = $csr_amount_initial;
									if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
										$corp_approved_10 = $distribution_status;
									}else{
										$corp_approved_10 = 'Pending';
									}
									$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - '. $externalNoteBonusDiscount .' provided for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
									if( $distribution_status == 'Security Hold' ){
										$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
									}
									$notes_external_10 = notes_trim_pipe( $notes_external_10 );
									$text_7 = null;
									if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
										$text_7 = 'Pending';
									}
									$data = array(
										'reference'				=>	wp_strip_all_tags( $refPrefix . $newAdmNo ),
										'eth_address'			=>	wp_strip_all_tags( $eth_address ),
										'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
										'csr_amount_issued'		=>	0,
										'amount_due'			=>	$amount_due,
										'username'				=>	wp_strip_all_tags( $username ),
										'first_name'			=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
										'last_name'				=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
										'redemption_date'		=>	$created,
										'email'					=>	wp_strip_all_tags( $email ),
										'_user_status'			=>	$member_status,
										// 'kyc_status'			=>	$distribution_status,
										// 'pool_ref'				=>	$pool_reference,
										'pool_ref'				=>	$new_pool_reference,
										'corp_approved'			=>	$corp_approved_10,
										'notes_external'		=>	$notes_external_10,
										'text_7'				=>	$text_7,
										'text_10'				=>	$year_number.'/'.sprintf("%02d", $week_number),
										'text_9'				=>	$promotion_type,
										'imported_by'			=>	$import_by,
										'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
										'token'					=>	$token
									);
									$inserting = $wpdb->insert( $tableTokenHolder, $data );
									if( $inserting ){
										$countSuccess++;
										$user_type = 'sm';
										$log_type = 'new_delivery_plan_redemptions_append';
										$logs = sprintf( __('Appended promotion record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
										create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
										// $wpdb->update( $tableNewDeliveryPlanTemp, array( 'append_status' => 1 ), array( 'id' => $getTempData->id ) );
									}else{
										$error = 1;
										$countError++;
										$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
										echo wp_json_encode( $out );
										exit;
									}
								}else{
									$csr_amount_pending = $csr_amount_initial;
									$newAdmNo = "";
									$loopCounter = 0;
									for( $i=0; $i < $promotion_number_of_deliveries; $i++ ){
										$amount_due = $csr_amount_pending / ( $promotion_number_of_deliveries - $i );
										$amount_due = ceil( $amount_due );
										if( $i == 0 ){
											$admNo = $reference.'-000';
										}else{
											$admNo = $newAdmNo;
										}
										$newAdmNo = ++$admNo;
										if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
											$corp_approved_10 = $distribution_status;
										}else{
											$corp_approved_10 = 'Pending';
										}
										if( $week_number > $totalNumberWeek ){
											$week_number = $week_number - $totalNumberWeek;
											$year_number = $year_number + 1;
										}else{
											$year_number = $year_number;
										}
										$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);
										$notes_external_10 = '| CSR delivery starts in week '. sprintf("%02d", $week_number).'/'.$year_number .' - '. $externalNoteBonusDiscount .' provided for redemption in week '. sprintf("%02d", $redemptionWeek).'/'.$redemptionYear .' |';
										if( $distribution_status == 'Security Hold' ){
											$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
										}
										$notes_external_10 = notes_trim_pipe( $notes_external_10 );
										$text_7 = null;
										if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
											$text_7 = 'Pending';
										}
										$data = array(
											'reference'				=>	wp_strip_all_tags( $refPrefix . $newAdmNo ),
											'eth_address'			=>	wp_strip_all_tags( $eth_address ),
											'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
											'csr_amount_issued'		=>	0,
											'amount_due'			=>	$amount_due,
											'username'				=>	wp_strip_all_tags( $username ),
											'first_name'			=>	ucwords( strtolower( wp_strip_all_tags( $first_name ) ) ),
											'last_name'				=>	ucwords( strtolower( wp_strip_all_tags( $last_name ) ) ),
											'redemption_date'		=>	$created,
											'email'					=>	wp_strip_all_tags( $email ),
											'_user_status'			=>	$member_status,
											// 'kyc_status'			=>	$distribution_status,
											// 'pool_ref'				=>	$pool_reference,
											'pool_ref'				=>	$new_pool_reference,
											'corp_approved'			=>	$corp_approved_10,
											'notes_external'		=>	$notes_external_10,
											'text_7'				=>	$text_7,
											'text_10'				=>	$new_week_number,
											'text_9'				=>	$promotion_type,
											'imported_by'			=>	$import_by,
											'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
											'token'					=>	$token
										);
										$csr_amount_pending = $csr_amount_pending - $amount_due;
										$inserting = $wpdb->insert( $tableTokenHolder, $data );
										if( $inserting ){
											$countSuccess++;
											$loopCounter++;
											$user_type = 'sm';
											$log_type = 'new_delivery_plan_redemptions_append';
											$logs = sprintf( __('Appended promotion record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
											create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
										}else{
											$error = 1;
											$countError++;
											$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => 0, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
											echo wp_json_encode( $out );
											exit;
										}
										// $week_number++;
										$week_number = $week_number + $promotion_delivery_interval;
									}
									if( $loopCounter == $promotion_number_of_deliveries ){
										// $wpdb->update( $tableNewDeliveryPlanTemp, array('append_status' => 1), array( 'id' => $getTempData->id ) );
									}
								}
								$rowDataCountPromotion = $getTempData->id;
							}

						}

					}
				}
				if( $_POST['total_paged'] == $_POST['page_id'] ){
					/* $total_items_user_status = $wpdb->get_var("SELECT COUNT(DISTINCT(`username`)) FROM $tableNewDeliveryPlanTemp WHERE 1");
					$per_page = 50;
					$total_paged_user_status = ceil( $total_items_user_status / $per_page ); */
					$total_items_user_status = 0;
					$total_paged_user_status = 0;
					$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
					$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
					$out = array( "error" => 0,'msg' => sprintf( __('<br/>%s: Appended : %s, Failed : %s',CIP_TXTDOMAIN), $rowDataCount, $countSuccess, $countError ), 'isLastPage' => 'yes', 'total_items_user_status' => $total_items_user_status, 'total_paged_user_status' => $total_paged_user_status, 'msg2' => __('User status check & update started...',CIP_TXTDOMAIN), 'totalmsg_user_status' => sprintf( __('%s row\'s to check & update user status', CIP_TXTDOMAIN),$total_items_user_status ), 'test' => "SELECT COUNT(id) FROM $tableNewDeliveryPlanTemp WHERE 1 GROUP BY `username`" );
				}else{
					$out = array( "error" => 0,'msg' => sprintf( __('<br/>%s: Appended : %s, Failed : %s',CIP_TXTDOMAIN), $rowDataCount, $countSuccess, $countError ), 'isLastPage' => 'no' );
				}
			}
		}else if( isset( $_POST['appending_data_user_status'] ) && $_POST['appending_data_user_status'] == 'yes' ){
			$per_page = 50;
			$paged = isset( $_POST['page_id_user_status'] ) ? max( 0, intval( $_POST['page_id_user_status'] -1 ) * $per_page ) : 0;
			$error = 0;
			$rowDataCount= 0;
			$countError = 0;
			$countSuccess = 0;
			$insertingCount = 1;
			$rowProceed = $paged;
			$getTempDatas = $wpdb->get_results("SELECT * FROM $tableNewDeliveryPlanTemp WHERE 1 GROUP BY `username` ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."");
			if( $getTempDatas ){
				foreach( $getTempDatas as $getTempData ){
					$username = $getTempData->username;
					$member_status = $getTempData->member_status;
					$statusUpdate = $wpdb->query( $wpdb->prepare( "UPDATE $tableTokenHolder SET `_user_status` = %s WHERE username = %s AND _user_status != 'Security Hold'", $member_status, $username ) );
					if( $statusUpdate ){
						$user_type = 'sm';
						$log_type = 'new_delivery_plan_appended_status_update';
						$logs = sprintf( __('Member status update, username:%s ,status:%s, pool_ref:%s at %s', CIP_TXTDOMAIN), $username, $member_status, $getTempData->pool_ref,date_i18n('d/m/Y H:i:s') );
						create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
					}
					$rowDataCount++;
					$rowProceed++;
				}
				foreach( $getTempDatas as $getTempData ){
					$username = $getTempData->username;
					$member_status = $getTempData->member_status;
					//only check abandoned
					if( $member_status == 'abandoned' ){
						$expiredDate = 'expired/'.date_i18n('Y-m-d');
						$dataUpdate = array(
							'pool_ref'	=>	$expiredDate
						);
						$dataWhere = array(
							'username'		=>	$username,
							'corp_approved'	=>	'Pending',
							'text_9'		=>	'bonus',
						);
						$poolUpdate = $wpdb->update( $tableTokenHolder, $dataUpdate, $dataWhere );
						if( $poolUpdate ){
							$user_type = 'sm';
							$log_type = 'new_delivery_plan_appended_status_update';
							$logs = sprintf( __('Pool ref update for abandoned user to %s, username:%s ,corp_approved:Pending, text_9:bonus, pool_ref:%s at %s', CIP_TXTDOMAIN), $expiredDate, $username, $getTempData->pool_ref,date_i18n('d/m/Y H:i:s') );
							create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
						}
					}
				}
			}
			if( $_POST['total_paged_user_status'] == $_POST['page_id_user_status'] ){
				$out = array( "error" => 0,'msg' => sprintf( __('<br/>%s: User status checked & updated',CIP_TXTDOMAIN), $rowProceed ), 'isLastPage_user_status' => 'yes', 'test' => "SELECT * FROM $tableNewDeliveryPlanTemp WHERE 1 GROUP BY `username` ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."" );
				$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
				$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
			}else{
				$out = array( "error" => 0,'msg' => sprintf( __('<br/>%s: User status checked & updated',CIP_TXTDOMAIN), $rowProceed ), 'isLastPage_user_status' => 'no', 'test' => "SELECT * FROM $tableNewDeliveryPlanTemp WHERE 1 GROUP BY `username` ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."" );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cancel_new_delivery_plan_append_process', 'cancel_new_delivery_plan_append_process_callback' );
function cancel_new_delivery_plan_append_process_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYCancelAppendDataYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableNewDeliveryPlan = $wpdb->prefix.'new_delivery_plan';
		$tableNewDeliveryPlanTemp = $wpdb->prefix.'new_delivery_plan_temp';
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlan."`");
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableNewDeliveryPlanTemp."`");
		if( $delete ){
			$out = array( "error" => 0,'msg' => __('Cancelled',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}