<?php
add_shortcode('SM-CSR25-SCHEDULER','cip_sm_csr25_scheduler_cb');
function cip_sm_csr25_scheduler_cb(){
    if( (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
	$html = "";
	global $wpdb;
	$tableScheduler = $wpdb->prefix.'csr25_scheduler';
	wp_enqueue_style( 'jquery-ui-style' );
	wp_enqueue_style( 'jquery-ui-timepicker-style' );
	wp_enqueue_script('jquery-ui');
	wp_enqueue_script('jquery-ui-timepicker');
	wp_enqueue_script('jquery-ui-sliderAccess');
	wp_enqueue_script('moment');
	wp_enqueue_style( 'bs-table' );
	ob_start();
	$add_csr_url = add_query_arg( 'action', 'add', get_permalink() );
	if( isset( $_GET['action'] ) && $_GET['action'] == 'add' ){	// add csr plans
	?>
	<div class="row">
	<div class="col-12">
		<form name="cip_csr25_schedule_changer" id="cip_csr25_schedule_changer">
		<div class="form-row">
			<div class="form-group col-md-12">
				<label for="selling_price_csr25"><?php _e('Selling Price of CSR25*',CIP_TXTDOMAIN); ?></label>
				<input type="number" step="0.00001" class="form-control" name="selling_price_csr25" id="selling_price_csr25" />
			</div>
			<div class="form-group col-md-12">
				<label for="price_type"><?php _e('Type*',CIP_TXTDOMAIN); ?></label>
				<select name="price_type" class="form-select">
					<option value="" selected disabled><?php _e('Choose option',CIP_TXTDOMAIN); ?></option>
					<option value="prompt"><?php _e('Prompt',CIP_TXTDOMAIN); ?></option>
					<option value="scheduled"><?php _e('Scheduled',CIP_TXTDOMAIN); ?></option>
				</select>
			</div>
			<div class="form-group col-md-8 time_schedule" style="display:none;">
				<label for="schedule_time"><?php _e('Schedule date*',CIP_TXTDOMAIN); ?></label>
				<input type="text" class="form-control" name="schedule_time" id="schedule_time" />
				<input type="hidden" class="form-control" name="schedule_time_alt" id="schedule_time_alt" />
			</div>
			<div class="form-group col-md-2 time_schedule" style="display:none;">
				<label for="schedule_hours"><?php _e('Hours*',CIP_TXTDOMAIN); ?></label>
				<select name="schedule_hours" class="form-control">
					<?php for ($h = 0; $h < 24; $h++) printf("<option value=\"%02d\"" . (!$h ? " selected" : "") . ">%02d</option>", $h, $h); ?>
				</select>
			</div>
			<div class="form-group col-md-2 time_schedule" style="display:none;">
				<label for="schedule_minutes"><?php _e('Minutes*',CIP_TXTDOMAIN); ?></label>
				<select name="schedule_minutes" class="form-control">
					<?php for ($m = 0; $m < 60; $m++) printf("<option value=\"%02d\"" . (!$m ? " selected" : "") . ">%02d</option>", $m, $m); ?>
				</select>
			</div>
		</div>
		<button type="submit" class="btn btn-primary"><?php _e('Add', CIP_TXTDOMAIN); ?></button>
		<input type="hidden" name="action" value="cip_add_csr25_scheduler" />
		<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPxsmCSR25ScheduleraddxCIP_'); ?>" />
		<p class="form_response"></p>
		</form>
	</div>
	</div>
	<?php
	}else if( isset( $_GET['action'] ) && $_GET['action'] == 'edit' && $_GET['pid'] != "" ){	// add saving plans
		/*$getPlan = $wpdb->get_row("SELECT * FROM $tablePlans WHERE id=".$_GET['pid']."");
		if( $getPlan ){
		?>
		<div class="row">
		<div class="col-12">
			<form name="cip_saving_plans_edit" id="cip_saving_plans_edit">
			<div class="form-row">
				<div class="form-group col-md-4">
					<label for="plan_name"><?php _e('Plan Name*',CIP_TXTDOMAIN); ?></label>
					<input type="text" class="form-control" name="plan_name" id="plan_name" value="<?php echo $getPlan->plan_name; ?>" />
				</div>
				<div class="form-group col-md-4">
					<label for="locking_period"><?php _e('Locking period*',CIP_TXTDOMAIN); ?></label>
					<select name="locking_period" class="form-select">
						<option value="365" <?php echo selected( '365', $getPlan->plan_periods ); ?>><?php _e('12 Months (365 days)',CIP_TXTDOMAIN); ?></option>
						<option value="182" <?php echo selected( '182', $getPlan->plan_periods ); ?>><?php _e('6 Months (182 days)',CIP_TXTDOMAIN); ?></option>
					</select>
				</div>
				<div class="form-group col-md-4">
					<label for="plan_interest"><?php _e('Plan Interest*',CIP_TXTDOMAIN); ?></label>
					<input type="number" class="form-control" name="plan_interest" id="plan_interest" value="<?php echo $getPlan->plan_interest; ?>" />
				</div>
			</div>
			<button type="submit" class="btn btn-primary"><?php _e('Save', CIP_TXTDOMAIN); ?></button>
			<a href="<?php echo get_permalink(); ?>" type="button" class="btn btn-primary"><?php _e('Cancel', CIP_TXTDOMAIN); ?></a>
			<input type="hidden" name="action" value="cip_addsaving_plan_edit" />
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPxsmsavingplaneditxCIP_'); ?>" />
			<p class="form_response"></p>
			</form>
		</div>
		</div>
		<?php
		}*/
	}else{ //display added saving plans
	?>
	<div class="row">
		<div class="col-12 text-right mt-3">
			<a href="<?php echo $add_csr_url; ?>" class="btn btn-primary"><?php _e('Add New',CIP_TXTDOMAIN); ?></a>
		</div>
	</div>
	<?php
		$getSchedulers = $wpdb->get_results("SELECT * FROM $tableScheduler order by id desc");
		wp_enqueue_style( 'cip-css' );
		wp_enqueue_style( 'bs-table' );
		wp_enqueue_style( 'bs-sticky-header' );
		wp_enqueue_script('bs-table');
		wp_enqueue_script('bs-sticky-header');
		wp_enqueue_script('bs-table-filter-control');
		?>
		<table id="cip_saving_plans_table"
		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="true" data-show-columns-toggle-all="false" data-show-export="false" data-click-to-select="false" class="table table-bordered">
		<thead>
			<tr>
				<th data-field="id" data-sortable="false" class="plan_id"><?php _e('Id',CIP_TXTDOMAIN); ?></th>
				<th data-field="csr25_price" data-sortable="true" data-filter-control="input" class="csr25_price"><?php _e('CSR25 Price',CIP_TXTDOMAIN); ?></th>
				<th data-field="type" data-sortable="true" data-filter-control="input" class="type"><?php _e('Type',CIP_TXTDOMAIN); ?></th>
				<th data-field="create_date" data-sortable="true" data-filter-control="input" class="create_date"><?php _e('Created',CIP_TXTDOMAIN); ?></th>
				<th data-field="start_date" data-sortable="true" data-filter-control="input" class="start_date"><?php _e('Start date',CIP_TXTDOMAIN); ?></th>
				<th data-field="status" data-sortable="false" data-filter-control="false" class="status"><?php _e('Status',CIP_TXTDOMAIN); ?></th>
				<th data-field="action" data-sortable="false" data-filter-control="false" class="action"><?php _e('Action',CIP_TXTDOMAIN); ?></th>
			</tr>
		</thead>
	<?php
		$loopCount = 1;
		if( $getSchedulers ){
			foreach( $getSchedulers as $getScheduler ){
				$delete_link = '';
				$edit_plan_url = add_query_arg( ['action' => 'edit','sid' => $getPlan->id], get_permalink() );
				if( $getScheduler->status == 'pending' ){
					$delete_link = '<a class="mr-2 del_scheduler_csr25" href="javascript:void(0);" data-toggle-tt="tooltip" data-placement="top" title="'.__('Delete',CIP_TXTDOMAIN).'"><i class=" fa fa-trash"></i></a>';
				}
				
				$create_date = '-';
				try {
					$createDateObj = DateTime::createFromFormat( 'Y-m-d H:i', $getScheduler->create_date );
					$create_date = $createDateObj->format('d/m/Y H:i');
				} catch (\Throwable $th) {
					$create_date = '-';
				}
				$start_date = '-';
				try {
					$startDateObj = DateTime::createFromFormat( 'Y-m-d H:i', $getScheduler->start_date );
					$start_date = $startDateObj->format('d/m/Y H:i');
				} catch (\Throwable $th) {
					$start_date = '-';
				}
				
			?>
			<tr data-schedular="<?php echo $getScheduler->id; ?>">
				<td><?php echo $loopCount; ?></td>
				<td><?php echo $getScheduler->csr25_price; ?></td>
				<td><?php echo $getScheduler->price_type; ?></td>
				<td><?php echo $create_date; ?></td>
				<td><?php echo $start_date; ?></td>
				<td><?php echo $getScheduler->status; ?></td>
				<td><?php echo $delete_link; ?></td>
			</tr>
			<?php
			$loopCount++;
			}
		}
		?>
	</table>
	<?php
	}
	$html .= ob_get_clean();
	return $html;
    }
}
add_action('wp_footer','cip_csr25_schedule_changer_script');
function cip_csr25_schedule_changer_script(){
    ?>
    <script>
        $('body').on('submit', '#cip_csr25_schedule_changer', function(){
            $form = $(this);
            $form.find('.form_response').html('');
            var selling_price_csr25 = $(this).find('input[name="selling_price_csr25"]').val();
            var  price_type = $(this).find('select[name="price_type"]').val();
            var schedule_time = $(this).find('input[name="schedule_time"]').val();
            // console.log( price_type );
            if( selling_price_csr25 == "" || price_type == "" || price_type == null ){
                $form.find('.form_response').html('* Fields are required');
                return false;
            }
            if( price_type == 'scheduled' && schedule_time == "" ){
                $form.find('.form_response').html('* Fields are required');
                return false;
            }
            var data = $(this).serialize();
            $form.block( block_config );
            $.post(cipscript.ajax_url, data, function(response) {
                var obj = JSON.parse( response );
                $form.unblock();
                $form.find('.form_response').html( obj.msg );
                if( obj.error == 0 ){
                    window.location.href = obj.redirect_url;
                }
            });
            return false;
        });
        $('#cip_csr25_schedule_changer select[name="price_type"]').on('change', function(){
            var thisVal = $(this).val();
            if( thisVal == "scheduled" ){
                $('.time_schedule').slideDown();
            }else{
                $('.time_schedule').slideUp();
            }
        });
        $('body').on('click', '.del_scheduler_csr25', function(){
            var current_tr = $(this).closest('tr');
            Swal({
                title: 'Are you sure?',
                text: "Are you sure you want to delete CSR25 schedular?",
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes'
            }).then((result) => {
                if (result.value) {
                    var thisid = current_tr.attr('data-schedular');
                    current_tr.block( block_config );
                    var data = {'action' : 'cip_csr25_schedular_remover','thisid' : thisid, '_micro': cipscript.microschedulardel };
                    $form.block( block_config );
                    $.post(cipscript.ajax_url, data, function(response) {
                        var obj = JSON.parse( response );
                        current_tr.unblock();
                        if( obj.error == 0 ){
                            Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
                            window.location.reload();
                        }else{
                            Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
                        }
                        current_tr.unblock();
                        
                    });
                }
            });
            return false;
        });
    </script>
    <?php
}
add_action('wp_ajax_cip_add_csr25_scheduler','cip_add_csr25_scheduler_callback');
function cip_add_csr25_scheduler_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableScheduler = $wpdb->prefix.'csr25_scheduler';
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsmCSR25ScheduleraddxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$status = ( $_POST['price_type'] == 'prompt' ) ? 'active' : 'pending';
		$schedule_time = ( $_POST['price_type'] == 'prompt' ) ? gmdate('Y-m-d H:i') : sprintf( '%s %s:%s', $_POST['schedule_time_alt'], $_POST['schedule_hours'], $_POST['schedule_minutes'] );
		$data = array(
			'csr25_price'		=>	$_POST['selling_price_csr25'],
			'price_type'	=>	$_POST['price_type'],
			'create_date'	=>	gmdate('Y-m-d H:i'),
			'start_date'	=>	$schedule_time,
			'status'		=>	$status,
		);
		$insert = $wpdb->insert($tableScheduler, $data);
		if( $insert ){
			if( $_POST['price_type'] == 'prompt' ){
				$lastid = $wpdb->insert_id;
				$getOldActive = $wpdb->get_results("SELECT * FROM $tableScheduler WHERE status='active' AND id!=$lastid");
				if( $getOldActive ){					
					foreach( $getOldActive as $oldActive ){					
						$dataActive = array( 'status'	=>	'overwritten' );
						$whereActive = array( 'id'	=>	$oldActive->id );
						$updateActive = $wpdb->update($tableScheduler, $dataActive, $whereActive);
					}
				}
				
				$selling_price_csr25 = ( !empty( $_POST['selling_price_csr25'] ) ) ? $_POST['selling_price_csr25'] : 0.025;				
				update_option( 'selling_price_csr25', $selling_price_csr25 );
			}
			// $out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'redirect_url'	=> get_permalink( get_page_by_path('csr-scheduler') ) );
			//$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'redirect_url'	=> get_permalink( get_page_by_path('csr-price-scheduler') ) );
			$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'redirect_url'	=> get_permalink( 9218 ) );
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_csr25_schedular_script','cip_csr25_schedular_script_cb');
add_action('wp_ajax_nopriv_csr25_schedular_script','cip_csr25_schedular_script_cb');
function cip_csr25_schedular_script_cb(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableScheduler = $wpdb->prefix.'csr25_scheduler';
	if( isset( $_GET['cronmicro'] ) && str_rot13( $_REQUEST['cronmicro'] ) === 'CIPcsr25_schedularCIP'  ){ //PVCpfe25_fpurqhynePVC
		$getSchedulars = $wpdb->get_results("SELECT * FROM $tableScheduler WHERE price_type='scheduled' AND status='pending'");
		if( $getSchedulars ){
			foreach( $getSchedulars as $getSchedular ){
				$start_date = "";
				$current_date = DateTime::createFromFormat( 'Y-m-d H:i', gmdate('Y-m-d H:i') );
				try{
					$start_date = DateTime::createFromFormat( 'Y-m-d H:i', $getSchedular->start_date );
				}catch (\Throwable $th){
				}
				if( !empty( $start_date ) ){
					if( $current_date >= $start_date ){
						
						$dataActive = array( 'status'	=>	'overwritten' );
						$whereActive = array( 'status'	=>	'active' );
						$updateActive = $wpdb->update($tableScheduler, $dataActive, $whereActive);
						$data = array('status'	=>	'active');
						$where = array('id'	=>	$getSchedular->id);
						$update = $wpdb->update($tableScheduler, $data, $where);
						if( $update ){
							update_option( 'selling_price_csr25', $getSchedular->csr25_price );
						}
					}
				}
			}
		}
	}
	// echo gmdate('Y-m-d H:i');
	// echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_csr25_schedular_remover','cip_csr25_schedular_remover_callback');
function cip_csr25_schedular_remover_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyPendingSchedularDeleteyX_' ) ){
		global $wpdb;
		$tableScheduler = $wpdb->prefix.'csr25_scheduler';
		$getSingleSchedular = $wpdb->get_row("SELECT id FROM $tableScheduler WHERE id = ".$_POST['thisid']." AND status = 'pending'");
		if( $getSingleSchedular ){
			$where = [ 'id' => $_POST['thisid'] ];
			$deleting = $wpdb->delete( $tableScheduler, $where );
			$out = array( "error" => 0,'msg' => __('Record Deleted',CIP_TXTDOMAIN) );
		}else{
			$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
?>