<?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']; 
	for($i=0;$i<count($_POST["group_code"]);$i=$i+1){
		$group_code = $_POST["group_code"][$i];
		$group_name = $_POST["group_name"][$i];
		$qty		 = $_POST["qty"][$i];
		$unit 		 = $_POST["unit"][$i];
		$product_cost = $_POST["product_cost"][$i];
		$product_labour_cost = $_POST["product_labour_cost"][$i];
		$product_labour_hours = $_POST["product_labour_hours"][$i];
		$group_number = $_POST["group_number"][$i];
		$sql="insert into product_name set group_code='".$group_code."',group_name='".$group_name."',cost='".$product_cost."',labour_cost='".$product_labour_cost."',labour_hours='".$product_labour_hours."',group_number='".$group_number."',qty='".$qty."',unit='".$unit."'";
		mysqli_query($conn,$sql);
		$newid=mysqli_insert_id($conn);
		
		if (isset($_POST["chk"]) && is_array($_POST["chk"])) {
			if (trim($_POST["is_child"]) == "1") {
				for ($j = 0; $j < count($_POST["chk"]); $j = $j + 1) {
					$ctrl_id = $_POST["chk"][$j];
					$sql = "insert into product_link set parent_id='" . $ctrl_id . "',child_id='" . $newid . "'";
					mysqli_query($conn, $sql);
				}
			} else {
				for ($j = 0; $j < count($_POST["chk"]); $j = $j + 1) {
					$ctrl_id = $_POST["chk"][$j];
					$sql = "insert into product_link set parent_id='" . $newid . "',child_id='" . $ctrl_id . "'";
					mysqli_query($conn, $sql);
				}
			}
		} else {
			// Handle the case where $_POST["chk"] is not set or is not an array
			// For example, you might display an error message or perform some other action.
			
		}

	}
	$_SESSION['info_message'] = "Product Group Added Sucessfully";
	
	header("Location: index?page=view_product_details&from=view_product&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;
}
</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">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>
				
				<button type="submit" name="" value="" class="btn btn-info" style="float:right;" onclick="validate_form();"><a href="<?php echo $siteURL ?>/daynmic_product_management/index?page=edit&from=view_product&pro_temp_id=<?=$_REQUEST['pro_temp_id'];?>&id=<?=$_REQUEST['id'];?>&group_code_search=<?=$enq_row['part_number_id'];?>"class="text-white">Update Bill OF Materials / Part Number</a></button>
			<div class="card-body">
				<form method="post">
				
					<table style="" id="product_list" class="">
						<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);"/> Create As Parent&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
							<input type="checkbox" id="is_child" name="is_child" value="1" checked onchange="update_group_type(2);"/> Create As Child
						</td>
						</tr>
						<tr>
							<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/><input type="text" id="group_code" name="group_code[]" value=""  class="form-control" placeholder="G Code" required/></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="0.01" 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/></td>
							
							<td class="col-lg-1"> <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" required/></td>
							
							<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"/></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 " onclick="add_new_product_list();" />Add New Part Number</button>
								<button type="submit" name="save" value="savedetails" class="btn btn-success " onclick="validate_form();">Save Part Number</button>
								     <input type="hidden" id="" name="pro_temp_id" value="<?=$_REQUEST['pro_temp_id']?>">  
									 <input type="hidden" id="" name="id" value="<?=$_REQUEST['id']?>">
								<button type="submit" name="" value="" class="btn btn-info " onclick="validate_form();"><a href="<?php echo $siteURL ?>/daynmic_product_management/index?page=edit&from=view_product&pro_temp_id=<?=$_REQUEST['pro_temp_id'];?>&id=<?=$_REQUEST['id'];?>"class="text-white">Edit Part Number</a></button>
							</td>
						</tr>
					</table>
					
					
					<table id="group_details" class="table table-bordered table-striped">
						<thead> 
							<tr> 
								<th></th>
								<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;">TotCompCost</th>
								<th style="font-size:13px;">TotLabCost</th>
								<th style="font-size:13px;">Total</th>
								<th style="font-size:13px;">Del</th>
							</tr> 
						</thead> 	
					</table>
					<!--<table style="width:100%">
						<tr><td>
							<div id="product_tree" style="border-top:solid 1px lightgray;margin-left:5px;">
								<br/>No Product Group Created
							</div>
						</td></tr>
					</table>
					<table style="width:100%">
						<tr>
							<td>
								
							</td>
						</tr>
					</table>
					<br/><br/><hr/><br/>
					<h2>Select Parent Group</h2>
					<table style="width:100%">
						<tr><td>
							<div id="group_tree" style="border-top:solid 1px lightgray;margin-left:5px;">
								<br/>No Group Created
							</div>
						</td></tr>
					</table>-->
				</form>

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

</body>
</html>

<script type="text/javascript">
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 * 1);
		}
	}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){
	if(ctrl==1){
		if(document.getElementById("is_parent").checked){
			document.getElementById("is_child").checked=false;
		}else{
			document.getElementById("is_child").checked=true;
		}
	}else{
		if(document.getElementById("is_child").checked){
			document.getElementById("is_parent").checked=false;
		}else{
			document.getElementById("is_parent").checked=true;
		}
	}
	update_total_cost();
}
//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){
	$.ajax({ 
		url: site_url+"/modules/daynmic_product_management/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,
                preventUnselect: true,
                showTags: true,
                color:'black'
			});
        },
		error :function(jqXHR, textStatus, errorThrown)
		{
			alert("something went wrong");
        }   
    });
}
$( document ).ready(function() {
	//create_group_tree(5);
	//create_product_tree();
	$('#group_details').DataTable({
		'lengthMenu': [
			[10,25, 50,100],
			[10,25, 50,100]
		],
	  "paging": true,
	  "lengthChange": true,
	  "searching": true,
	  "ordering": true,
	  "info": true,
	  "autoWidth": false,
	  "processing": true,
	  "serverSide": false,
	  "selectedBackColor": 'none',
	  "language": {
		  "emptyTable": "No Group Created.Try Adding Group"
		},
		
	  "ajax": {
			'type': 'POST',
			url: site_url+"/modules/daynmic_product_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="chk[]" value="'+full.chk_val+'"/>';
					}
				},
				{ "data": "group_number" },
				{ "data": "group_name" },
				{ "data": "group_code" },
				{ "data": "qty" },
				{ "data": "cost" },
				{ "data": "labour_cost" },
				{ "data": "labour_hours" },
				{ "data": "total_cost" },
				{ "data": "total_labour_cost" },
				{ "data": "total_final_cost" },
				{ 
					"data": "Action",
					sortable: false,
					"render": function (data, type, full, meta){
						return '<span style="cursor:pointer;" class="notes_remove" alt="'+full.chk_val+'"><img src="<?=$frontEndURL;?>/admin/images/del.gif" ></span><i class="fas fa-sync-alt fa-spin" style="display:none;" id="delete_loading_notes_'+full.chk_val+'"></i><i class="fa fa-check text-success" style="display:none;" id="delete_notes_done'+full.chk_val+'"></i>';
					}
				},
				
			],
			
			"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");
            $("#delete_loading_notes_"+notes_id).show();
            var form_data = {'notes_id': notes_id};
            $.ajax({
                async: true,
                type: "POST",
                url: "<?php echo $siteURL?>/modules/daynmic_product_management/index.php?page=ajax_actions&action=delete_job_notes",
                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);
                    }
                }
            });
        }
    }); 

	
});
</script>