<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view_product";
$form_action	= "insert";
$button_value 	= "Submit";
$table_name 	= "product_main";
$id	 = "";
$vat = "";
$query_string = "";
$page_name      = "Add Item";
$organisation_date = date("d-m-Y");
$from = $_REQUEST['from'];
$product_template_id 	= isset($_REQUEST['pro_temp_id']) ? $_REQUEST['pro_temp_id'] : "";
################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string","admin_id","new_fields","attribute_name","attribute_id"));    
    
    $product_template_id 					= $_REQUEST['product_template_id']; 
    $name 									= $_REQUEST['name']; 
    $part_number 							= $_REQUEST['part_number'];
    $g_number 							= $_REQUEST['g_number'];
	$part_number_revision 					= $_REQUEST['part_number_revision'];
	$part_number_category 					= $_REQUEST['part_number_category'];
	$stock_part 							= $_REQUEST['stock_part'];
	$current_product_range					= $_REQUEST['current_product_range'];
	$is_taxable 							= $_REQUEST['is_taxable'];
	$sales_item_code 						= $_REQUEST['sales_item_code'];
	$sales_price 							= $_REQUEST['sales_price'];
	$product_group							= $_REQUEST['product_group'];
	$product_group_short_code 				= $_REQUEST['product_group_short_code'];
	$description_external 					= $_REQUEST['description_external'];
	$description_internal 					= $_REQUEST['description_internal'];
	$currency								= $_REQUEST['currency'];
	$part_checked 							= $_REQUEST['part_checked'];
	$part_checked_date 						= utility::setFormatedDate($_REQUEST['part_checked_date']);
	$part_requires_attention 				= $_REQUEST['part_requires_attention'];
	$part_attention_notes 					= $_REQUEST['part_attention_notes'];
	$components_costs 						= $_REQUEST['components_costs'];
	$costing_method 						= $_REQUEST['costing_method'];
	$labour_hours 							= $_REQUEST['labour_hours'];
	$labour_hours_total_parts 				= $_REQUEST['labour_hours_total_parts'];
	$total_cost 							= $_REQUEST['total_cost'];
	$bill_of_materials 						= $_REQUEST['bill_of_materials'];
	$where_used 							= $_REQUEST['where_used'];
	$qr_code 								= $_REQUEST['qr_code'];
	$barcode 								= $_REQUEST['barcode'];
	$image1									= $_REQUEST['image1'];
	$image2 								= $_REQUEST['image2'];
	$image3 								= $_REQUEST['image3']; 
	$is_active 								= $_REQUEST['is_active']; 
	
	$quantity 								= $_REQUEST['quantity']; 
	$unit 							     	= $_REQUEST['unit']; 
	
	$created_on								= date("Y-m-d H:i:s");	    
	$created_by 							=$_SESSION['admin_user_id'];
    
	$sql = "product_template_id = '".$product_template_id."',name = '".$name."',part_number = '".$part_number."',part_number_revision = '".$part_number_revision."',part_number_category = '".$part_number_category."',stock_part = '".$stock_part."',current_product_range = '".$current_product_range."',is_taxable = '".$is_taxable."',sales_item_code = '".$sales_item_code."',sales_price = '".$sales_price."',product_group = '".$product_group."',product_group_short_code = '".$product_group_short_code."', description_external = '".$description_external."',description_internal = '".$description_internal."',currency = '".$currency."',part_checked = '".$part_checked."',part_checked_date = '".$part_checked_date."',part_requires_attention = '".$part_requires_attention."',part_attention_notes = '".$part_attention_notes."',components_costs = '".$components_costs."',costing_method = '".$costing_method."',labour_hours = '".$labour_hours."',labour_hours_total_parts = '".$labour_hours_total_parts."',total_cost = '".$total_cost."',bill_of_materials = '".$bill_of_materials."',where_used = '".$where_used."',barcode = '".$barcode."',is_active = '".$is_active."', quantity = '".$quantity."',unit = '".$unit."', created_on = '".$created_on."',  created_by = '".$created_by."'";
  
  
  
	if(trim($_FILES['image1']['name'])!=""){
			$target_dir="../product_images/";
			$target_file=$target_dir . basename($_FILES["image1"]["name"]);
			$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));    
			if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
			  $_SESSION['info_message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
			}else{
				$fname=pathinfo($_FILES["image1"]["name"]);
				$tmpfilename=$fname["filename"];
				$target_file=$target_dir.$tmpfilename.".".$imageFileType;
				$i=1;
				while (file_exists($target_file)) {
					$target_file=$target_dir.$tmpfilename."_".$i.".".$imageFileType;
					$i=$i+1;
				}
				if (move_uploaded_file($_FILES["image1"]["tmp_name"], $target_file)) {
					if($i==1){
						$target_file=$tmpfilename.".".$imageFileType;
					}else{
						$target_file=$tmpfilename."_".$i.".".$imageFileType;    
					}
					$sql=$sql.",image1='".$target_file."'";
					
				}    



			}
		}
		/*  Image 2 insert */
		if(trim($_FILES['image2']['name'])!=""){
			$target_dir="../product_images/";
			$target_file=$target_dir . basename($_FILES["image2"]["name"]);
			$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));    
			if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
			  $_SESSION['info_message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
			}else{
				$fname=pathinfo($_FILES["image2"]["name"]);
				$tmpfilename=$fname["filename"];
				$target_file=$target_dir.$tmpfilename.".".$imageFileType;
				$i=1;
				while (file_exists($target_file)) {
					$target_file=$target_dir.$tmpfilename."_".$i.".".$imageFileType;
					$i=$i+1;
				}
				if (move_uploaded_file($_FILES["image2"]["tmp_name"], $target_file)) {
					if($i==1){
						$target_file=$tmpfilename.".".$imageFileType;
					}else{
						$target_file=$tmpfilename."_".$i.".".$imageFileType;    
					}
					$sql=$sql.",image2='".$target_file."'";
					
				}    



			}
		}
		/*  Image 3 insert */
		if(trim($_FILES['image3']['name'])!=""){
			$target_dir="../product_images/";
			$target_file=$target_dir . basename($_FILES["image3"]["name"]);
			$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));    
			if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
			  $_SESSION['info_message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
			}else{
				$fname=pathinfo($_FILES["image3"]["name"]);
				$tmpfilename=$fname["filename"];
				$target_file=$target_dir.$tmpfilename.".".$imageFileType;
				$i=1;
				while (file_exists($target_file)) {
					$target_file=$target_dir.$tmpfilename."_".$i.".".$imageFileType;
					$i=$i+1;
				}
				if (move_uploaded_file($_FILES["image3"]["tmp_name"], $target_file)) {
					if($i==1){
						$target_file=$tmpfilename.".".$imageFileType;
					}else{
						$target_file=$tmpfilename."_".$i.".".$imageFileType;    
					}
					$sql=$sql.",image3='".$target_file."'";
					
				}    



			}
		}
		/*  qr_code  insert */
		if(trim($_FILES['qr_code']['name'])!=""){
			$target_dir="../product_images/";
			$target_file=$target_dir . basename($_FILES["qr_code"]["name"]);
			$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));    
			if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
			  $_SESSION['info_message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
			}else{
				$fname=pathinfo($_FILES["qr_code"]["name"]);
				$tmpfilename=$fname["filename"];
				$target_file=$target_dir.$tmpfilename.".".$imageFileType;
				$i=1;
				while (file_exists($target_file)) {
					$target_file=$target_dir.$tmpfilename."_".$i.".".$imageFileType;
					$i=$i+1;
				}
				if (move_uploaded_file($_FILES["qr_code"]["tmp_name"], $target_file)) {
					if($i==1){
						$target_file=$tmpfilename.".".$imageFileType;
					}else{
						$target_file=$tmpfilename."_".$i.".".$imageFileType;    
					}
					$sql=$sql.",qr_code='".$target_file."'";
					
				}    



			}
		}
	$sql=utility::convert_to_crypt_data($sql,$table_name);
	$sql= "INSERT INTO $table_name SET ".$sql;
    mysqli_query($conn,$sql);
	$product_id = mysqli_insert_id($conn);
	
	if($part_number !=''){
		$sql="insert into product_name set pro_id='".$product_id."',group_name='".$part_number."',group_number='".$part_number."',group_code='".$g_number."'";
		mysqli_query($conn,$sql);
		$group_id=mysqli_insert_id($conn);
	}
	mysqli_query($conn,"UPDATE product_main SET part_number_id = '$group_id' WHERE id = '$product_id' ");
	
	 foreach ($_POST['attribute_id'] as $key => $attribute_id) {
        $attribute_value = $_POST['attribute_name'][$key];
        $sql = "INSERT INTO product_attributes_value (product_id, pro_template_id,pro_attr_id, pro_attr_value,created_by,created_on)
                VALUES ('$product_id', '$product_template_id', '$attribute_id', '$attribute_value','$created_by','$created_on')";
        mysqli_query($conn, $sql);
    } 

	header('Location: index?page=view_product&pro_temp_id=' .$product_template_id);
    $_SESSION['info_message'] = "Item added sucessfully";
	exit;
	
}

################################################# END INSERT #################################################
$is_active =1;
$currency =1;
$quantity =1;
################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id 				= $_REQUEST['id'];
	
	$readonly 	= "readonly";
	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit Item";
	$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);
	$row_edit = utility::validate_crypt_data($row_edit);
	
    $product_template_id 					= $row_edit['product_template_id']; 
    $name 									= $row_edit['name']; 
    $part_number 							= $row_edit['part_number'];
	$part_number1 							= $gsi->getProductGroupById($part_number);
	$part_number_revision 					= $row_edit['part_number_revision'];
	$part_number_category 					= $row_edit['part_number_category'];
	$stock_part 							= $row_edit['stock_part'];
	$current_product_range					= $row_edit['current_product_range'];
	$is_taxable 							= $row_edit['is_taxable'];
	$sales_item_code 						= $row_edit['sales_item_code'];
	$sales_price 							= $row_edit['sales_price'];
	$product_group							= $row_edit['product_group'];
	$product_group_short_code 				= $row_edit['product_group_short_code'];
	$description_external 					= $row_edit['description_external'];
	$description_internal 					= $row_edit['description_internal'];
	$currency								= $row_edit['currency'];
	$part_checked 							= $row_edit['part_checked'];
	$part_checked_date 						= $row_edit['part_checked_date'];
	$part_requires_attention 				= $row_edit['part_requires_attention'];
	$part_attention_notes 					= $row_edit['part_attention_notes'];
	$components_costs 						= $row_edit['components_costs'];
	$costing_method 						= $row_edit['costing_method'];
	$labour_hours 							= $row_edit['labour_hours'];
	$labour_hours_total_parts 				= $row_edit['labour_hours_total_parts'];
	$total_cost 							= $row_edit['total_cost'];
	$bill_of_materials 						= $row_edit['bill_of_materials'];
	$where_used 							= $row_edit['where_used'];
	$qr_code 								= $row_edit['qr_code'];
	$barcode 								= $row_edit['barcode'];
	$image1									= $row_edit['image1'];
	$image2 								= $row_edit['image2'];
	$image3 								= $row_edit['image3']; 
	$is_active 								= $row_edit['is_active']; 
	$quantity 								= $row_edit['quantity']; 
	$unit 									= $row_edit['unit']; 
   
}
################################################# END EDIT ################################################# 

 if($part_checked==1){
    $part_check_hide="block";
	$part_attention_hide ="none";
}else if($part_checked==2){
   $part_attention_hide ="block";
    $part_check_hide="none";
}else{
	$part_attention_hide ="none";
    $part_check_hide="none";
}
################################################## START UPDATE ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
    utility::addslashesOnAllInput(array("query_string","parent_product_groups","new_fields","attribute_name","attribute_id"));
    
    $id          							= $_REQUEST['id'];
    $product_template_id 					= $_REQUEST['product_template_id']; 
    $name 									= $_REQUEST['name']; 
    $g_number 								= $_REQUEST['g_number'];
    $g_id 									= $_REQUEST['g_id'];
	$part_number_revision 					= $_REQUEST['part_number_revision'];
	$part_number_category 					= $_REQUEST['part_number_category'];
	$stock_part 							= $_REQUEST['stock_part'];
	$current_product_range					= $_REQUEST['current_product_range'];
	$is_taxable 							= $_REQUEST['is_taxable'];
	$sales_item_code 						= $_REQUEST['sales_item_code'];
	$sales_price 							= $_REQUEST['sales_price'];
	$product_group							= $_REQUEST['product_group'];
	$product_group_short_code 				= $_REQUEST['product_group_short_code'];
	$description_external 					= $_REQUEST['description_external'];
	$description_internal 					= $_REQUEST['description_internal'];
	$currency								= $_REQUEST['currency'];
	$part_checked 							= $_REQUEST['part_checked'];
	$part_checked_date 						= utility::setFormatedDate($_REQUEST['part_checked_date']);
	$part_requires_attention 				= $_REQUEST['part_requires_attention'];
	$part_attention_notes 					= $_REQUEST['part_attention_notes'];
	$components_costs 						= $_REQUEST['components_costs'];
	$costing_method 						= $_REQUEST['costing_method'];
	$labour_hours 							= $_REQUEST['labour_hours'];
	$labour_hours_total_parts 				= $_REQUEST['labour_hours_total_parts'];
	$total_cost 							= $_REQUEST['total_cost'];
	$bill_of_materials 						= $_REQUEST['bill_of_materials'];
	$where_used 							= $_REQUEST['where_used'];
	$qr_code 								= $_REQUEST['qr_code'];
	$barcode 								= $_REQUEST['barcode'];
	$image1									= $_REQUEST['image1'];
	$image2 								= $_REQUEST['image2'];
	$image3 								= $_REQUEST['image3'];   
    $is_active        						= $_REQUEST['is_active'];  
    $quantity        						= $_REQUEST['quantity'];  
    $unit        							= $_REQUEST['unit'];  
	
	$created_on								= date("Y-m-d H:i:s");	
	$created_by								= $_SESSION['user_id'];
	$updated_by								= $_SESSION['user_id'];
	
	$sql = "product_template_id = '".$product_template_id."',name = '".$name."',part_number_revision = '".$part_number_revision."',part_number_category = '".$part_number_category."',stock_part = '".$stock_part."',current_product_range = '".$current_product_range."',is_taxable = '".$is_taxable."',sales_item_code = '".$sales_item_code."',sales_price = '".$sales_price."',product_group = '".$product_group."',product_group_short_code = '".$product_group_short_code."',  description_external = '".$description_external."',description_internal = '".$description_internal."',currency = '".$currency."',part_checked = '".$part_checked."',part_checked_date = '".$part_checked_date."',part_requires_attention = '".$part_requires_attention."',part_attention_notes = '".$part_attention_notes."',components_costs = '".$components_costs."',costing_method = '".$costing_method."',labour_hours = '".$labour_hours."',labour_hours_total_parts = '".$labour_hours_total_parts."',total_cost = '".$total_cost."',bill_of_materials = '".$bill_of_materials."',where_used = '".$where_used."',barcode = '".$barcode."',is_active = '".$is_active."',quantity = '".$quantity."',unit = '".$unit."', updated_by = '".$updated_by."'";
  
   if($current_product_range ==1){
      $sql_g = "SELECT child_id FROM product_link WHERE parent_id = '".$g_id."'";
		$result = mysqli_query($conn, $sql_g);
		if (mysqli_num_rows($result) > 0) {
					while ($row = mysqli_fetch_assoc($result)) {
						  $sql_u = "UPDATE  product_name set group_code= '$g_number' where id = '".$row['child_id']."'";
						   mysqli_query($conn, $sql_u);
					}
		}
   }	
		
	if(trim($_FILES['image1']['name'])!=""){

        $target_dir="../product_images/";    

        if(trim($_REQUEST["hid_prd_image"])!=""){
			$tmpfilename=$_REQUEST["hid_prd_image"];    
			$target_file=$target_dir.$tmpfilename;
			unlink($target_file);
			if (move_uploaded_file($_FILES["image1"]["tmp_name"], $target_file)) {
				$sql=$sql.",image1='".$tmpfilename."'";
            } 
        }else{
			$target_file=$target_dir . basename($_FILES["image1"]["name"]);
            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));    
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
              $_SESSION['info_message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            }else{
                $fname=pathinfo($_FILES["image1"]["name"]);
                $tmpfilename=$fname["filename"];
                $target_file=$target_dir.$tmpfilename.".".$imageFileType;
                $i=1;
				while (file_exists($target_file)) {
					$target_file=$target_dir.$tmpfilename."_".$i.".".$imageFileType;
					$i=$i+1;
				}
				if (move_uploaded_file($_FILES["image1"]["tmp_name"], $target_file)) {
				    if($i==1){
						$target_file=$tmpfilename.".".$imageFileType;
					}else{
						$target_file=$tmpfilename."_".$i.".".$imageFileType;    
					}
					$sql=$sql.",image1='".$target_file."'";
				} 
            } 
        }

    }
	if(trim($_FILES['image2']['name'])!=""){

        $target_dir="../product_images/";    

        if(trim($_REQUEST["hid_prd_image_2"])!=""){
			$tmpfilename=$_REQUEST["hid_prd_image_2"];    
			$target_file=$target_dir.$tmpfilename;
			unlink($target_file);
			if (move_uploaded_file($_FILES["image2"]["tmp_name"], $target_file)) {
				$sql=$sql.",image2='".$tmpfilename."'";
            } 
        }else{
			$target_file=$target_dir . basename($_FILES["image2"]["name"]);
            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));    
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
              $_SESSION['info_message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            }else{
                $fname=pathinfo($_FILES["image2"]["name"]);
                $tmpfilename=$fname["filename"];
                $target_file=$target_dir.$tmpfilename.".".$imageFileType;
                $i=1;
				while (file_exists($target_file)) {
					$target_file=$target_dir.$tmpfilename."_".$i.".".$imageFileType;
					$i=$i+1;
				}
				if (move_uploaded_file($_FILES["image2"]["tmp_name"], $target_file)) {
				    if($i==1){
						$target_file=$tmpfilename.".".$imageFileType;
					}else{
						$target_file=$tmpfilename."_".$i.".".$imageFileType;    
					}
					$sql=$sql.",image2='".$target_file."'";
				} 
            } 
        }

    }
	if(trim($_FILES['image3']['name'])!=""){

        $target_dir="../product_images/";    

        if(trim($_REQUEST["hid_prd_image_3"])!=""){
			$tmpfilename=$_REQUEST["hid_prd_image_3"];    
			$target_file=$target_dir.$tmpfilename;
			unlink($target_file);
			if (move_uploaded_file($_FILES["image3"]["tmp_name"], $target_file)) {
				$sql=$sql.",image3='".$tmpfilename."'";
            } 
        }else{
			$target_file=$target_dir . basename($_FILES["image3"]["name"]);
            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));    
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
              $_SESSION['info_message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            }else{
                $fname=pathinfo($_FILES["image3"]["name"]);
                $tmpfilename=$fname["filename"];
                $target_file=$target_dir.$tmpfilename.".".$imageFileType;
                $i=1;
				while (file_exists($target_file)) {
					$target_file=$target_dir.$tmpfilename."_".$i.".".$imageFileType;
					$i=$i+1;
				}
				if (move_uploaded_file($_FILES["image3"]["tmp_name"], $target_file)) {
				    if($i==1){
						$target_file=$tmpfilename.".".$imageFileType;
					}else{
						$target_file=$tmpfilename."_".$i.".".$imageFileType;    
					}
					$sql=$sql.",image3='".$target_file."'";
				} 
            } 
        }

    }
	
	if(trim($_FILES['qr_code']['name'])!=""){

        $target_dir="../product_images/";    

        if(trim($_REQUEST["hid_prd_image_4"])!=""){
			$tmpfilename=$_REQUEST["hid_prd_image_4"];    
			$target_file=$target_dir.$tmpfilename;
			unlink($target_file);
			if (move_uploaded_file($_FILES["qr_code"]["tmp_name"], $target_file)) {
				$sql=$sql.",qr_code='".$tmpfilename."'";
            } 
        }else{
			$target_file=$target_dir . basename($_FILES["qr_code"]["name"]);
            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));    
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
              $_SESSION['info_message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            }else{
                $fname=pathinfo($_FILES["qr_code"]["name"]);
                $tmpfilename=$fname["filename"];
                $target_file=$target_dir.$tmpfilename.".".$imageFileType;
                $i=1;
				while (file_exists($target_file)) {
					$target_file=$target_dir.$tmpfilename."_".$i.".".$imageFileType;
					$i=$i+1;
				}
				if (move_uploaded_file($_FILES["qr_code"]["tmp_name"], $target_file)) {
				    if($i==1){
						$target_file=$tmpfilename.".".$imageFileType;
					}else{
						$target_file=$tmpfilename."_".$i.".".$imageFileType;    
					}
					$sql=$sql.",qr_code='".$target_file."'";
				} 
            } 
        }

    }
	
		 foreach ($_POST['attribute_id'] as $key => $attribute_id) {
			$attribute_value = $_POST['attribute_name'][$key];
			$check_sql = "SELECT * FROM product_attributes_value WHERE product_id = '$id' AND pro_template_id = '$product_template_id' AND pro_attr_id = '$attribute_id'";
			$check_result = mysqli_query($conn, $check_sql);
			if (mysqli_num_rows($check_result) > 0) {
				$update_sql = "UPDATE product_attributes_value SET pro_attr_value = '$attribute_value', updated_by = '$updated_by' WHERE product_id = '$id' AND pro_template_id = '$product_template_id' AND pro_attr_id = '$attribute_id'";
				mysqli_query($conn, $update_sql);
			} else {
				$insert_sql = "INSERT INTO product_attributes_value (product_id, pro_template_id, pro_attr_id, pro_attr_value)
							   VALUES ('$id', '$product_template_id', '$attribute_id', '$attribute_value')";
				mysqli_query($conn, $insert_sql);
			}
		}

	
	$sql=utility::convert_to_crypt_data($sql,$table_name);
	$sql= "UPDATE $table_name SET ".$sql." WHERE id = '".$id."'";
    mysqli_query($conn,$sql);
	
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	//$query_string = str_ireplace("page=add_productgg", "page=view_productggg", $query_string);
	$query_string = "&".$query_string;
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	
	$_SESSION['info_message'] = "Item updated sucessfully";
    header("Location: $file_name$query_string");
	exit;
}

################################################# Image Remove ################################################# 

if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_img'){
	$id				 = $_REQUEST['id'];
	$pro_temp_id	 = $_REQUEST['pro_temp_id'];
	$idd 			 = utility::app_crypt($_REQUEST['id'],'e');
	$doc_name 		 = utility::getTableFieldById("product_main","image1","id",$id);
	$dir			 = "../product_images/";
	if(file_exists($dir.$doc_name)){ 
		unlink($dir.$doc_name);
	}
	mysqli_query($conn,"UPDATE product_main SET image1 = '' WHERE id = '".$_REQUEST['id']."' ");
	$_SESSION['info_message'] = "Picture Removed sucessfully";
	header("Location: index?page=add_product&action=edit&id=".$id.'&pro_temp_id='.$pro_temp_id);
    exit();
}
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_img2'){
	$id				 = $_REQUEST['id'];
	$pro_temp_id	 = $_REQUEST['pro_temp_id'];
	$idd 			 = utility::app_crypt($_REQUEST['id'],'e');
	$doc_name 		 = utility::getTableFieldById("product_main","image2","id",$id);
	$dir			 = "../product_images/";
	if(file_exists($dir.$doc_name)){ 
		unlink($dir.$doc_name);
	}
	mysqli_query($conn,"UPDATE product_main SET image2 = '' WHERE id = '".$_REQUEST['id']."' ");
	$_SESSION['info_message'] = "Picture Removed sucessfully";
	header("Location: index?page=add_product&action=edit&id=".$id.'&pro_temp_id='.$pro_temp_id);
    exit();
}
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_img3'){
	$id				 = $_REQUEST['id'];
	$pro_temp_id	 = $_REQUEST['pro_temp_id'];
	$idd 			 = utility::app_crypt($_REQUEST['id'],'e');
	$doc_name 		 = utility::getTableFieldById("product_main","image3","id",$id);
	$dir			 = "../product_images/";
	if(file_exists($dir.$doc_name)){ 
		unlink($dir.$doc_name);
	}
	mysqli_query($conn,"UPDATE product_main SET image3 = '' WHERE id = '".$_REQUEST['id']."' ");
	$_SESSION['info_message'] = "Picture Removed sucessfully";
	header("Location: index?page=add_product&action=edit&id=".$id.'&pro_temp_id='.$pro_temp_id);
    exit();
}
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_img4'){
	$id				 = $_REQUEST['id'];
	$pro_temp_id	 = $_REQUEST['pro_temp_id'];
	$idd 			 = utility::app_crypt($_REQUEST['id'],'e');
	$doc_name 		 = utility::getTableFieldById("product_main","qr_code","id",$id);
	$dir			 = "../product_images/";
	if(file_exists($dir.$doc_name)){ 
		unlink($dir.$doc_name);
	}
	mysqli_query($conn,"UPDATE product_main SET qr_code = '' WHERE id = '".$_REQUEST['id']."' ");
	$_SESSION['info_message'] = "Picture Removed sucessfully";
	header("Location: index?page=add_product&action=edit&id=".$id.'&pro_temp_id='.$pro_temp_id);
    exit();
}

################################################# END UPDATE ################################################# 

	$fetch_attr = "SELECT * FROM product_attributes WHERE pro_template_id ='".$_REQUEST['pro_temp_id']."' ORDER BY id";		   
	$sql_attr=mysqli_query($conn,$fetch_attr);
	$result_attr=mysqli_num_rows($sql_attr);
	
    $sql= "SELECT * FROM product_template WHERE id = '".$_REQUEST['pro_temp_id']."'";
    $result_temp = mysqli_query($conn,$sql);
    $row_temp = mysqli_fetch_array($result_temp);
	$row_ = utility::validate_crypt_data($row_temp);
	
?>
<style>
em {
    color: red;
    font-size: 20px;
    position: absolute;
}
</style>
<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'];
			if(isset($from) && $from == "view_product_details"){
				$query_string = str_ireplace("page=add_product", "page=view_product_details", $query_string);
			}else {
				$query_string = str_ireplace("page=add_product", "page=view_product", $query_string);
			}
				
			?>
                <button type="button" id="back" name="back" value="back"
                    style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-success"
                    onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
            </div>
        </div>
    </div>
</section>
<section class="content">
<div class="row">
	<div class="col-12">
			      <?php if(isset($_SESSION['info_message'])) { ?>
						<script>
							$(document).ready(function(){
								Toastify({
									text: "<?php echo $_SESSION['info_message']; ?>",duration: 3000,close: true,gravity: "top",position: 'right',backgroundColor: "#3498DB",style: {borderBottom: "3px solid white",},
								}).showToast();
								<?php unset($_SESSION['info_message']); ?>
							});
						</script>
					<?}?>
		<!----------------------- End Message ------------------------------->
		<!-- general form elements -->
		<div class="card">
			<form class="" method="post" name="form1" id="form1"
				action="index?page=add_product&action=<? echo $form_action; ?>" onsubmit="return validateForm(this)"
				enctype="multipart/form-data">
				<div class="card-body">
					<div class="row">
						   <div class="col-lg-12 col-sm-12">
								<div class="form-group">
									<label for="bay_name" class="control-label">Item Template Name <em>*</em></label>
									<div class="">
										<? echo $gsi->getProductTempateList("product_template_id",$product_template_id,"100%",false,"form-control select2","required"); ?>
									</div>
								</div>
							</div>
							 <?php if ($row_['part_number_category'] == 1){ ?>
							<div class="col-lg-6">
								<div class="row"> 
								 <div class="col-sm-4 form-group"> 
									<label class="control-label" for="Country">Part Number Category </label> 
									<div> 
										<? $gsi->getCategoryList("part_number_category",$part_number_category,"100%",false,"form-control select2"); ?>
									</div>
									<i class="fas fa-sync-alt fa-spin" id="zone_checking1" style="font-size: 10px; display:none;"></i>
								 </div>
								 <div class="col-sm-4 form-group"> 
									<label class="control-label">Part Number</label>
									<div> 
										<input type="text" class="form-control" id="part_number" name="part_number" value="<?=$part_number1; ?>"  placeholder="Part Number" required <?=$readonly;?>>
									</div> 
								 </div>
								 <div class="col-sm-4 form-group"> 
									<label class="control-label">Group Code</label>
									<div> 
										<input type="text" class="form-control" id="g_number" name="g_number" value="<?= utility::getTableFieldById("product_name","group_code","id",$part_number);?>"  placeholder="Group Code" required <?=$readonly;?>>
										<input type="hidden" name="g_id" value="<?=$part_number;?>">
									</div> 
								 </div>
							  </div>
							</div>
						 <?php } ?>
						  <?php if ($row_['stock_part'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Stock Part</label>
									<? echo $gsi->getYesNo("stock_part",$stock_part,"100%",false,"form-control ","required"); ?>
								</div>
							</div>
						<?php }?>
							<div class="form-group col-lg-6">
								<label for="name" class=" control-label">Name<em>*</em></label>
								<div class="">
									<input type="text" id="name" name="name" value="<?php echo $name;?>" class="form-control" placeholder="Enter Name" required>
								</div>
							</div>
						 
						<? if ($row_['part_number_revision'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Part Number Revision</label>
									<input type="text" class="form-control" id="part_number_revision" name="part_number_revision" value="<?= $part_number_revision; ?>" placeholder="Enter Part Number Revision">
								</div>
							</div>
						<?php }if ($row_['sales_price'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Sales Price</label>
									<input type="text" class="form-control" id="sales_price" name="sales_price" value="<?= $sales_price; ?>" placeholder="Enter Sales Price">
								</div>
							</div>
						<?php } if ($row_['costing_method'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Costing Method</label>
									<? echo Keycode::getKeycodeListValue("costing_method", $costing_method, $width = "100%", "Please Select", "id", "code", "costing_method","","form-control",false,""); ?>
								</div>
							</div>
						<?php } if ($row_['currency'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Currency</label>
									<?$gsi->getCurrencyList("currency",$currency,"100%",false,"form-control ");?>
								</div>
							</div>
						<?php }if ($row_['product_group'] == 1) { ?>
							    <div class="col-lg-6 hide">
								  <div class="row">
								  <div class="col-sm-5">
									<label class="control-label">Group Number</label> 
									   <?$gsi->getProductGroupList("product_group",$product_group,"100%",false,"form-control select2");?>
								 </div>
								 <div class="col-sm-3 form-group"> 
									<label class="control-label">Short Code</label>
									<input type="text" class="form-control" id="product_group_short_code" name="product_group_short_code" value="<?= $product_group_short_code; ?>" placeholder="Short Code" readonly>
								 </div>
								 <?if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){?>
								 <div class="col-sm-4 form-group text-center"> 
									<label class="control-label">Parent Group View</label><br>
								      <a href='#' data-toggle='modal' class="btn btn-success" data-target='#ShowModal' id="group_name" alt="<?=$product_group?>"><?= $gsi->getProductGroupById($product_group);?></a>
								 </div>
								 <?}else{?>
								   <div class="col-sm-4 form-group text-center"> 
									  <label class="control-label">Parent Group View</label><br>
								      <a href='#' data-toggle='modal' class="btn btn-success" data-target='#ShowModal' id="group_name"style="display:none"></a>
								   </div>
								 <?}?>
							  </div>
							</div>
						<?php }if ($row_['sales_item_code'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Sales Item Code</label>
									<input type="text" class="form-control" id="sales_item_code" name="sales_item_code" value="<?= $sales_item_code; ?>" placeholder="Enter Sales Item Code">
								</div>
							</div>
						<?php } if ($row_['labour_hours'] == 1) { ?>
							<div class="col-lg-6 hide">
								<div>
									<label class="control-label">Labour Hours <span id="total__labour_hours" class="text-success"></span></label>
									<input type="text" class="form-control" id="labour_hours" name="labour_hours" value="<?= $labour_hours; ?>" placeholder=" Labour Hours" readonly>
								</div>
							</div>
						<?php } if ($row_['is_taxable'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Is Taxable</label>
									<? echo Keycode::getKeycodeListValue("is_taxable", $is_taxable, $width = "100%", "Please Select", "id", "code", "tax_code","","form-control",false,""); ?>
								</div>
							</div>
						<?php } if ($row_['labour_hours_total_parts'] == 1) { ?>
							<div class="col-lg-6 hide">
								<div>
									<label class="control-label">Labour Cost <span id="total_labour_cost" class="text-success"></span></label>
									<input type="text" class="form-control" id="labour_hours_total_parts" name="labour_hours_total_parts" value="<?= $labour_hours_total_parts; ?>" placeholder="Enter Labour Total Cost" readonly>
								</div>
							</div>
						<?php }if ($row_['barcode'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Barcode</label>
									<input type="text" class="form-control" id="barcode" name="barcode" value="<?= $barcode; ?>" placeholder="Enter Barcode Value">
								</div>
							</div>
						<?php } if ($row_['components_costs'] == 1) { ?>
							<div class="col-lg-6 hide">
							 <div class="row"> 
								 <div class="col-lg-12"> 
									<label class="control-label">Components Costs <span id="total_com_cost" class="text-success"></span></label>
									<input type="text" class="form-control" id="components_costs" name="components_costs" value="<?= $components_costs; ?>" placeholder="Components Costs" readonly>
								 </div>
							  </div>
							  </div>
						<?php }if ($row_['description_external'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Description External</label>
									<textarea class="form-control" id="description_external" name="description_external" rows="2" placeholder="Enter Description External"><?php echo $description_external;?></textarea>
								</div>
							</div>
						<?php } if ($row_['total_cost'] == 1) { ?>
							<div class="col-lg-6 hide">
								<div>
									<label class="control-label">Total Cost <span id="total_costs" class="text-success"></label>
									<input type="text" class="form-control" id="total_cost" name="total_cost" value="<?= $total_cost; ?>" placeholder="Enter Total Cost" readonly>
								</div>
							</div>
						<?php } if ($row_['bill_of_materials'] == 1) { ?>
							<div class="col-lg-6 hide">
								<div>
									<label class="control-label">Bill of Materials</label>
									<? echo Keycode::getKeycodeListValue("bill_of_materials", $bill_of_materials, $width = "100%", "Please Select", "id", "code", "","","form-control",false,""); ?>
								</div>
							</div>
						<?php } if ($row_['where_used'] == 1) { ?>
							<div class="col-lg-6 hide">
								<div>
									<label class="control-label">Where Used</label>
									<? echo Keycode::getKeycodeListValue("where_used", $where_used, $width = "100%", "Please Select", "id", "code", "","","form-control",false,""); ?>
								</div>
							</div>
						<?php } if ($row_['description_internal'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Description Internal</label>
									<textarea class="form-control" id="description_internal" name="description_internal" rows="2" placeholder="Auto "><?php echo $description_internal;?></textarea>
								</div>
							</div>
						<?php } if ($row_['part_checked'] == 1) { ?>
							<div class="col-lg-6">
								<div>
									<label class="control-label">Part Checked</label>
									<?$gsi->getPartChecked("part_checked",$part_checked,"100%",false,"form-control ");?>
								</div>
							</div>
						<?php } if ($row_['qr_code'] == 1) { ?>
						 <div class="col-lg-6"> 
							 <div class="row"> 
							   <div class="col-lg-8"> 
							   <div class="form-group">
								<label class="control-label" for="First Name">QR Code</label>
								<div class="">
									<input type="file" class="form-control" id="qr_code" name="qr_code"
									onchange="ValidateSingleInput(this)">
									<input type="hidden" id="hid_prd_image_4" name="hid_prd_image_4"
									value="<?php echo $qr_code;?>" />
								</div>
							</div>
							</div>
							<div class="col-lg-4" style="display:<?=$qr_code_cond;?>"> 
							  <?php
								if(trim($_REQUEST["action"])=="add" || trim($_REQUEST["action"])==""){
								$qr_code="no-image.gif";?>
									<img src="../../product_images/<?php echo $qr_code;?>" id="product_image_preview_4"
									name="product_image_preview_4" width="60%;" style="margin-top:5px;">
								<?}else{
									if(trim($qr_code)==""){
									$qr_code="no-image.gif";?>
									<img src="../../product_images/<?php echo $qr_code;?>"
									id="product_image_preview_4" name="product_image_preview_4" width="60%;"
									style="margin-top:10px;">
								<? }else{?>
										<a href="../../product_images/<?php echo $qr_code;?>" target='blank'><img
										src="../../product_images/<?php echo $qr_code;?>"
										id="product_image_preview_4" name="product_image_preview_4" width="120px;"
										style="margin-top:10px;"></a>
									<?}
									}
								?>
								<?if(isset($_REQUEST['action']) && $_REQUEST['action']=='edit'){
									 if($qr_code =='no-image.gif'){
									 	echo "";
									}else{?>
											<a href="index?page=add_product&action=delete_img4&id=<?=$id;?>&pro_temp_id=<?=$_REQUEST['pro_temp_id'];?>"
											onclick=" javascript:return confirm('Are you sure! You want to Delete');"><i
											class="fa fa-fw fa-trash text-danger"></i> </a>
									<?}
								}?>
							  </div>
							 </div>
						 </div>
						 <?php } if ($row_['part_attention_notes'] == 1) { ?>
							<div class="col-lg-6" style="display:<?=$part_attention_hide;?>;" id="part_attention_notes_">
								<div>
									<label class="control-label">Part Attention Notes</label>
									<textarea class="form-control" id="part_attention_notes" name="part_attention_notes" rows="2" placeholder="Part Attention Notes"><?php echo $part_attention_notes;?></textarea>
								</div>
							</div>
						 <?php }if ($row_['part_checked_date'] == 1) { ?>
							<div class="col-lg-6" style="display:<?=$part_check_hide;?>;"id="part_checked_date_">
								<div>
									<label class="control-label">Part Checked Date</label>
									<input type="text" class="form-control datepicker" id="part_checked_date" name="part_checked_date" value="<?php (isset($part_checked_date) && $part_checked_date !="") ? utility::getFormatedDate($part_checked_date) : "";?>"placeholder="DD-MM-YYYY" autocomplete="off">
								</div>
							</div>
						<?}?>	
						 <div class="col-lg-12"> 
						 <div class="row"> 
						 <?php if ($row_['image1'] == 1) { ?>
						 <div class="col-lg-6">
							 <div class="row"> 
							   <div class="col-lg-8">
							   <div class="form-group">
								<label class="control-label" for="First Name">Image 1</label>
								<div class="">
									<input type="file" class="form-control" id="image1" name="image1"
									onchange="ValidateSingleInput(this)">
									<input type="hidden" id="hid_prd_image" name="hid_prd_image"
									value="<?php echo $image1;?>" />
								</div>
							   </div>
							   </div>
							<div class="col-lg-4" style="display:<?=$image1_cond;?>"> 
							  <?php
								if(trim($_REQUEST["action"])=="add" || trim($_REQUEST["action"])==""){
								$image1="no_image.png";?>
									<img src="../../product_images/<?php echo $image1;?>" id="product_image_preview"
									name="product_image_preview" alt="1"width="90%;" style="margin-top:5px;">
								<?}else{
								if(trim($image1)==""){
									$image1="no_image.png";?>
									<img src="../../product_images/<?php echo $image1;?>"
									id="product_image_preview" name="product_image_preview" width="150px;"
									style="margin-top:10px;">
								<? }else{?>
										<a href="../../product_images/<?php echo $image1;?>" target='blank'><img
										src="../../product_images/<?php echo $image1;?>"
										id="product_image_preview" name="product_image_preview" width="150px;"
										style="margin-top:10px;"></a>
									<?}
									}
								?>
							<?if(isset($_REQUEST['action']) && $_REQUEST['action']=='edit'){
								  if($image1 =='no_image.png'){
									  echo "";
								 }else{?>
										<a href="index?page=add_product&action=delete_img&id=<?=$id;?>&pro_temp_id=<?=$_REQUEST['pro_temp_id'];?>"
										onclick=" javascript:return confirm('Are you sure! You want to Delete');"><i
										class="fa fa-fw fa-trash text-danger"></i> </a>
									<?}
							  }?>
							</div>
							</div>
						  </div>
						 <?}?>
						<?php if ($row_['image2'] == 1) { ?>
						<div class="col-lg-6">  
							<div class="row"> 
							   <div class="col-lg-8">
							   <div class="form-group">
								<label class="control-label" for="First Name">Image 2</label>
								<div class="">
									<input type="file" class="form-control" id="image2" name="image2"
									onchange="ValidateSingleInput(this)">
									<input type="hidden" id="hid_prd_image_2" name="hid_prd_image_2"
									value="<?php echo $image2;?>" />
								</div>
							</div>
							</div>
							<div class="col-lg-4" style="display:<?=$image2_cond;?>"> 
							  <?php
								if(trim($_REQUEST["action"])=="add" || trim($_REQUEST["action"])==""){
								$image2="no_image.png";?>
									<img src="../../product_images/<?php echo $image2;?>" id="product_image_preview_2"
									name="product_image_preview_2" alt="1"width="90%;" style="margin-top:5px;">
								<?}else{
								if(trim($image2)==""){
									$image2="no_image.png";?>
									<img src="../../product_images/<?php echo $image2;?>"
									id="product_image_preview_2" name="product_image_preview_2" width="150px;"
									style="margin-top:10px;">
								<? }else{?>
										<a href="../../product_images/<?php echo $image2;?>" target='blank'><img
										src="../../product_images/<?php echo $image2;?>"
										id="product_image_preview_2" name="product_image_preview_2" width="150px;"
										style="margin-top:10px;"></a>
									<?}
									}
								?>
								<?if(isset($_REQUEST['action']) && $_REQUEST['action']=='edit'){
									  if($image2 =='no_image.png'){
											echo "";
										}else{?>
											<a href="index?page=add_product&action=delete_img2&id=<?=$id;?>&pro_temp_id=<?=$_REQUEST['pro_temp_id'];?>"
											onclick=" javascript:return confirm('Are you sure! You want to Delete');"><i
											class="fa fa-fw fa-trash text-danger"></i> </a>
										<?}
								}?>
							  </div>
							 </div>
						 </div>
						<?}?>
						 <?php if ($row_['image3'] == 1) { ?>
						 <div class="col-lg-6"> 
							 <div class="row"> 
							   <div class="col-lg-8"> 
							   <div class="form-group">
								<label class="control-label" for="First Name">Image 3</label>
								<div class="">
									<input type="file" class="form-control" id="image3" name="image3"
									onchange="ValidateSingleInput(this)">
									<input type="hidden" id="hid_prd_image_3" name="hid_prd_image_3"
									value="<?php echo $image3;?>" />
								</div>
							</div>
							</div>
							<div class="col-lg-4" style="display:<?=$image3_cond;?>"> 
							  <?php
								if(trim($_REQUEST["action"])=="add" || trim($_REQUEST["action"])==""){
								$image3="no_image.png";?>
									<img src="../../product_images/<?php echo $image3;?>" id="product_image_preview_3"
									name="product_image_preview_3" alt="1"width="90%;" style="margin-top:5px;">
								<?}else{
								if(trim($image3)==""){
									$image3="no_image.png";?>
									<img src="../../product_images/<?php echo $image3;?>"
									id="product_image_preview_3" name="product_image_preview_3" width="150px;"
									style="margin-top:10px;">
								<? }else{?>
										<a href="../../product_images/<?php echo $image3;?>" target='blank'><img
										src="../../product_images/<?php echo $image3;?>"
										id="product_image_preview_3" name="product_image_preview_3" width="150px;"
										style="margin-top:10px;"></a>
									<?}
									}
								?>
								<?if(isset($_REQUEST['action']) && $_REQUEST['action']=='edit'){
									  if($image3 =='no_image.png'){
									  echo "";
								}else{?>
										<a href="index?page=add_product&action=delete_img3&id=<?=$id;?>&pro_temp_id=<?=$_REQUEST['pro_temp_id'];?>"
										onclick=" javascript:return confirm('Are you sure! You want to Delete');"><i
										class="fa fa-fw fa-trash text-danger"></i> </a>
									<?}
								}?>
							  </div>
							 </div>
						 </div>
						 <?}?>
						 </div>
						 </div>
						 
						 <?php if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
						    if ($row_['current_product_range'] == 1) { ?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="current_product_range" name="current_product_range" value="1" <?php echo ($current_product_range == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" >
									<label class="control-label">Current Item Range</label>
								</div>
							</div>
						 <?}}?>
						 <div class="col-lg-3 form-group ">
						   <input type="checkbox" id="is_active" name="is_active" class="" value="1" <?php echo ($is_active==1) ? 'checked' :''; ?> style="height: 17px; width: 17px;"> 
							 <label for="control-label">Is Active </label>
						 </div>
						 
					</div>
					
				   <?php
					$fetch_attr = "SELECT * FROM product_attributes WHERE pro_template_id ='".$_REQUEST['pro_temp_id']."' ORDER BY id";		   
					$sql_attr = mysqli_query($conn, $fetch_attr);
					$result_attr = mysqli_num_rows($sql_attr);

					if($result_attr > 0) {
						?>
						<div class="text-center col-lg-12">
							<strong class="h5">Item Template Attributes</strong>
							<hr style="background-color:#fa4a14; height:0.9px;">
						</div>
						<div class="row">
							<?php while($row = mysqli_fetch_array($sql_attr)) { 
								$row = utility::validate_crypt_data($row);
								$product_id = $row_edit['id']; 
								$attribute_id = $row['id'];
								$fetch_attr_value = "SELECT pro_attr_value FROM product_attributes_value WHERE product_id = '$product_id' AND pro_attr_id = '$attribute_id'";
								$sql_attr_value = mysqli_query($conn, $fetch_attr_value);
								$row_attr_value = mysqli_fetch_assoc($sql_attr_value);
								$existing_value = isset($row_attr_value['pro_attr_value']) ? $row_attr_value['pro_attr_value'] : '';

								?>
								<div class="col-lg-6">
									<label class="control-label"><?= ucwords($row['attribute_name']); ?>:</label>
									<?php if ($row['data_type'] == 'INTEGER') { ?>
										<input type="text" class="form-control only_num" name="attribute_name[]" value="<?= $existing_value ?>" placeholder="<?= ucwords($row['attribute_name']); ?>">
										<input type="hidden" name="attribute_id[]" value="<?= $row['id']; ?>">
									<?php } else if ($row['data_type'] == 'TEXT') { ?>
										<textarea class="form-control" name="attribute_name[]" rows="3" placeholder="<?= ucwords($row['attribute_name']); ?>"><?= $existing_value ?></textarea>
										<input type="hidden" name="attribute_id[]" value="<?= $row['id']; ?>">
									<?php } else if ($row['data_type'] == 'DATETIME') { ?>
										<input type="text" class="form-control datepicker" id="attribute_name" name="attribute_name[]" value="<?= $existing_value ?>" placeholder="DD-MM-YYYY" autocomplete="off">
										<input type="hidden" name="attribute_id[]" value="<?= $row['id']; ?>">
									<?php } else { ?>
										<input type="text" class="form-control" name="attribute_name[]" value="<?= $existing_value ?>" placeholder="<?= ucwords($row['attribute_name']); ?>">
										<input type="hidden" name="attribute_id[]" value="<?= $row['id']; ?>">
									<?php } ?>
								</div>
							<?php } ?>
						</div>
					<?php } ?>

				  </div>
					<div class="card-footer">
						<input type="hidden" id="id" name="id" value="<?php echo $id;?>">
						<input type="hidden" id="from" name="from" value="<?php echo $from;?>">
						<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"><?php echo $button_value;?>
							<i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
						</button>
					</div>
			</form>
		</div><!-- /.box -->
	</div>
</div>
<div class="modal fade" id="ShowModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable" role="document" style="width:75%; max-width:80%">
	<div class="modal-content">
	  <div class="modal-header">
		<h5 class="modal-title" id="exampleModalScrollableTitle" style="float:left">Group Tree</h5>
		<button type="button" class="close" data-dismiss="modal" aria-label="Close">
		  <span aria-hidden="true">&times;</span>
		</button>
	  </div>
	  <div class="modal-body">
		<!--<h5 class="modal-title" id="exampleModalScrollableTitle">Q->Quantity, C->Cost, LC->Labour Cost, TC->Total Cost, TLC->Total Labour Cost</h5>-->
		<div id="group_tree" style="">
		</div>
	  </div>
	  <div class="modal-footer">
		<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
		
	  </div>
	</div>
  </div>
</div>
</section>
<script>
$(document).ready(function () {
	
    $('#ShowModal').on('show.bs.modal', function (e) {
	  create_group_tree(e.relatedTarget.attributes.alt.value);
   })
	   
	function create_group_tree(id){
		$.ajax({ 
			url: site_url+"/modules/product_group/index.php?page=ajax_actions&action=get_group_list&id="+id,
			method:"POST",
			dataType: "json",       
			success: function(data)  
			{
				$('#group_tree').treeview({
					data: data,
					levels: 1,
					collapseIcon: "fa fa-angle-down",
					expandIcon: "fa fa-angle-right",
					nodeIcon: "fa fa-share-alt-square",
					backColor: 'white',
					showBorder: false,
					enableLinks: true,
					preventUnselect: true,
					selectedBackColor: 'lightgray',
					showTags: true,
					color:'black'
				});
			},
			error :function(jqXHR, textStatus, errorThrown)
			{
				alert("something went wrong");
			}   
		});
	}
	    
	function create_group_tree(id){
		$.ajax({ 
			url: site_url+"/modules/product_group/index.php?page=ajax_actions&action=get_group_list&id="+id,
			method:"POST",
			dataType: "json",       
			success: function(data)  
			{
				$('#group_tree').treeview({
					data: data,
					levels: 1,
					collapseIcon: "fa fa-angle-down",
					expandIcon: "fa fa-angle-right",
					nodeIcon: "fa fa-share-alt-square",
					backColor: 'white',
					showBorder: false,
					enableLinks: true,
					preventUnselect: true,
					selectedBackColor: 'lightgray',
					showTags: true,
					color:'black'
				});
			},
			error :function(jqXHR, textStatus, errorThrown)
			{
				alert("something went wrong");
			}   
		});
	}
  $('#form1').submit(function(event) {
			$('#product_template_id').prop('disabled', false);
			$("#submit").attr("disabled", true);
			$('#page_load_div').show();
			$('#form1').submit();
	});
	$('#product_template_id').prop('disabled', true);
	
	$('#description_external').on('input', function() {
		var externalText = $(this).val();
		$('#description_internal').val(externalText);
	});
		
	 function readURL(input, previewID) {
		if (input.files && input.files[0]) {
			var reader = new FileReader();
			reader.onload = function(e) {
				$('#' + previewID).attr('src', e.target.result);
			}
			reader.readAsDataURL(input.files[0]);
		}
	}

	$("#image1").change(function() {
		readURL(this, 'product_image_preview');
	});

	$("#image2").change(function() {
		readURL(this, 'product_image_preview_2');
	});
    $("#image3").change(function() {
		readURL(this, 'product_image_preview_3');
	});
	$("#qr_code").change(function() {
		readURL(this, 'product_image_preview_4');
	});

	$(document).on('select2:open', () => {
		document.querySelector('.select2-search__field').focus();
	 });
	
	
	$('input.only_num').on('input', function() {
		var inputValue = $(this).val();
		// Regular expression to allow integers and decimals
		var numberPattern = /^\d*\.?\d*$/;

		if (!numberPattern.test(inputValue)) {
			// Remove non-numeric and non-decimal characters from the input
			$(this).val(inputValue.replace(/[^\d.]/g, ''));
		}
	});
	
	
/////////////// fetch Category  //////////////
	$("#form1").on("change","#part_number_category",function(){
		var part_num_category_id = $(this).val();
		if(part_num_category_id != ""){
		$('#zone_checking').show();
		//alert(part_number_category);
		var form_data   = {'part_num_category_id':part_num_category_id};       
			////////////////////// For fetching address /////////////////////////
			$.ajax({
				async: true,
				type: "POST",
				url: site_url+"/modules/daynmic_product_management/index.php?page=ajax_actions&action=get_part_num_category_zone",
				data: form_data,
				success: function(result){  
					var resultObj = jQuery.parseJSON(result); 
					if(resultObj.status == 1){
						$('#zone_checking').hide();
						$("#part_number").val(resultObj.part_num_internal);
					}
				}
			});
			////////////////////// End For fetching part_num_internal  /////////////////////////
		}else{
			$("#part_number").val('');
		}
	});
	$("#product_group").change(function() {
		  var product_group = $(this).val();
		//  alert(product_group);
       if (product_group !== "") {
			var form_data = { 'product_group': product_group };

			$.ajax({
				type: "POST",
				 url: site_url+"/modules/daynmic_product_management/index.php?page=ajax_actions&action=get_product_grp_cost",
				data: form_data,
				success: function (result) {
					var resultObj = jQuery.parseJSON(result);
					if (resultObj.status == 1) {
						$("#group_name").show();
						$("#components_costs").val(resultObj.total_com_cost);
						$("#labour_hours_total_parts").val(resultObj.total_labour_cost);
						$("#total_cost").val(resultObj.total_cost);
						$("#product_group_short_code").val(resultObj.short_code);
						$("#labour_hours").val(resultObj.labour_hours);
						$("#group_name").text(resultObj.group_name);
						$("#group_name").attr("alt", resultObj.id);
						
					}
				}
			});
		}else{
			$("#group_name").hide();
			$("#components_costs").val('');
			$("#labour_hours_total_parts").val('');
			$("#total_cost").val('');
			$("#product_group_short_code").val('');
		}
     }); 
   
	$("#form1").on("change","#part_checked",function(){
		 var part_checked = $(this).val();
		 if(part_checked ==2){
			 $('#part_attention_notes_').show();
			 $('#part_checked_date_').hide();
			 $('#part_checked_date').val('');
		 }else if(part_checked==1){
			 $('#part_attention_notes_').hide();
			 $('#part_attention_notes').val('');
			 $('#part_checked_date_').show();
		 }else{
			 $('#part_attention_notes_').hide();
			 $('#part_checked_date_').hide();
		 }
		
	})
   
/////////////// fetch Total Components cost  //////////////
	/* $("#form1").on("change","#product_group",function(){
		var product_grp_id = $(this).val();
		if(product_grp_id != ""){
		//$('#zone_checking').show();
		//alert(product_grp_id);
		var form_data   = {'product_grp_id':product_grp_id};       
			////////////////////// For fetching address /////////////////////////
			$.ajax({
				async: true,
				type: "POST",
				url: site_url+"/modules/daynmic_product_management/index.php?page=ajax_actions&action=get_total_comonents_cost",
				data: form_data,
				success: function(result){  
					var resultObj = jQuery.parseJSON(result); 
					if(resultObj.status == 1){
						//$('#zone_checking').hide();
						  $("#total_com_cost").text("- Total : " + resultObj.total_com_cost); 
						  $("#total__labour_hours").text("- Total : " + resultObj.total_labour_hours); 
						  $("#total_labour_cost").text("- Total : " + resultObj.total_labour_cost); 
						  $("#total_costs").text("- Total : " + resultObj.total_cost); 
						  $("#total_quantity").text("- Total : " + resultObj.total_quantity); 
						  
						  $("#total_com_cost_val").val(+ resultObj.total_com_cost); 
						  $("#total__labour_hours_val").val(+ resultObj.total_labour_hours); 
						  $("#total_labour_cost_val").val(+ resultObj.total_labour_cost); 
						  $("#total_costs_val").val(+ resultObj.total_cost); 
						  $("#total_quantity_val").val(+ resultObj.total_quantity); 
					}else{
						  $("#total_com_cost").text('');
						  $("#total__labour_hours").text('');
						  $("#total_labour_cost").text('');
						  $("#total_costs").text('');
						  $("#total_quantity").text('');
						
						  $("#total_com_cost_val").val(''); 
						  $("#total__labour_hours_val").val(''); 
						  $("#total_labour_cost_val").val(''); 
						  $("#total_costs_val").val(''); 
						  $("#total_quantity_val").val(''); 
					}
						  $("#labour_hours_total_parts").val('');
						  $("#labour_hours").val('');
						  $("#components_costs").val('');
						  $("#total_cost").val('');
						  $("#total_quantity").val('');  
						  
						  
				}
			});
			////////////////////// End For fetching part_num_internal  /////////////////////////
		}else{
			  $("#part_number").val('');
			  $("#labour_hours_total_parts").val('');
			  $("#labour_hours").val('');
			  $("#components_costs").val('');
			  $("#total_cost").val('');
			  
			  $("#total_com_cost").text('');
			  $("#total__labour_hours").text('');
			  $("#total_labour_cost").text('');
			  $("#total_costs").text('');
			  
			  $("#total_com_cost_val").val(''); 
			  $("#total__labour_hours_val").val(''); 
			  $("#total_labour_cost_val").val(''); 
			  $("#total_costs_val").val(''); 
			  $("#total_quantity_val").val(''); 
		}
	});
	 */
	
    $(document).ready(function(){
       /* 
		$('#labour_hours').on('change', function(){
            var labourHoursTotalParts2 = parseFloat($(this).val());
            var currentTotalHours2 = parseFloat($('#total__labour_hours').text().split(':')[1]);

            if (!isNaN(currentTotalHours2)) {
                var newTotalHours2 = currentTotalHours2 + labourHoursTotalParts2;
                $('#labour_hours').val(newTotalHours2);
            }
        });  */
		/* $('#labour_hours_total_parts').on('change', function(){
            var labourHoursTotalParts1 = parseFloat($(this).val());
            var currentTotalHours1 = parseFloat($('#total_labour_cost').text().split(':')[1]);

            if (!isNaN(currentTotalHours1)) {
                var newTotalHours1 = currentTotalHours1 + labourHoursTotalParts1;
                $('#total_cost').val(newTotalHours1);
            }
        });
		$('#components_costs').on('change', function(){
            var labourHoursTotalParts3 = parseFloat($(this).val());
            var currentTotalHours3 = parseFloat($('#total_com_cost').text().split(':')[1]);

            if (!isNaN(currentTotalHours3)) {
                var newTotalHours3 = currentTotalHours3 + labourHoursTotalParts3;
                $('#components_costs').val(newTotalHours3);
            }
        }); */
		/* $('#total_cost').on('change', function(){
            var labourHoursTotalParts4 = parseFloat($(this).val());
            var currentTotalHours4 = parseFloat($('#total_costs').text().split(':')[1]);

            if (!isNaN(currentTotalHours4)) {
                var newTotalHours4 = currentTotalHours4 + labourHoursTotalParts4;
                $('#total_cost').val(newTotalHours4);
            }
        }); */
		
		$('#labour_hours_total_parts, #components_costs,#quantity').on('change', function(){
			var totalquantity = parseFloat($('#quantity').val()) || 0;
			 
			var totalLabourCost = parseFloat($('#labour_hours_total_parts').val()) || 0;
			var currentTotalHours = parseFloat($('#total_labour_cost').text().split(':')[1]) || 0;
			 
			var totalComponentsCost = parseFloat($('#components_costs').val()) || 0;
			    var new_comp_cost = totalComponentsCost * totalquantity;
				$('#components_costs').val(new_comp_cost);
				
			var totalComponents = parseFloat($('#components_costs').val()) || 0;	
			var currentTotalCost = parseFloat($('#total_com_cost').text().split(':')[1]) || 0;
			
			// var totalCost = parseFloat($('#total_cost').val()) || 0;
			
			 
			 
               
				
				/* var newTotalCost= totalLabourCost + new_comp_cost;
                $('#total_cost').val(newTotalCost); */
           
				var newTotalCost = totalLabourCost + currentTotalHours + totalComponents + currentTotalCost;
				$('#total_cost').val(newTotalCost);
			
		});
		
		  /* $('#quantity', '#components_costs').on('change', function(){
             var quantity = $(this).val();
            var currentTotalH = parseFloat($('#components_costs').val());
            if (!isNaN(currentTotalH)) {
                var new_comp_cost = currentTotalH * quantity;
				
                $('#components_costs').val(new_comp_cost);
            } 
        }); */ 
    });
	
	
   

});	
</script>