<?php 
session_start();
$where 					= " WHERE 1=1 ";
$next_page_condition 	= "";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
}
$frontEndURL = $config->frontEndURL;
###########################################  STRAT FILTER CONITIONS    #####################################
$category	= isset($_REQUEST['category']) ? $_REQUEST['category'] : "";
if($category) {
    $where	.= " AND product_group_name LIKE '%$category%' ";
    $next_page_condition.="&category=$category";
}

###########################################  	END  FILTER CONITIONS 	#####################################
###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page
$table_name		= "product_group";
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  $where ";
$page_header = "Product Group Management";
include("paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################
$query = "SELECT * FROM $table_name $where ORDER BY id DESC LIMIT $eu, $limit";
$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_counties = mysqli_num_rows(mysqli_query($conn,$join_query_for_paging));
#################################   DELETE    #########################################
// when we click on delete this area of php code will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete')
{
	$sql=mysqli_query($conn,"DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	$sql=mysqli_query($conn,"DELETE FROM product_group_mapping WHERE group_id = '".$_REQUEST['id']."' ");
	$_SESSION['info_message'] = "Product Group  deleted sucessfully";
	header("location: $file_name?page=view".$next_page_condition.$paging);
	exit;
}
#################################  END DELETE    #########################################


if($_POST["save"]){
	  $pro_temp_id 					= $_REQUEST['pro_temp_id']; 
	  $id 					= $_REQUEST['id']; /////////////
	  
	  
	  $usual_source_id = utility::getTableFieldById("item_management","usual_source","id",$id);
	  $usual_source_pro_temp_id = utility::getTableFieldById("item_management","usual_source","id",$pro_temp_id);
	  
		
	if (isset($_POST["is_parent"])) {
		
		function hasChildren($id, $pro_temp_id, $conn) {
			$query = "SELECT sub_part_id FROM bom WHERE main_product_id = $id";
			$check_result = mysqli_query($conn, $query);

			if ($check_result->num_rows > 0) {
				while ($row = $check_result->fetch_assoc()) {
					
					if ($row['sub_part_id'] == $pro_temp_id) {
						return true; 
					}
					
					if (hasChildren($row['sub_part_id'], $pro_temp_id, $conn)) {
						return true; 
					}
				}
			}
			return false; 
		}

		function canBeParent($id, $pro_temp_id, $conn) {
			if (hasChildren($id, $pro_temp_id, $conn)) {
				//echo "No, you cannot attach this as a parent.";
				$_SESSION['info_message'] = "No, you cannot attach this as a parent.";
				header("Location: index?page=view_item_details&from=view_item&pro_temp_id=" . $pro_temp_id . "&id=" . $id);
                exit;
			} else {
				
			}
		}
	    canBeParent($id, $pro_temp_id, $conn);
		
        $check_sql = "SELECT id FROM bom WHERE main_product_id = '$pro_temp_id' AND sub_part_id = '$id'";
        $check_result = mysqli_query($conn, $check_sql);
		
		$check_sql_error = "SELECT id FROM bom WHERE main_product_id = '$id' AND sub_part_id = '$pro_temp_id'";
        $check_result_error = mysqli_query($conn, $check_sql_error);

        if (mysqli_num_rows($check_result_error) > 0) {
            $_SESSION['info_message'] = "Not Possible.";
            header("Location: index?page=view_item_details&from=view_item&pro_temp_id=" . $pro_temp_id . "&id=" . $id);
            exit;
        }
		
		
		if (mysqli_num_rows($check_result) > 0) {
            $_SESSION['info_message'] = "This Parent already exists.";
            header("Location: index?page=view_item_details&from=view_item&pro_temp_id=" . $pro_temp_id . "&id=" . $id);
            exit;
        }
	
		
		if($usual_source_pro_temp_id == "Bought In"){
			$_SESSION['info_message'] = "Not Possible As This Parent is Bought In";
            header("Location: index?page=view_item_details&from=view_item&pro_temp_id=" . $pro_temp_id . "&id=" . $id);
            exit;
			
		}
    }else{
		
        if($usual_source_id == "Bought In"){
			$_SESSION['info_message'] = "Not Possible As This Parent is Bought In";
            header("Location: index?page=view_item_details&from=view_item&pro_temp_id=" . $pro_temp_id . "&id=" . $id);
            exit;
			
		}
			$check_sql = "SELECT id FROM bom WHERE main_product_id = '$id' AND sub_part_id = '$pro_temp_id'";
			$check_result = mysqli_query($conn, $check_sql);
			if (mysqli_num_rows($check_result) > 0) {
				$_SESSION['info_message'] = "This Child already exists.";
				header("Location: index?page=view_item_details&from=view_item&pro_temp_id=" . $pro_temp_id . "&id=" . $id);
				exit;
			}
	}
	
	
	for($i=0;$i<count($_POST["group_code"]);$i=$i+1){
		$group_code = $_POST["group_code"][$i];
		$group_name = $_POST["group_number"][$i];
		$qty		 = $_POST["qty"][$i];
		$unit 		 = $_POST["unit"][$i];
		$ctrl_id = $_POST["chk"][$i];
		$product_cost = $_POST["product_cost"][$i];
		$product_labour_cost = $_POST["product_labour_cost"][$i];
		$product_labour_hours = $_POST["product_labour_hours"][$i];		
		$machine_cost = $_POST["machine_cost"][$i];
		$machine_hours = $_POST["machine_hours"][$i];
		$child_qty = $_POST["child_qty"][$i];
		
		$group_number = $_POST["group_number"][$i];
		
	   
	   /*  $machine_cos = utility::getTableFieldById("product_name","machine_cost","pro_id",$pro_temp_id);
	    $machine_cost = $machine_cos *$qty;
		$sql2= "UPDATE product_name SET machine_cost = '".$machine_cost."' WHERE id = '$newid' "; 
	    mysqli_query($conn,$sql2);*/
		if (trim($_POST["is_child"]) == "2") {
		$sql = "insert into bom set main_product_id='" . $ctrl_id . "',sub_part_id='" . $pro_temp_id . "',sub_part_name='" . $group_name . "',quantity_required='".$qty."',type='".$group_code."',unit_cost='".$product_cost."',product_labour_cost='".$product_labour_cost."',product_labour_hours='".$product_labour_hours."',machine_cost='".$machine_cost."',machine_hours='".$machine_hours."'";
		 mysqli_query($conn, $sql);

		}else{
			//$group_number = utility::getTableFieldById("item_management","group_number","id",$ctrl_id);
			
			
			
			 $query_for_parent = "SELECT * FROM product_name WHERE pro_id = $ctrl_id";
			//die;
			$result_for_Parent = $conn->query($query_for_parent);

			if ($result_for_Parent && $result_for_Parent->num_rows > 0) {
				$row = $result_for_Parent->fetch_assoc();

				$cost = $row['cost'];
				$group_number = $row['group_number'];
				$labour_hours_parent = $row['labour_hours'];
				$labour_cost_parent = $row['labour_cost'];
				$machine_hours_parent = $row['machine_hours'];
				$machine_cost_parent = $row['machine_cost'];
				$group_code = $row['group_code'];

			}
			
			/*
			$cost = utility::getTableFieldById("product_name","cost","pro_id",$ctrl_id);
			$labour_hours_parent = utility::getTableFieldById("product_name","labour_hours","pro_id",$ctrl_id);
			$labour_cost_parent = utility::getTableFieldById("product_name","labour_cost","pro_id",$ctrl_id);
			$machine_hours_parent = utility::getTableFieldById("product_name","machine_hours","pro_id",$ctrl_id);
			$machine_cost_parent = utility::getTableFieldById("product_name","machine_cost","pro_id",$ctrl_id);
			$group_code = utility::getTableFieldById("product_name","group_code","pro_id",$ctrl_id);*/
			
			$sql = "insert into bom set main_product_id='" . $pro_temp_id . "',sub_part_id='" . $ctrl_id . "',sub_part_name='" . $group_number . "',quantity_required='".$child_qty."',type='".$group_code."',unit_cost='".$cost."',product_labour_cost='".$labour_cost_parent."',product_labour_hours='".$labour_hours_parent."',machine_cost='".$machine_cost_parent."',machine_hours='".$machine_hours_parent."'";
		 mysqli_query($conn, $sql);
		}
	}
	$_SESSION['info_message'] = "Product Group Added Sucessfully";
	
	header("Location: index?page=view_item_details&from=view_item&pro_temp_id=" . $pro_temp_id . "&id=" . $id);
	exit;


}elseif($_POST["update"]){
}
?>
<style>
.list-group-item>.badge {
    float: none !important; 
    margin-left: 10px;
}
.node-treeview button{
    background: none;
    border: none;
}
.no_background_border{
    background: none;
    border: none;
}

        /* Dropdown container */
        .dropdown {
            position: relative;
            display: inline-block;
        }

        /* Primary button styling */
        .dropdown button {
            background-color: #007bff; /* Primary blue */
            color: white;
            border: none;
            padding: 8px 10px;
            font-size: 16px;
            cursor: pointer;
            border-radius: 5px;
            transition: background 0.3s;
        }

        /* Hover effect for button */
        .dropdown button:hover {
            background-color: #0056b3;
        }

        /* Dropdown content */
        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 200px;
            box-shadow: 0px 8px 16px rgba(0,0,0,0.2);
            border-radius: 5px;
            overflow: hidden;
            z-index: 1;
        }

        /* Dropdown items */
        .dropdown-content a {
            display: block;
            padding: 10px;
            text-decoration: none;
            color: black;
            transition: background 0.2s;
        }

        /* Hover effect for dropdown items */
        .dropdown-content a:hover {
            background-color: #ddd;
        }
    </style>
<section class="content">
	<div class="container-fluid">
		<div class="row">
			<div class="col-lg-12">
				<div class="card">
				<!----------------------- Message ------------------------------->
				 <?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 ------------------------------->
			  <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">Product 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">
							<div id="group_tree">
								<!-- Dynamic content will be inserted here by AJAX -->
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
						</div>
					</div>
				</div>
			</div>
						<?php $id = $_REQUEST['id']; 
						     $usual_source = $enq_row['usual_source']; 
						$sql_for_parent = "SELECT im.part_number, im.part_number_id FROM bom b JOIN item_management im ON b.main_product_id = im.id WHERE b.sub_part_id = $id";

							$result_for_paret = $conn->query($sql_for_parent);
						?>                 

				  
				   <div style="display: flex; justify-content: flex-end; align-items: center;">
				   
						<?php if($usual_source =='Manufactured'){ include("add_route_used_with_ajax.inc.php");}else{
							
						} ?>

						<div class="m-2 dropdown">
							<button id="dropdown-btn" class="btn" onclick="toggleDropdown()">View Parent ▼</button>
							<div id="dropdown-content" class="dropdown-content">
								<?php
								if ($result_for_paret->num_rows > 0) {
									while ($row = $result_for_paret->fetch_assoc()) {
										$partNumber = htmlspecialchars($row['part_number']);
										$itemId = $row['part_number_id']; 
										//echo "<a href='#' onclick='create_group_tree(\"$itemId\")'>$partNumber</a>";
										echo "<a href='#' data-toggle='modal' class='p-1 text-info text-bold' data-target='#ShowModal' id='".$itemId."' alt='".$itemId."'>$partNumber</a>";
									}
								} else {
                                  echo "<a href='#' class='p-1 text-danger text-bold' data-toggle='modal' data-target='#ShowModal' onclick='showParent(\"No Parent Found\", null)'>No Parent Found</a>";
								}
								?>
							</div>
						</div>
						<a href="" data-toggle="modal" data-target="#myModal"
							class="m-2 btn btn-success add_new_station"
							style="margin-right: 10px; padding: 7px 10px;" 
							alt="" data-station_name="">Add New Item</a>
					</div>
                     <strong style="padding-left:25px;color:red;"> <?=$messgae;?></strong>
				<div class="card-body">
				<form method="post">
				         
					<table style="" id="product_list" class="<?=$hideRoute;?>">
						<tr> 
						<td colspan="10" style="text-align:left;padding:5px;">
							<input type="checkbox" id="is_parent" name="is_parent" value="1" onchange="update_group_type(1);"/> Add Parent Item&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
							<input type="checkbox" id="is_child" name="is_child" value="2"  onchange="update_group_type(2);"/> Add Sub-Item
						</td>
							
						</tr>
						<tr style="display:none;" class="exists_bill_of_material">
							<td colspan="10">
								<label class="control-label" style="font-size:15px;">Select Part Number:</label>
								<? $gsi->getPartNumberListBOM("pro_temp_id", $pro_temp_id, "100%", false, "form-control select2 pro_temp_id", "",$product_id); ?>
							</td>
						</tr>

						<tr style="display:none;" class="bill_of_material">
							<td class="col-lg-1"><label class="control-label" style="font-size:15px;">P Number</label><br /><input type="text" id="group_number" name="group_number[]" value="" class="form-control" placeholder="P Num.." /></td>
							<td class="col-lg-1"><label class="control-label" style="font-size:15px;">P Name</label><br /><input type="text" id="group_name" name="group_name[]" value="" class="form-control" placeholder="P Name" required /></td>
							<td class="col-lg-1"><label class="control-label" style="font-size:14px;">G Code</label><br /><select class="form-control" id="group_code" name="group_code[]">
								<option value="Manufactured" <?=($group_code == 'Manufactured' ? 'selected' : '');?>>Manufactured</option>
								<option value="Bought In" <?=($group_code == 'Bought In' ? 'selected' : '');?>>Bought In</option>
							</select></td>
							<td class="col-lg-1"><label class="control-label" style="font-size:15px;">Quantity</label><br /><input type="number" id="qty" name="qty[]" step="1" value="" class="form-control" placeholder="Qty" required /></td>
							<td class="col-lg-1"><label class="control-label" style="font-size:15px;">Unit</label><br /><input type="text" id="unit" name="unit[]" value="" class="form-control" placeholder="em" /></td>
							<td class="col-lg-1"><label class="control-label" style="font-size:15px;">Cost</label><br /><input type="number" id="product_cost" name="product_cost[]" min="0" value="" class="form-control" placeholder="Cost" required readonly /></td>
							<td class="col-lg-1" id="l_cost"><label class="control-label" style="font-size:14px;">Labour Cost</label><br /><input type="number" id="product_labour_cost" name="product_labour_cost[]" min="0" value="" class="form-control" placeholder="Labour Cost"  readonly /></td>
							<td class="col-lg-1" id="l_hrs"><label class="control-label" style="font-size:15px;">Labour Hrs</label><br /><input type="number" id="product_labour_hours" name="product_labour_hours[]" step="0.01" value="" class="form-control" placeholder="Hours"readonly /></td>
							<td class="col-lg-2" id="m_cost_hide"><label class="control-label" style="font-size:15px;">Machine Cost</label><br /><input type="number" id="machine_cost" name="machine_cost[]" min="0" value="" class="form-control" placeholder="Total Cost" readonly /></td>
							<td class="col-lg-2" id="m_hrs_hide"><label class="control-label" style="font-size:15px;">Machine Hours</label><br /><input type="number" id="machine_hours" name="machine_hours[]" min="0" value="" class="form-control" placeholder="Total Cost" readonly /></td>
							<!-- <td class="col-lg-2"><label class="control-label" style="font-size:15px;">Total Comp Cost</label><br /><input type="number" id="total_product_cost" name="total_product_cost[]" min="0" value="" class="form-control" placeholder="Total Cost" readonly="readonly" /></td>
							<td class="col-lg-2"><label class="control-label" style="font-size:15px;">Total Labour Cost</label><br /><input type="number" id="total_labour_cost" name="total_labour_cost[]" min="0" value="" class="form-control" placeholder="Total Cost" readonly="readonly" /></td> -->
						</tr>
					</table>

					<br/>
					<table style="width:100%; dsiplay:none">
						<tr>
							<td>
								<button type="button" value="Add New Product" class="btn btn-primary bill_of_material_add" style="display:none;"  onclick="add_new_product_list();" />Add More </button>
								<button type="submit" name="save" value="savedetails" class="btn btn-success bill_of_material_save" onclick="validate_form();" style="display:none;" >Save</button>  
									 <input type="hidden" id="" name="id" value="<?=$_REQUEST['id']?>">
								<button type="submit" name="" value="" class="btn btn-info m-2 hide"  onclick="validate_form();"><a href="<?php echo $siteURL ?>/item_management/index?page=edit&from=view_item&id=<?=$_REQUEST['id'];?>&group_code_search=<?=$enq_row['part_number_id'];?>"class="text-white">Update Bill OF Materials</a></button>
				                
							</td>
						</tr>
					</table>
					
					
					<table id="group_details" class="table table-bordered table-striped">
						<thead> 
							<tr> 
								 
								<th style="font-size:13px;">P Number</th> 
								<th style="font-size:13px;">P Name</th> 
								<th style="font-size:13px;">G Code</th> 
								<th style="font-size:13px;">QTY</th> 
								<th style="font-size:13px;">Cost</th>
								<th  style="font-size:13px;">L Cost</th>
								<th style="font-size:13px;">L Hours</th>
								<th style="font-size:13px;">M Cost</th>
								<th style="font-size:13px;">M - Hrs</th>
								<th style="font-size:13px;">Total</th>
								<th style="font-size:13px;">Edit</th>
							</tr> 
						</thead> 	
					</table>
					<div id="tableContainer"></div>
				</form>

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

</body>
</html>


<script>
    function toggleDropdown() {
        var dropdown = document.getElementById("dropdown-content");
        var button = document.getElementById("dropdown-btn");

        if (dropdown.style.display === "block") {
            dropdown.style.display = "none";
            button.innerHTML = "View Parent ▼"; 
        } else {
            dropdown.style.display = "block";
            button.innerHTML = "View Parent ▲";
        }
    }

    const id = <?= json_encode($_REQUEST['id'] ?? 0); ?>;
	
    function fetchGroupListForListing(id) {
        $.ajax({
            url: site_url + "/modules/item_management/index.php?page=ajax_actions&action=get_group_list_for_listing&id=" + id,
            method: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    $('#tableContainer').html(response.htmlContent);
                } else {
                    alert(response.message);
                }
            },
            error: function() {
                alert('An error occurred while processing the request.');
            }
        });
    }
    fetchGroupListForListing(id);
</script>
<script type="text/javascript">
$(document).on('click', '.delete-btn', function () {
    const id = $(this).data('id');
    const mainProductId = $(this).data('main-product-id');
    //alert(mainProductId);
	//alert(id);
    if (confirm('Are you sure you want to delete this item?')) {
        $.ajax({
			url: site_url + "/modules/item_management/index.php?page=ajax_actions&action=delete_table_item&id=" + id,
            method: 'POST',
            data: { id: id, main_product_id: mainProductId },
            dataType: 'json',
            success: function (response) {
                if (response.status === 'success') {
                    alert(response.message);
                    $('#row-' + id).remove(); 
					location.reload();
                } else {
                    alert(response.message);
                }
				 
            },
            error: function () {
                alert('An error occurred while deleting the item.');
            }
        });
    }
});



$(document).ready(function(){
  $("#myModal .close_button2").click(function(){
		location.reload();
  });	
  
  $(".add_new_station").click(function(){	
   $("#myModalLabel").html("Add New Part");
	var hide_top_left = "&hide_top=1&hide_left=1";
	var from = "&from=add_new_item_progress";
	var client_id = 'test';
	$('.modal-dialog').css({"max-width":"60%"});
	$(".modal_iframe").attr("src","<?=$config->frontEndURL?>/admin/item_management/index?page=add&client_id="+client_id+hide_top_left+from);
});
  });	

function validate_form(){
	return true;
}
$('#ShowModal').on('show.bs.modal', function (e) {
  create_group_tree(e.relatedTarget.attributes.alt.value);
})

function deltblrow(ctrl){
	$(ctrl).closest('tr').remove();
	return false;
}/* 
function update_total_cost(){
	//$('#group_details').DataTable().rows().data().toArray()
	//qty[]
	
	if(document.getElementById("is_parent").checked){
		var total_product_cost=0;
		var total_labour_cost=0;
		var table = $('#group_details').DataTable();
		var rows = table.rows().nodes();
		
		for(i=0;i<rows.length;i=i+1){
			if(rows[i].childNodes[0].childNodes[0].checked){
				total_product_cost=total_product_cost + (rows[i].childNodes[6].innerText * 1);
				total_labour_cost=total_labour_cost + (rows[i].childNodes[7].innerText * 1);
			}
		}
		
		for(i=0;i<$('input[name="total_product_cost[]"]').length;i=i+1){
			if($('input[name="qty[]"]')[i].value.trim()==""){
				$('input[name="qty[]"]')[i].value=0;
			}
			if($('input[name="product_cost[]"]')[i].value.trim()==""){
				$('input[name="product_cost[]"]')[i].value=0;
			}
			if($('input[name="product_labour_cost[]"]')[i].value.trim()==""){
				$('input[name="product_labour_cost[]"]')[i].value=0;
			}
			
			$('input[name="total_product_cost[]"]')[i].value=total_product_cost + ($('input[name="qty[]"]')[i].value * $('input[name="product_cost[]"]')[i].value);
			$('input[name="total_labour_cost[]"]')[i].value=total_labour_cost + ($('input[name="product_labour_cost[]"]')[i].value * $('input[name="qty[]"]')[i].value);
		}
	}else{
		for(i=0;i<$('input[name="total_product_cost[]"]').length;i=i+1){
			for(i=0;i<$('input[name="total_product_cost[]"]').length;i=i+1){
				if($('input[name="qty[]"]')[i].value.trim()==""){
					$('input[name="qty[]"]')[i].value=0;
				}
				if($('input[name="product_cost[]"]')[i].value.trim()==""){
					$('input[name="product_cost[]"]')[i].value=0;
				}
				if($('input[name="product_labour_cost[]"]')[i].value.trim()==""){
					$('input[name="product_labour_cost[]"]')[i].value=0;
				}
				
				$('input[name="total_product_cost[]"]')[i].value=($('input[name="qty[]"]')[i].value * $('input[name="product_cost[]"]')[i].value);
				$('input[name="total_labour_cost[]"]')[i].value=($('input[name="product_labour_cost[]"]')[i].value * 1);
			}
			
		}			
	}
} */

function update_group_type(ctrl) {
    const parentCheckbox = document.getElementById("is_parent");
    const childCheckbox = document.getElementById("is_child");
    const existsBillRow = document.querySelector(".exists_bill_of_material");
	const existsBillRowsave = document.querySelector(".bill_of_material_save");
    const newBillRow = document.querySelector(".bill_of_material");

    if (ctrl == 1) {
        if (parentCheckbox.checked) {
            childCheckbox.checked = false;
            existsBillRow.style.display = "table-row";
            newBillRow.style.display = "none";
			$('.bill_of_material').hide();
			$('.bill_of_material_add').hide();
			$('.bill_of_material_save').show();
        } else {
            existsBillRow.style.display = "none";
			$('.bill_of_material').hide();
        }
    } else {
        if (childCheckbox.checked) {
           parentCheckbox.checked = false;
            existsBillRow.style.display = "table-row";
            newBillRow.style.display = "none";
			$('.bill_of_material').show();
			$('.bill_of_material_add').hide();
			$('.bill_of_material_save').show();
        } else {
            newBillRow.style.display = "none";
			$('.bill_of_material').hide();
			
        }
    }
    update_total_cost(); // Ensure cost updates as needed
}

//chk[]
//[]
$(document).on('change', '.group_checkbox, input[name="qty[]"], input[name="product_cost[]"], input[name="product_labour_cost[]"]', function() {
    //alert($(this).val());
	update_total_cost();
});
/* 
function add_new_product_list(){
	tbl=document.getElementById("product_list");
	newrow='<tr>';
	;
	newrow=newrow+'<td  class="col-lg-1"><label class="control-label" style="font-size:15px;">P Number </label><input type="text" id="group_number" name="group_number[]" class="form-control" placeholder="P Num.." value=""/></td>';
	
	newrow=newrow+'<td  class="col-lg-1"><label class="control-label" style="font-size:15px;">P Name </label><input type="text" id="group_name" name="group_name[]" class="form-control" placeholder="P Name" value=""/></td>';
	
	newrow=newrow+'<td class="col-lg-1"><label class="control-label" style="font-size:14px;">G Code</label><input type="text" id="group_code" name="group_code[]" class="form-control" placeholder="G Code" value=""/></td>';
	
	newrow=newrow+'<td  class="col-lg-1"><label class="control-label" style="font-size:15px;">Quantity</label> <input type="number" id="qty" name="qty[]" step="0.01" value="" class="form-control" placeholder="Qty" required/></td>';
	
	newrow=newrow+'<td  class="col-lg-1"><label class="control-label" style="font-size:15px;">unit </label><br/><input type="text" id="unit" name="unit[]"  value="" class="form-control" placeholder="Unit" /></td>';
	
	newrow=newrow+'<td  class="col-lg-1"><label class="control-label" style="font-size:15px;">Cost</label> <input type="number" id="product_cost" name="product_cost[]" min="0" value="" placeholder="Cost" class="form-control" required/></td>';
	
	newrow=newrow+'<td class="col-lg-1"><label class="control-label" style="font-size:14px;">Labour Cost</label> <input type="number" id="product_labour_cost" name="product_labour_cost[]" min="0" value="" placeholder="Labour Cost" class="form-control" required/></td>';
	
	newrow=newrow+'<td class="col-lg-1"> <label class="control-label" style="font-size:15px;">Labour Hrs </label><br/><input type="number" id="product_labour_hours" name="product_labour_hours[]" step="0.01" value="" class="form-control" placeholder="Hours" required/></td>';
	
	newrow=newrow+'<td class="col-lg-2" ><label class="control-label" style="font-size:15px;">Total Components Cost</label><input type="number" id="total_product_cost" name="total_product_cost[]" min="0" value="" placeholder="Total Components Cost" class="form-control" readonly="readonly"/></td>';
	
	newrow=newrow+'<td  class="col-lg-2" ><label class="control-label" style="font-size:15px;">Total Labour Cost </label><input type="number" id="total_labour_cost" name="total_labour_cost[]" min="0" placeholder="Total Labour Cost" value="" class="form-control" readonly="readonly"/></td>';
	
	newrow=newrow+'<td><a href="#" onclick="return deltblrow(this)"><img src="<?=$frontEndURL;?>/admin/images/del.gif" ></a></td>';
	newrow=newrow+'</tr>';
	$(tbl).find('tbody').append(newrow);
} */

function create_group_tree(id) {
	//alert(id);

    $.ajax({
        url: site_url + "/modules/item_management/index.php?page=ajax_actions&action=get_group_list&id=" + id,
        method: "POST",
        dataType: "json",  // Assuming your PHP script returns JSON data
        success: function(data) {
            if (data.status === 'success') {
                // Populate the #group_tree div with the received data
                $("#group_tree").html(data.htmlContent);  // Assume the PHP script sends back HTML content for the tree

                // Show the modal
                $('#ShowModal').modal('show');
            } else {
                alert("No data available");
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Something went wrong: " + textStatus + " - " + errorThrown);
        }
    });

};
$( document ).ready(function() {
	//create_group_tree(5);
	//create_product_tree();
	$('#group_details').DataTable({
		'lengthMenu': [
			[10,25, 50,100],
			[10,25, 50,100]
		],
	  "paging": false,
	  "lengthChange": true,
	  "searching": false,
	  "ordering": false,
	  "info": false,
	  "autoWidth": false,
	  "processing": true,
	  "serverSide": false,
	  "selectedBackColor": 'none',
	  "language": {
		  "emptyTable": "No Group Created.Try Adding Group"
		},
		
	  "ajax": {
			'type': 'POST',
			url: site_url+"/modules/item_management/index.php?page=ajax_actions&action=get_group_details&pro_id",
			'data': {
			   'pro_id': '<?php echo $_REQUEST['id'];?>',
			},
	  },
	  'columnDefs': [
		/* {
			"targets": 0, 
			"className": "text-center"
		}, */
		{
			"targets": 1,
			"className": "text-center"
		},
		{
			"targets": 2,
			"className": "text-center"
		},
		{
			"targets": 3,
			"className": "text-center"
		},
		{
			"targets": 4,
			"className": "text-center"
		},
		{
			"targets": 5,
			"className": "text-center"
		},
		{
			"targets": 6,
			"className": "text-center"
		},
		{
			"targets": 7,
			"className": "text-center"
		},
		{
			"targets": 8,
			"className": "text-center"
		},
		{
			"targets": 9,
			"className": "text-center"
		} ,
		{
			"targets": 10,
			"className": "text-center"
		} 
	  ],
	  "columns": [
				/*  { 
					"data": "Action",
					sortable: false,
					"render": function (data, type, full, meta){
						return '<input type="checkbox" class="group_checkbox" name="chk1[]" value="'+full.chk_val+'"/>';
					}
				},  */
				{ "data": "group_number" },
				{ "data": "group_name" },
				{ "data": "group_code" },
				{ "data": "qty" },
				{ "data": "cost" },
				{ "data": "labour_cost" },
				{ "data": "labour_hours" },
				{ "data": "m_cost" },
				{ "data": "m_hrs" },
				{ "data": "total_final_cost" },
				{ 
					"data": "Action",
					sortable: false,
					"render": function (data, type, full, meta){
						return '<span ><a href="<?php echo $siteURL ?>/item_management/index?page=edit&from=view_item&id=<?php echo $_REQUEST['id'];?>&group_code_search=<?php echo $enq_row['part_number_id'];?>" class="text-primary">Edit<a/></span>';
					}
				}, 
				
			],
			
			"fnDrawCallback": function(oSettings) {
				if (oSettings._iDisplayLength > oSettings.fnRecordsDisplay()) {
					$(oSettings.nTableWrapper).find('#group_details_paginate').hide();
				} else {
					 $(oSettings.nTableWrapper).find('#group_details_paginate').show();
				}
			},
			//order: [[4, 'desc']],
	  
	});
	
/* 	 $('#group_details tbody').on('click', '.notes_remove', function() {
        if (confirm("Do you want to delete.")) {
            var notes_id = $(this).attr("alt");
			alert(notes_id);
            $("#delete_loading_notes_"+notes_id).show();
            var form_data = {'notes_id': notes_id};
            $.ajax({
                async: true,
                type: "POST",
                url: "<?php echo $siteURL?>/modules/item_management/index.php?page=ajax_actions&action=remove_item_link",
                data: form_data,
                success: function(result) {
                    var resultObj = jQuery.parseJSON(result);
                    if (resultObj.status == "success") {
						location.reload();
                        $("#delete_loading_notes_"+notes_id).hide();
                        $("#delete_notes_done"+notes_id).show();
                        flag_for_table = 1;
                        post_out_t.draw(false);
                    }
                }
            });
        }
    });  */

$('#pro_temp_id').on('change', function(){
     var id = $(this).val();
	
	  var form_data   = {'part_id':id};
			$.ajax({
				async: true,
				type: "POST",
				url: site_url+"/modules/item_management/index.php?page=ajax_actions&action=get_part_details",
				data: form_data,
				success: function(result){  
					var resultObj = jQuery.parseJSON(result); 
					if(resultObj.status == "success"){
						$("#group_number").val(resultObj.group_number);
						$("#product_labour_cost").val(resultObj.labour_cost);
						$("#product_labour_hours").val(resultObj.labour_hours);
						$("#group_name").val(resultObj.group_name);
						$("#qty").val(resultObj.qty);
						$("#machine_cost").val(resultObj.machine_cost);
						$("#machine_hours").val(resultObj.machine_hours);
						$("#product_cost").val(resultObj.total_child_cost);
					    $("#group_code").val(resultObj.group_code).trigger("change");
						
					}
					if(resultObj.group_code == 'Bought In'){
						
						
						$('#product_labour_cost').val('');
						$('#product_labour_hours').val('');
						$('#machine_hours').val('');
						$('#machine_cost').val('');
						
						$('#m_cost_hide').hide();
						$('#m_hrs_hide').hide();
						$('#l_hrs').hide();
						$('#l_cost').hide();
						
					}else{
						$('#l_hrs').show();
						$('#l_cost').show();
						$('#m_hrs_hide').show();
						$('#m_cost_hide').show();
					}
				}
			});
	 
	
 });	
});
</script>