<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);
if($_SERVER['HTTP_HOST'] =="localhost" || $_SERVER['HTTP_HOST'] =="localhost:81"){
	$servername = "localhost";
	$username = "root";
	$password = "";
	$dbname = "griffith";
}else{
	$servername = "localhost";
	$username = "demo8_griffith_user";
	$password = "r2_,.c=+xkRc";
	$dbname = "demo8_griffith-elder";
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
			
if($_POST["update"]){
	$id=$_POST["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];
		$product_cost = $_POST["product_cost"][$i];
		$product_labour_cost = $_POST["product_labour_cost"][$i];
		$sql="update product_name set group_code='".$group_code."',group_name='".$group_name."',cost='".$product_cost."',labour_cost='".$product_labour_cost."',qty='".$qty."' where id='".$id."'";
		mysqli_query($conn,$sql);
		if(count($_POST["chk"])>0){
			$sql="delete from product_link where parent_id='".$id."' and child_id not in (".implode(",",$_POST["chk"]).")";
			//echo "<br/>".$sql;
			mysqli_query($conn,$sql);
			for($j=0;$j<count($_POST["chk"]);$j=$j+1){
				$sql="select * from product_link where parent_id='".$id."' and child_id='".$_POST["chk"][$j]."'";
				//echo "<br/>".$sql;
				$res1=mysqli_query($conn,$sql);
				if(mysqli_num_rows($res1)<=0){
					$sql="insert into product_link set parent_id='".$id."', child_id='".$_POST["chk"][$j]."'";
					//echo "<br/>".$sql;
					mysqli_query($conn,$sql);
				}
			}
		}else{
			$sql="delete from product_link where parent_id='".$id."'";
			//echo "<br/>".$sql;
			mysqli_query($conn,$sql);
		}
		//var_dump($_POST);
		
		
	}
	echo "Details Updated Sucessfully";
	header("location: edit.php");
	exit();
}
?>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript" charset="utf8" src="js/bootstrap-treeview.min.js"></script>
<link rel="stylesheet" href="css/bootstrap-treeview.min.css" />
<script type="text/javascript" charset="utf8" src="js/bootstrap-treeview.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"/> 
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script> 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
<script src="<?php echo $siteURL ?>js/select2.full.min.js"></script>
<link rel="stylesheet" href="css/select2.min.css"/>
    

<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>

</head>
<body>
<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:85%;">
    <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>
	<h1>Edit Group Structure</h1>
<form method="post">
	<table style="width:100%">
		<tr><td colspan="10" style="text-align:left;padding:5px;">
			Select Group : 
			<select id="group_code_search" name="group_code_search" class="form-control select2" required style="width:50%">
				<option value="">Please Select</option>
				<?php
					$sql="select * from product_name order by group_name";
					$res=mysqli_query($conn,$sql);
					while($row=mysqli_fetch_array($res)){
						echo '<option value="'.$row["id"].'"';
						if($row["id"]==$_REQUEST["group_code_search"]){
							echo ' selected="selected" ';
						}
						echo '>'.$row["group_name"].'</option>';
					}
				?>
			</select>&nbsp;&nbsp;
			<input type="submit" id="edit" name="edit" value="Show Details"/>
		</td>
		
		</tr>
	</table>
</form>
<form method="post">
	<?php
		function calculate_child_cost($id){
			global $conn;
			$total_cost=0;
			$total_labour_cost=0;
			
			$stack=array();
			$stack[]=$id;
			while(count($stack)>0){
				$id=$stack[0];
				array_splice($stack, 0, 1);
				$sql="select * from product_name where id='".$id."'";
				$res=mysqli_query($conn,$sql);
				$row=mysqli_fetch_assoc($res);
				$total_cost=$total_cost + ($row["cost"] * $row["qty"]);
				$total_labour_cost=$total_labour_cost + ($row["labour_cost"] * 1);
				$sql="select * from product_link where parent_id='".$id."'";
				$res=mysqli_query($conn,$sql);
				while($row=mysqli_fetch_assoc($res)){
					$stack[]=$row["child_id"];
				}
				
			}
			
			return array($total_cost,$total_labour_cost);
		}
		
		echo '<input type="hidden" id="id" name="id" value="'.$_REQUEST["group_code_search"].'"/>';

		if($_POST["edit"]){
			$id=$_REQUEST["group_code_search"];
			$sql="select * from product_name where id='".$id."'";
			$res=mysqli_query($conn,$sql);
			$row=mysqli_fetch_assoc($res);
			$child_cost=calculate_child_cost($row["id"]);
	?>
			<table style="width:100%" id="product_list">
				<tr>
					<td style="text-align:left;padding:5px;width:10%">Group Code : <br/><input type="text" id="group_code" name="group_code[]" value="<?php echo $row["group_code"];?>" required/></td>
					<td style="text-align:left;padding:5px;width:10%;">Group Name : <br/><input type="text" id="group_name" name="group_name[]" value="<?php echo $row["group_name"];?>" required/></td>
					<td style="text-align:left;padding:5px;width:10%;">Quantity : <br/><input type="number" id="qty" name="qty[]" min="1" value="<?php echo $row["qty"];?>" required/></td>
					<td style="text-align:left;padding:5px;width:10%;">Cost : <br/><input type="number" id="product_cost" name="product_cost[]" min="0" value="<?php echo $row["cost"];?>"  required/></td>
					<td style="text-align:left;padding:5px;width:10%;">Labour Cost : <br/><input type="number" id="product_labour_cost" name="product_labour_cost[]" min="0" value="<?php echo $row["labour_cost"];?>" required/></td>
					<td style="text-align:left;padding:5px;width:10%;">Total Cost : <br/><input type="number" id="total_product_cost" name="total_product_cost[]" min="0" value="<?php echo $child_cost[0];?>" readonly="readonly"/></td>
					<td style="text-align:left;padding:5px;width:10%;">Total Labour Cost : <br/><input type="number" id="total_labour_cost" name="total_labour_cost[]" min="0" value="<?php echo $child_cost[1];?>" readonly="readonly"/></td>
					<td style="width:10%;"></td>
				</tr>
			</table>
			<br/>
			<table style="width:100%">
				<tr>
					<td>
						<!--<button type="button" value="Add New Product" onclick="add_new_product_list();" />Add New Product</button>-->
						<button type="submit" name="update" value="updatedetails" onclick="validate_form();" />Update Product</button>
					</td>
				</tr>
			</table>
			<br/>
			<table id="group_details">
				<thead> 
					<tr> 
						<th></th>
						<th>Group Code</th> 
						<th>Group Name</th> 
						<th>Quantity</th> 
						<th>Cost</th>
						<th>Labour Cost</th>
						<th>Total Cost</th>
						<th>Total Labour Cost</th>
					</tr> 
				</thead> 	
			</table>	
	<?php
		}
	?>
</form>
</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.length!=0){
				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();
}

$(document).on('change', '.group_checkbox', function() {
    var parent_id=document.getElementById("id").value;
	var child_id=$(this).val();
	var id=document.getElementById("id").value;
	if($(this)[0].checked){
		$.ajax({
			url: "ajax.php?action=get_cyclic_status&parent_id="+parent_id+"&child_id="+child_id,
			method:"POST",
			success: function(data)  
			{
				var resultObj = jQuery.parseJSON(data);    
				if(resultObj.status=="sucess"){
				   if(resultObj.result=="0"){
						update_total_cost();
				   }else{
						alert("Creating link will create become cyclic");
						$(this)[0].checked=false;
				   }
				}else{
					alert("Unable To Process");
				}
			},
			error :function(jqXHR, textStatus, errorThrown)
			{
				alert("something went wrong");
			}   
		});
	}
	
});
$(document).on('change', '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 style="text-align:left;padding:5px;">Group Code : <br/><input type="text" id="group_code" name="group_code[]" value=""/></td>';
	newrow=newrow+'<td style="text-align:left;padding:5px;">Group Name : <br/><input type="text" id="group_name" name="group_name[]" value=""/></td>';
	newrow=newrow+'<td style="text-align:left;padding:5px;">Quantity : <br/><input type="number" id="qty" name="qty[]" min="1" value="" required/></td>';
	newrow=newrow+'<td style="text-align:left;padding:5px;">Cost : <br/><input type="number" id="product_cost" name="product_cost[]" min="0" value="" required/></td>';
	newrow=newrow+'<td style="text-align:left;padding:5px;">Labour Cost : <br/><input type="number" id="product_labour_cost" name="product_labour_cost[]" min="0" value="" required/></td>';
	newrow=newrow+'<td style="text-align:left;padding:5px;">Total Cost : <br/><input type="number" id="total_product_cost" name="total_product_cost[]" min="0" value="" readonly="readonly"/></td>';
	newrow=newrow+'<td style="text-align:left;padding:5px;">Total Labour Cost : <br/><input type="number" id="total_labour_cost" name="total_labour_cost[]" min="0" value="" readonly="readonly"/></td>';
	newrow=newrow+'<td style="text-align:left;padding:5px;"><a href="#" onclick="return deltblrow(this)">Del</a></td>';
	newrow=newrow+'</tr>';
	$(tbl).find('tbody').append(newrow);
}
function create_product_tree(){
	$.ajax({ 
		url: "ajax.php?action=get_group_list",
		method:"POST",
		dataType: "json",       
		success: function(data)  
		{
			$('#product_tree').treeview({
                data: data,
                levels: 1,
                collapseIcon: "fa fa-angle-down",
                expandIcon: "fa fa-angle-right",
                nodeIcon: "fa fa-folder",
                backColor: 'white',
                showBorder: false,
                enableLinks: true,
                preventUnselect: false,
                selectedBackColor: 'lightgray',
                showTags: false,
                color:'black'
			});
        },
		error :function(jqXHR, textStatus, errorThrown)
		{
			alert("something went wrong");
        }   
    });
}

function create_group_tree(id){
	$.ajax({ 
		url: "ajax.php?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");
        }   
    });
}
$( document ).ready(function() {
	var id=document.getElementById("id").value;
	$('#group_code_search').select2();
	//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': 'ajax.php?action=get_group_details&page=edit&id='+id,
			/*'data': {
			   'customer_id': '<?php echo $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"
		}
	  ],
	  "columns": [
				{ 
					"data": "Action",
					sortable: false,
					"render": function (data, type, full, meta){
						var chk='<input type="checkbox" class="group_checkbox" name="chk[]" value="'+full.chk_val+'"';
						if(full.checked_status!=0){
							chk=chk+' checked="checked" ';
						}
						if(full.cycle_status==1){
							chk=chk+' disabled="disabled" ';
						}
						chk=chk+'/>';
						return chk;
						if(full.checked_status==0){
							return '<input type="checkbox" class="group_checkbox" name="chk[]" value="'+full.chk_val+'"/>';
						}else{
							return '<input type="checkbox" class="group_checkbox" name="chk[]" value="'+full.chk_val+'" checked="checked"/>';
						}
						/*if(full.chk_val=='<?php echo $id;?>'){
							return '';
						}else{
							if(full.cycle_status==0){
								if(full.checked_status==0){
									return '<input type="checkbox" class="group_checkbox" name="chk[]" value="'+full.chk_val+'"/>';
								}else{
									return '<input type="checkbox" class="group_checkbox" name="chk[]" value="'+full.chk_val+'" checked="checked"/>';
								}
							}else{
								return '<input type="checkbox" class="group_checkbox" name="chk[]" value="'+full.chk_val+'"/>';
							}
						}*/
					}
				},
				{ "data": "group_code" },
				{ "data": "group_name" },
				{ "data": "qty" },
				{ "data": "cost" },
				{ "data": "labour_cost" },
				{ "data": "total_cost" },
				{ "data": "total_labour_cost" },
				/*{
					"data": "Action",
					sortable: false,
					 "render": function ( data, type, full, meta ){
						 var buttonID = full.Action;
						 //return '<span style="cursor:pointer;" data-toggle="modal" data-backdrop="static"  data-target="#myModalAjax" class="post_out_edit" alt="'+buttonID+'"><i class="fa fa-edit" style="font-size:20px;"></i></span>';
						var action_btn="";
						action_btn=action_btn+'<div class="btn-group"><a href="index?page=project_details&project_id='+buttonID+'&customer_id=<?php echo $id;?>" class="btn btn-warning">View</a>';
						action_btn=action_btn+'<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-expanded="false">';
						action_btn=action_btn+'<span class="caret"></span>';
						action_btn=action_btn+'<span class="sr-only">Toggle Dropdown</span>';
						action_btn=action_btn+'</button>';
						action_btn=action_btn+'<ul class="dropdown-menu" role="menu">';
						action_btn=action_btn+'<li><a href="index?page=project_details&project_id='+buttonID+'&customer_id=<?php echo $id;?>">View</a></li>';
						action_btn=action_btn+'<li><a href="index?page=project&action=edit&project_id='+buttonID+'&customer_id=<?php echo $id;?>&from_source=customer_record">Edit</a></li>';
						<?php
							if($_SESSION['group_id']=="3"){
						?>
							action_btn=action_btn+'<li><a href="#" onclick="return archive_project('+full.quotation_client_id+')">Delete</a></li>';
						<?php	
							}
						?>
						action_btn=action_btn+'</ul>';
						action_btn=action_btn+'</div>';
						return action_btn;
						}
				},*/
				
			],
			
			"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']],
	  
	});

});
</script>


<?php
$conn->close(); 
?>