<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name = "index?page=view";
$form_action = "insert";
$button_value = "Add";
$table_name = "set_mangmnt"; 
$page_name = "Add Set";
$query_string = "";
$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(set_number, 5) AS UNSIGNED)), 0) + 1 AS new_id FROM set_mangmnt");
$rr_row = mysqli_fetch_assoc($rr_query);
$set_number = '1' . str_pad($rr_row['new_id'], 2, '0', STR_PAD_LEFT);

// Insert action
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert') {    
    utility::addslashesOnAllInput(array("query_string"));
    
    $description = $_REQUEST['description'];
    $set_number = $_REQUEST['set_number'];
    
	$created_by					= $_SESSION['user_id'];
	$created_on					= date("Y-m-d H:i:s");	
	$updated_by					= $_SESSION['user_id'];
	
    $sql = "INSERT INTO $table_name (description, set_number,created_on,created_by,updated_by) 
	VALUES ('$description', '$set_number','$created_on', '$created_by', '$updated_by')";
    mysqli_query($conn, $sql);
	$set_id = mysqli_insert_id($conn);
     
	 
	  	 if(count($_REQUEST['part_number'])>0){	 
			foreach($_REQUEST['part_number'] as $key => $part_number){
				$part_number                   = $_REQUEST['part_number'][$key];			

				if($part_number!=""){
					 $sql1= "INSERT INTO set_mangmnt_mapping (set_id,part_number) VALUES('$set_id','$part_number')";
					mysqli_query($conn,$sql1);
					
				}
			}
		}
    $_SESSION['info_message'] = "Set added successfully";
    header("Location: $file_name");
    exit();
}

// Edit action
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
    $id = $_REQUEST['id'];
    $form_action = "update";
    $button_value = "Update";
    $page_name = "Edit Set";

    $sql = "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn, $sql);
    $row_edit = mysqli_fetch_array($result_edit);

    $description = $row_edit['description'];
    $set_number = $row_edit['set_number'];
}

// Update action
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update') {
    utility::addslashesOnAllInput(array("query_string"));
    
    $id = $_REQUEST['id'];
    $description = $_REQUEST['description'];
    $set_number = $_REQUEST['set_number'];
    $updated_by					= $_SESSION['user_id'];
	
	$sql = "UPDATE $table_name SET set_number = '$set_number', 
	description = '$description',updated_by = '$updated_by' WHERE id = $id";
    mysqli_query($conn, $sql);
	
	  
			if(count($_REQUEST['part_number'])>0){	
					foreach($_REQUEST['part_number'] as $key => $part_number){
						$part_number                   = $_REQUEST['part_number'][$key];		
						$referal_parent_mapping_id 		= $_REQUEST['referal_parent_mapping_id'][$key];			
							
							if(mysqli_num_rows(mysqli_query($conn,"SELECT * FROM set_mangmnt_mapping WHERE id = '$referal_parent_mapping_id' ")) > 0){
								  $sql1= "UPDATE set_mangmnt_mapping SET part_number = '$part_number' WHERE id = '$referal_parent_mapping_id' ";
							}else{
								$sql1= "INSERT INTO set_mangmnt_mapping (set_id,part_number)
								VALUES('$id','$part_number')";
							}
							mysqli_query($conn,$sql1);
						}
					}
				

    
    $_SESSION['info_message'] = "Set updated successfully";
    header("Location: $file_name");
    exit();
}
################################################# END UPDATE ################################################# 
?>
<style>
em{color:red;font-size: 20px;position: absolute;}
</style>
<!-- parent cloning -->
<div id="new_assest_div_to_clone" style="display:none;">
<div class='row mt-2'> 
	<div class='col-6'> 
		<div class=""> 
			 <? $gsi->getPartNumberListNew("part_number[]","","100%",false,"form-control select2 part_number","required"); ?>
		</div> 
	</div>
	
	<div class='col-1'> 
		<div class="custom-trash">
			<label class="control-label"></label> 
			<span class="fa fa-trash delete_new_assest text-danger" alt=""></span>
		</div>
    </div>
</div>
</div>

<section class="content-header">
	<div class="container-fluid">
		<div class="row mb-2">
			<div class="col-sm-6">
				<h1>
					<?=$page_name;?>
				</h1>
			</div>
			<div class="col-sm-6">
			<?
			$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
			$query_string = str_ireplace("page=add", "page=view", $query_string);
			?>
			<button type="button" id="back" name="back" value="back"  style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-primary" onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
			</div>
		</div>
	</div>
</section>
<section class="content">
	<div class="row">
		<div class="col-lg-12">
              <div class="card box-primary">
               <form class="form-horizontal" method="post" name="form1" id="form1" action="index?page=add&action=<?php echo $form_action; ?>" onsubmit="return validateForm(this)" enctype="multipart/form-data">
					  <div class="card-body">
					  <div class="row">
						<div class="col-lg-2">
						  <label for="set_number" class="control-label">Set Number<em>*</em></label>
						  <div>
							<input type="text" id="set_number" name="set_number" value="<?php echo $set_number; ?>" class="form-control" placeholder="Set Number" required readonly>
						  </div>
						</div>
                        <div class="col-lg-10">
						  <label for="description" class="control-label">Set Description<em>*</em></label>
						  <div>
							  <textarea class="form-control" rows="1" id="description" name="description"
                                            placeholder="Set Description"><?php echo stripslashes($description); ?></textarea>
						  </div>
						</div>

						</div>
						

						<?	
							$map_hc=mysqli_query($conn,"SELECT * FROM set_mangmnt_mapping WHERE set_id='".$id."'");
							$map_cot=mysqli_num_rows($map_hc);
							if($map_cot>0){
							while($map_row=mysqli_fetch_array($map_hc)){
								$values=$map_row['id'];
						?>
						<div class="initial_row_for_na" id="new_assest<?=$values;?>" data-na_count="<?=$values;?>">								
							<div class='mt-3'> 
							<label class="control-label" for="Company Name">Part Number<em></em></label>
							<div class='row'> 
							<div class='col-6'> 
								<div class=""> 
									 <? $gsi->getPartNumberListNew("part_number[]",$map_row['part_number'],"100%",false,"form-control select2 part_number","required"); ?>
								</div> 
							</div>
							<div class="col-lg-2"> 
								<div class="custom-trash">
									<input type="hidden" name="referal_parent_mapping_id[]" value="<?php echo $map_row['id'];?>" required_>		
											
									<span class="fa fa-trash delete_new_assest text-danger" alt="<?php echo $map_row['id'];?>"></span>
									<i class="fa fa-refresh fa-spin" id="load_new_assest_<?=$map_row['id'];?>" style="font-size: 10px;display:none;"></i>
									<i class="fa fa-check" id="status_update_done_<?=$map_row['id'];?>" style="color:#bad23a;font-size: 10px;display:none;"></i>
								 </div>
								</div>
							</div>
							</div>
							
						</div>
						<? }}else{?>
						<div class="initial_row_for_na" id="new_assest1" data-na_count="1">
													
							<div class='mt-3'> 
							<label class="control-label" for="Company Name">Part Number<em></em></label>
							<div class='row'> 
							<div class='col-6'> 
								<div class=""> 
									<? $gsi->getPartNumberListNew("part_number[]","","100%",false,"form-control select2 part_number","required"); ?>
								</div> 
							</div>
						
							</div>
							</div>
						</div>
						<? }?>	
						<div class="form-group col-sm-12 new_assest_div_to_append">	
							<label class="add_one_more_new_assest text-primary" style="margin-left:0%;cursor:pointer"><span class="fa fa-plus"></span>Add More</label>
						</div>
						<!-- multiple parents records end   -->


					  </div>

					  <div class="card-footer">
						<input type="hidden" id="id" name="id" value="<?php echo $id; ?>">
						<input type="hidden" id="query_string" name="query_string" value="<?php echo $query_string; ?>">
						<button type="submit" id="submit" name="submit" value="<?php echo $button_value; ?>" class="btn btn-primary">
						  Submit
						  <i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
						</button>
					  </div>
					</form>

              </div><!-- /.box -->
		</div>
	</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
	
// add  clone
$('.add_one_more_new_assest').click(function() {	
		$('#new_assest_div_to_clone').show();		
		var div_count = $('.initial_row_for_na').last().attr("data-na_count");
		div_count++;
		var cloned_div = $('#new_assest_div_to_clone').clone().addClass("initial_row_for_na").attr("id","new_assest"+div_count).attr("data-na_count",div_count);		
		$('.new_assest_div_to_append').before(cloned_div);	
		$('#new_assest'+div_count).children().find(".fa-spin").attr("id","make_load"+div_count);
		
			
		$('#new_assest_div_to_clone').hide();			
	});


$("#form1").on("click", ".delete_new_assest",function() {
	    if(confirm('Are you sure! You want to delete')){		
			if($(this).attr("alt") != ""){
				var na_mapping_id = $(this).attr("alt");
				$('#load_new_assest_'+na_mapping_id).show();
				var form_data   = {'na_mapping_id':na_mapping_id};       
				$.ajax({
					async: true,
					type: "POST",
					url: site_url+"/modules/enquiries/index.php?page=ajax_actions&action=delete_referal_mapping",
					data: form_data,
					success: function(result){    
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$('#status_update_done_'+na_mapping_id).show();
							$('#load_new_assest_'+na_mapping_id).hide();
							
							setTimeout(function() {
								$('#status_update_done_'+na_mapping_id).hide();
								$('#new_assest'+na_mapping_id).remove();
								//location.reload();
							},1000);
						}
					}
				});
			}else{
				$(this).parent().parent().parent().remove();
			}
		}
	});
	
	/* /////////////////ajax-action
	else if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_referal_mapping'){
	$id = $_REQUEST['na_mapping_id'];
	mysqli_query($conn,"DELETE FROM referal_parents_mapping WHERE id = '$id' ");
	$returnArray["status"] = "success";
	echo json_encode($returnArray);
} */
});
</script>