<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view";
$form_action	= "insert";
$button_value 	= "Add";
$table_name 	= "product_group";
$page_name      = "Add Product Group";
$id	 = "";
$vat = "";
$query_string = "";
################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string","parent_product_group_name"));
	
    $product_group_name 	= $_REQUEST['product_group_name']; 
    $product_short_code 	= $_REQUEST['product_short_code']; 
    $product_name_new 	= $_REQUEST['product_name_new']; 
	
    $sql= "INSERT INTO $table_name (product_group_name,product_short_code) VALUES('$product_group_name','$product_short_code')";
    mysqli_query($conn,$sql);
	$group_id = mysqli_insert_id($conn);
	
	if(count($_REQUEST['parent_product_group_name'])>0){
			foreach($_REQUEST['parent_product_group_name'] as $key => $parent_product_group_name){
				$parent_product_group_id                  = $_REQUEST['parent_product_group_name'][$key];		
				
				$parent_product_group_name = utility::getTableFieldById("product_group","product_group_name","id",$parent_product_group_id);
				if($parent_product_group_name ==''){
					$parent_product_group_name = $product_name_new ;
				}
				if($parent_product_group_name!=""){
					$sql1= "INSERT INTO product_group_mapping (group_id,parent_product_group_name,parent_group_id) VALUES('$group_id','$parent_product_group_name','$parent_product_group_id')";
					mysqli_query($conn,$sql1);
					
				}
			}
		}
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	$_SESSION['info_message'] = "$tmp added sucessfully";
    header("Location: $file_name");
    exit();
}
################################################# END INSERT #################################################

################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id = $_REQUEST['id'];

	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit Product Group";
	$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
	
    $sql= "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);

	$product_group_name 					= $row_edit['product_group_name']; 
	$product_short_code 					= $row_edit['product_short_code']; 
}
################################################# END EDIT ################################################# 


################################################## START UPDATE ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string","parent_product_group_name","referal_parent_mapping_id_pro","parent_product_group_name1"));
	 
	$id								= $_REQUEST['id'];
	$product_group_name 			= $_REQUEST['product_group_name'];
	$product_short_code 			= $_REQUEST['product_short_code'];
	$product_name_new 			= $_REQUEST['product_name_new'];
	

	$sql= "UPDATE $table_name SET product_group_name = '$product_group_name' ,product_short_code = '$product_short_code' WHERE id = $id";
    mysqli_query($conn,$sql);
	
	  if(count($_REQUEST['parent_product_group_name'])>0){	
			foreach($_REQUEST['parent_product_group_name'] as $key => $parent_product_group_name){	
				$parent_product_group_id				= $_REQUEST['parent_product_group_name'][$key];			
				$referal_parent_mapping_id_pro 			= $_REQUEST['referal_parent_mapping_id_pro'][$key];	
				$parent_product_group_name1 			= $_REQUEST['parent_product_group_name1'][$key];	
				
				$parent_product_group_name = utility::getTableFieldById("product_group","product_group_name","id",$parent_product_group_id);
					if($parent_product_group_name ==''){
						$parent_product_group_name = $parent_product_group_id ;
					}
				if(mysqli_num_rows(mysqli_query($conn,"SELECT * FROM product_group_mapping WHERE id = '$referal_parent_mapping_id_pro' ")) > 0){
					  $sql1= "UPDATE product_group_mapping SET parent_product_group_name = '$parent_product_group_name',parent_group_id = '$parent_product_group_id' WHERE id = '$referal_parent_mapping_id_pro' ";
				}else{
					if($product_name_new !=''){
						$parent_product_group_name = $product_name_new ;
					}
					 $sql1= "INSERT INTO product_group_mapping (group_id,parent_product_group_name,parent_group_id) VALUES('$id','$parent_product_group_name','$parent_product_group_id')";
				}
				mysqli_query($conn,$sql1);
			}
		}
		
	
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	$query_string = str_ireplace("page=add", "page=view", $query_string);
	$query_string = "&".$query_string;
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	$_SESSION['info_message'] = "$tmp updated sucessfully";
    header("Location: $file_name$query_string");
    exit();
}
################################################# END UPDATE ################################################# 
?>
<style>
em{color:red;font-size: 20px;position: absolute;}
</style>

<div id="new_product_div_to_clone" style="display:none;">
  <div class='row mt-3'> 
	<div class="col-lg-10"> 
	  <label for="parent_product_group_name" class=" control-label">Parent Product Groups Name<em>*</em></label>
	  <div class="">
		<? $gsi->getProductGroupCodeList("parent_product_group_name[]",$parent_product_group_name,"100%",false,"form-control select2"); ?>
	  </div>
	</div>
	<div class="col-lg-2"> 
		<div class="custom-trash"><br> 
			<span class="fa fa-trash delete_new_assest_pro text-danger " alt="" style="margin-top:15px; padding-left:10px;"></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>
	</div>
</section>
<section class="content">
	<div class="row">
		<div class="col-lg-12">
			<!-- general form elements -->
              <div class="card box-primary">
                <form class="form-horizontal" method="post" name="form1" id="form1" action="index?page=add&action=<? echo $form_action; ?>" onsubmit="return validateForm(this)" enctype="multipart/form-data">
                  <div class="card-body">
                  <div class="row">
                    <div class="col-sm-3">
                      <label for="product_group_name" class=" control-label"> Product Group Name<em>*</em></label>
                      <div class="">
                        <input type="text" id="product_group_name" name="product_group_name" value="<?php echo $product_group_name;?>" class="form-control" placeholder="EnterProduct Group Name" required>
						<span style="inline:block;color:red;display:none;" id="product_group_name_check"></span>
                      </div>
                    </div>
					<div class=" col-sm-3">
                      <label for="product_short_code" class=" control-label">Product Group Short Code<em>*</em></label>
                      <div class="">
                        <input type="text" id="product_short_code" name="product_short_code" value="<?php echo $product_short_code;?>" class="form-control" placeholder="Enter Product Group Short Code" required>
                      </div>
                    </div>
					<div class=" col-sm-6">
					 <div class="row">
						<div class="col-lg-12">
							<?	
								$map_hc1=mysqli_query($conn,"SELECT * FROM product_group_mapping WHERE group_id='".$id."'");
								$map_cot1=mysqli_num_rows($map_hc1);
								if($map_cot1>0){
								while($map_row12=mysqli_fetch_array($map_hc1)){
									$map_row1=utility::validate_crypt_data($map_row12);
									$values1=$map_row1['id'];
							?>
							 
							<div class="initial_row_for_na_pro" id="new_assest<?=$values1;?>" data-na_count="<?=$values1;?>">		 
								<div class='row'> 
								<? if($map_row1['parent_group_id'] !=0){?>
								<div class="col-lg-10"> 
									<label for="parent_product_group_name" class=" control-label">Parent Product Groups Name<em>*</em></label>
									  <div class="">
										<? $gsi->getProductGroupCodeList("parent_product_group_name[]",$map_row1['parent_group_id'],"100%",false,"form-control select2"); ?>
										<select id="parent_product_group_name" name="parent_product_group_name[]" class="form-control select2">
											<option value="0">Please Select</option>
											<?php
												/* $sql="select * from product_name";
												$res=mysqli_query($conn,$sql);
												while($row=mysqli_fetch_assoc($res)){
													echo '<option value="'.$row["id"].'">'.$row["group_code"].'</option>';
												} */
											?>
										</select>
									  </div>
								</div>
								<?}else{?>
								<div class="col-lg-10"> 
									<label for="parent_product_group_name" class=" control-label">Parent Product Groups Name<em>*</em></label>
									  <div class="">
										<input type="text" class="form-control" id="parent_product_group_name1" name="parent_product_group_name[]" value="<?= $map_row1['parent_product_group_name']; ?>">
									  </div>
								</div>
								<?}?>
								 <div class='col-2'> 
									<div class="custom-trash">
										<input type="hidden" name="referal_parent_mapping_id_pro[]" value="<?php echo $map_row1['id'];?>" required_>	
										<span class="fa fa-trash delete_new_assest_pro text-danger" alt="<?php echo $map_row1['id'];?>"style="margin-top:42px; padding-left:15px;"></span>
										<i class="fas fa-sync-alt fa-spin" id="load_new_assest_pro<?=$map_row1['id'];?>" style="font-size: 10px;display:none;"></i>
										<i class="fa fa-check text-success" id="status_update_done_pro<?=$map_row1['id'];?>" style="color:#bad23a;font-size: 10px;display:none;"></i>
									</div>
								 </div> 
								</div>				
							</div>
							<? }}else{?>
							<div class="initial_row_for_na_pro" id="new_assest1" data-na_count="1">	
							  <div class='row'> 
							   <div class="col-lg-12 " id=""> 
								<label for="parent_product_group_name" class="product_hide control-label">Parent Product Groups Name<em>*</em></label>
								  <div class="product_hide">
									<? $gsi->getProductGroupCodeList("parent_product_group_name[]",$parent_product_group_name,"100%",false,"form-control select2 "); ?>
									
											<?php
												/* $sql="select * from product_name";
												$res=mysqli_query($conn,$sql);
												while($row=mysqli_fetch_assoc($res)){
													echo '<option value="'.$row["id"].'">'.$row["group_code"].'</option>';
												} */
											?>
										
								  </div>
								</div> 
								 <div id="new_product_div" class="col-lg-12" style="display:none;">
									<div class="form-group"> 
										<label class="control-label " for="New Sector">New Parent Product Groups Name</label> 
										<div> 
											<input type="text" id="product_name_new" name="product_name_new" class="form-control" value="" placeholder="New Parent Product Groups Name"> 
										</div> 
									</div>
								</div>
								<div id="new_product_name_link" class="col-lg-12 text-right"style="color:#367FA9;cursor:pointer;">New Parent Name</div>
							   </div>
							  </div>
							<? }?>	
							<div class="form-group col-sm-12 new_assest_div_to_append_pro">	
								<label class="add_one_more_new_product  product_hide text-primary" style="margin-left:0%;cursor:pointer"><span class="fa fa-plus" autocomplete="off"></span>Add More</label>
							</div>
						</div>
						</div>
                    </div>
                  </div><!-- /.box-body -->
                  </div><!-- /.box-body -->
                  <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(){
	
	$("#new_product_name_link").click(function(){
		$("#new_product_div").toggle();
		$(".product_hide").toggle();
		$("#product_name_new").val('');
		$(".parent_product_group_name").val(null).trigger("change");
		var currentText = $(this).text();
		// Check the current text and toggle between "Old Product" and "New Product"
		if (currentText === 'Old Parent Name') {
			$(this).text('New Product Name');
		} else {
			$(this).text('Old Parent Name');
		}
	});
	$("#form1").submit(function() {
		$("#submit").attr("disabled", true);
		$('#page_load_div').show();
		//return true;
	});
	$("#form1").on("blur","#product_group_name",function(){	
		var product_group_name = $(this).val();
		var product_group_name = $("#product_group_name").val();
		var id = $("#id").val();
		if(product_group_name != ""){
		var form_data   = {'product_group_name':product_group_name,'id':id};       
			$.ajax({
				async: false,
				type: "POST",
				url: site_url+"/modules/product_group_name/index.php?page=ajax_actions&action=check_product_group_name_exist",
				data: form_data,
				success: function(result){          
					var resultObj = jQuery.parseJSON(result); 
					if(resultObj.status == "failure"){
						//alert("This product_group_name already in system");
						$("#product_group_name_check").show();
						$("#product_group_name_check").html("This product_group_name already in system.");
						//$("#email").val("");
						$("#product_group_name").focus();
					}else{
						$("#product_group_name_check").html("");
						$("#product_group_name_check").hide();
					}
				}
			});
		}
	});
	$('.add_one_more_new_product').click(function() {			
		$('#new_product_div_to_clone').show();		
		var div_count = $('.initial_row_for_na_pro').last().attr("data-na_count");
		div_count++;
		var cloned_div = $('#new_product_div_to_clone').clone().addClass("initial_row_for_na_pro").attr("id","new_assest"+div_count).attr("data-na_count",div_count);		
		$('.new_assest_div_to_append_pro').before(cloned_div);	
		$('#new_assest'+div_count).children().find(".fa-spin").attr("id","make_load"+div_count);
		$('#new_assest'+div_count).find("#product").select2(); // assuming the dropdown has ID sku_no_1
			
		$('#new_product_div_to_clone').hide();			
	});

	$("#form1").on("click", ".delete_new_assest_pro",function() {
	    if(confirm('Are you sure! You want to delete')){		
			if($(this).attr("alt") != ""){
				var na_mapping_id = $(this).attr("alt");
				$('#load_new_assest_pro'+na_mapping_id).show();
				var form_data   = {'na_mapping_id':na_mapping_id};       
				$.ajax({
					async: true,
					type: "POST",
					url: site_url+"/modules/product_group/index.php?page=ajax_actions&action=delete_product_mapping",
					data: form_data,
					success: function(result){    
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$('#status_update_done_pro'+na_mapping_id).show();
							$('#load_new_assest_pro'+na_mapping_id).hide();
							
							setTimeout(function() {
								$('#status_update_done_pro'+na_mapping_id).hide();
								$('#new_assest'+na_mapping_id).remove();
								//location.reload();
							},1000);
						}
					}
				});
			}else{
				$(this).parent().parent().parent().remove();
			}
		}
	});
	
});
</script>