<?php
include 'connect/cms-config.php' ;
include 'requires/function.php' ;
include 'requires/session.php' ;

// include the class
include 'requires/class_resize.php' ;

// keep parameter in value
$page = escapeString($_GET['page']) ;
$page_mode = escapeString($_GET['page_mode']) ;
$type = escapeString($_GET['type']) ;
$type = ( empty($type) ? "A" : $type ) ;
$search = escapeString($_GET['search']) ;
$search_category = escapeString($_GET['search_category']) ;
$store = escapeString($_GET['store']) ;

$current_date = date("Y-m-d H:i:s", time());

$array_data =[];

$group_number = 2;
LIMIT = 30;

// page setting
$active_main_menu = "hr";
$active_sub_menu = "org-chart";

switch ($page_mode) {
	case 'edit_chart':

		//update chart
		if ($_POST['hide'] == "2" && $_POST['action'] == "update"){

			$add 	= escapeString($_POST['add']);
			$remove = escapeString($_POST['remove']);

			if ( isset($_POST['add']) && $add >= 0 ){
				$mysqli->query("INSERT INTO system_orgChart (chart_parent, created_at, updated_at, chartTitle_id) VALUES ('".$add."', '".$current_date."', '".$current_date."', '".$page."')");
			}

			if ( isset($_POST['remove']) && $remove > 0 ){
				$mysqli->query("UPDATE system_orgChart set chart_trash = '1' where chart_id = '".$remove."'");
			}
		}

		// udpate time
		if ($_POST['hide'] == "1" && $_POST['action'] == "edit"){

			$name 		= ($_POST['name']);
			$start 		= ($_POST['start']);
			$end 		= ($_POST['end']);
			$trash 		= ($_POST['trash']);
			$new_name 	= ($_POST['new_name']);
			$new_start 	= ($_POST['new_start']);
			$new_end 	= ($_POST['new_end']);
			$new_trash 	= ($_POST['new_trash']);

			$temp = [];
			foreach ($name as $k => $v) {
				$temp[0][] = 	"When ".$k." Then '".$name[$k]."'";
				$temp[1][] = 	"When ".$k." Then '".$start[$k]."'";
				$temp[2][] = 	"When ".$k." Then '".$end[$k]."'";
				$temp[3][] = 	"When ".$k." Then '".(!empty($trash[$k]) ? "1" : "0")."'";	
				$temp[4][] = 	$k;
			}
			$mysqli->query("UPDATE system_chartTime SET 
							time_name = CASE time_id ".implode(",", $temp[0]). " END,
							time_start = CASE time_id ".implode(",", $temp[1]). " END,
							time_end = CASE time_id ".implode(",", $temp[2]). " END,
							time_trash = CASE time_id ".implode(",", $temp[3]). " END
							WHERE time_id IN (".implode(",", $temp[4]).") ");



			$temp = [];
			foreach ($new_name as $k => $v) {
				$temp[] = 	'( "'.$new_name[$k].'", "'.$new_start[$k].'", "'.$new_end[$k].'", "'.$page.'" )';
			}
			$mysqli->query("INSERT INTO system_chartTime (time_name, time_start, time_end, time_chart) VALUES ".implode(",", $temp));
			

		}


		// all data
		$data[]		= ["Name",'Parent'];
		$chart 		= [];

		// array for seaching query
		$staff_list = [];

		//parent_list
		$parent = [];

		// default parameter
		$title_name  = '';		
		$group_title = [];

		$query = $mysqli->query("SELECT a.chart_id, a.staff_id, a.chart_parent, b.group_id, c.chart_title, c.chart_group, a.type, a.remark,c.group_title
								from system_orgChart a
								 LEFT JOIN (SELECT * FROM system_formula  WHERE formula_group = '".$type."') b on (a.chart_id = b.chart_id) 
								 LEFT JOIN system_chartTitle c on ( a.chartTitle_id = c.chartTitle_id )
								 where a.chartTitle_id = '".$page."' AND a.chart_trash = '0' ");
		if ( $query->num_rows > 0 ){
			while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
				$chart[$row['chart_parent']][] = [
					"staff_id" => $row['staff_id'],
					"parent"   => $row['chart_parent'],
					"id"   	   => $row['chart_id'],
					"group_id" => $row['group_id'],
					"type" 	   => $row['type'],
					"remark"   => $row['remark'],
				];
				$group_title = json_decode( $row['group_title'] , true );
				$title_name = $row['chart_title'];
				$staff_list[$row['staff_id']] = $row['staff_id'];
				$parent[] = $row['chart_parent'];				
			}
			$query = $mysqli->query("SELECT staff_id, staff_idno, staff_image, staff_name from staff where (staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00') AND deleted_at IS NULL ");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$staff_list[$row['staff_id']] = [
						"staff_idno" 		=> $row['staff_idno'],
						"image"   			=> $row['staff_image'],
						"name"   			=> $row['staff_name'],
					];
				}
			}

			//get working hours
			$working_hours = [];
			$query = $mysqli->query("SELECT group_id, group_name FROM setting_working_group WHERE deleted_at IS NULL ORDER BY group_id ");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$working_hours[$row['group_id']] = [
						"name"   			=> $row['group_name'],			
					];
				}
			}
		}else{
			$query = $mysqli->query("SELECT chart_title FROM system_chartTitle 
								 where chartTitle_id = '".$page."' AND chart_trash = '0'");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$title_name = $row['chart_title'];
				}
			}
		}

			

		if ( arrayCheck($chart) ){
			foreach ($chart as $k => $v) {
				foreach ($v as $k1 => $v1) {
					$image = '';
					$content = '<option value="" file="" place="'.$v1['id'].'">Select</option>';
					foreach ($staff_list as $k2 => $v2) {
						$selected = "";
						if ($v1['staff_id'] > 0 ){
							if ($v1['staff_id'] == $k2){
								$selected = "selected";
								$image 	  = $v2['image'];
							}
						}
						
						$content .= '<option value = "'.$k2.'" '.$selected.' file="'.$v2['image'].'" place="'.$v1['id'].'">'.$v2['staff_idno'].'</option>';
					}

					$content_working = '<option value="" place="'.$v1['id'].'">Select</option>';
					foreach ($working_hours as $k2 => $v2) {
						$selected = "";
						if ($v1['group_id'] > 0 ){
							if ($v1['group_id'] == $k2){
								$selected = "selected";
							}
						}
						
						$content_working .= '<option value = "'.$k2.'" '.$selected.' place="'.$v1['id'].'">'.$v2['name'].'</option>';
					}
					$data[] = 	[
									[
										"v" => "child_node_".$v1['id'],
										"f" => '<div style="position:relative" >
													<a href="#" class="exchange" name="'.$v1['id'].'"><i class="fa fa-exchange"></i></a>
													'.(in_array($v1['id'], $parent) ? '' : '
													<button class="remove-button" name="remove" value="'.$v1['id'].'"><i class="fa fa-times"></i></button>').'
													<button class="add-button" name="add" value="'.$v1['id'].'"><i class="fa fa-plus"></i></button>
													<div class="option '.( $v1['type'] == "staff" || empty($v1['type']) ? "" : "hide" ).'">
														<img class="lazy_load_img img_staff" src="'.PATH.(empty($image) ? "images/NoProduct.jpg":"uploads/Staff/".$image).'"/><br/>
														<select class="select2-basic-single staff_list">
															'.$content.'
														</select>
														<br/>
														<select class="select2-basic-single working_list" style="margin-top: -20px;">
															'.$content_working.'
														</select><br/>
														<a href="#" class="update_group">Update Now <i class="fa fa-edit"></i></a>
													</div>	
													<div class="remark '.( $v1['type'] == "remark" ? "" : "hide" ).'">
														<input type="text" name="'.$v1['id'].'" class="remark_input" placeholder="Remark" value="'.$v1['remark'].'"/>
													</div>
												</div>
												',
									],
									( $k == 0 ? "" : "child_node_".$v1['parent'] ),
								];
					
								
				}
			}
		}else{
			$data[] = [
				[
					"v" => "child_node_".$v1['id'],
					"f" => '<div style="position:relative">
								New<br/>
								<button class="add-button" name="add" value="0"><i class="fa fa-plus"></i></button>
								</select>
							</div>',
				],
				( $k == 0 ? "" : "child_node_".$v1['parent'] ),
			];
		}
		


		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>

		<style type="text/css">
			.add-button{
				position: absolute;
			    bottom: -17px;
			    left: 45%;
			    border: 0;
			    background: none;
			    cursor: pointer;
			}
			.remove-button{
			    position: absolute;
			    top: -10px;
		    	right: -3%;
			    background: red;
			    border: 1px solid #000;
			    border-radius: 10px;
			    color: #fff;
			    font-size: 7px;
			}
			.google-visualization-orgchart-node{
				border: 0;
			}

			.img_staff{
				object-fit: cover;
				max-width: 40px;
				max-height: 40px;
				width: 100%;
				min-width: 40px;
			}
			.select2-selection{
				min-width: 250px;
				max-width: 250px;
				font-size: 14px;
			}
			.select2-container--default .select2-selection--single{
				padding: 0;
				margin: 0 auto;
			}
			.google-visualization-orgchart-table *{
				padding-bottom: 0;
			}
			.select2-selection--single{
				margin-top: -20px!important;
			}
			.select2-selection__arrow{
				padding: 0;
    			top: -6px;
			}
			.page_loader{
				z-index: 1000;
			    position: absolute;
			    width: 100%;
			    height: 100%;
			    object-fit: contain;
			    background: white;
			    opacity: 50%;
			    display: none;
			}
			.page_loader img{
				object-fit: contain;
			    position: absolute;
			    top: 50%;
			    left: 50%;
			}
			#chart_div{
			    min-height: 500px;
			    padding-bottom: 20px;
			}
			.hide{
				display: none;
			}

		</style>
		<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

		<script type="text/javascript">
		function drawChart(array) {
		    var data = new google.visualization.arrayToDataTable(array, false);
		    var chart = new google.visualization.OrgChart(document.querySelector('#chart_div'));
		    chart.draw(data, {allowHtml: true});
		    $('.select2-basic-single').select2();
		}

		google.load('visualization', '1', {packages:['orgchart'], callback: function(){drawChart(<?= json_encode($data) ?>);}});		

		</script>
		<div class="warper container-fluid"> 
			<div class="page-header"><h1><?=$lang['Organization Chart']?><small><?=$lang['Chart']?></small></h1></div>			
			<div class="panel panel-default">
				<div class="panel-body">					
					<form method="post" class="form-horizontal" id="quotationForm" enctype="multipart/form-data" novalidate="novalidate">
						<div class="form-group">
		                    <div class="col-sm-2 control-label"></div>
		                    <div class="col-sm-9">
		                    	<?php
							   		$letter = "A";
									for ($i = 0 ; $i < $group_number ; $i++ ){
										echo '<a style="margin: 0 5px;" href="org_chart.php?page_mode='.$page_mode.'&page='.$page.'&type='.$letter.'" class="btn btn-purple '.($letter == $type ? "active" : '').'" >'.( !empty( $group_title[$letter] ) ? $group_title[$letter] : 'Group '.$letter ).'</a>';
										$letter++;
									}
								?>
		                    </div>
		                </div>
						<div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['title']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="<?=$title_name?>">
		                    </div>
		                </div>		                
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['Group']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="Group <?=$type?>">
		                    </div>
		                </div>
					</form>
				</div>
			</div>
			<div class="panel panel-default">
				<div class="panel-body">
					
					<form method="post" style="overflow: auto;position: relative;">
						<div class="page_loader">
							<img src="<?=PATH?>/images/fancybox_loading.gif"/>
						</div> 
						<br/>
						<div class="result_success display_none">
			                <?= $lang['Thank you details has been updated'] ?>
			            </div>
						<div id="chart_div"></div>
						<input type="hidden" name="hide" value="2">
						<input type="hidden" name="action" value="update">
					</form>
				</div>
			</div>
		</div>

		<script type="text/javascript">
			$(document).on("change", ".staff_list", function(){
				//console.log(this);
				var value = $(this).find("option:selected").attr('place'),
					staff_id = $(this).find("option:selected").val(),
					file = $(this).find("option:selected").attr("file"),
					select_this = this;

				$.ajax({
					type: "POST",
					url : "requires/ajax_chart.php",
					// async: false,
					dataType: 'json',
					data: {"place" : value , "staff_id" : staff_id , "type" : "staff"},
					success:function(data){
						if (data['result'] == "success"){
							//console.log(file);
							$(select_this).parent().find("img").attr("src", "<?=PATH?>" + ( file == '' ? "images/NoProduct.jpg":"uploads/Staff/"+file ));
						}else{
							location.reload();
						}
					}
				});
			});

			$(document).on("change", ".working_list", function(){
				//console.log(this);
				var value = $(this).find("option:selected").attr('place'),
					group_id = $(this).find("option:selected").val(),
					select_this = this;

				$.ajax({
					type: "POST",
					url : "requires/ajax_chart.php",
					// async: false,
					dataType: 'json',
					data: {"place" : value , "group_id" : group_id, "type" : "working_hours", "formula_group" : '<?= $type ?>'},
					success:function(data){
						if (data['result'] == "success"){
						}else{
							location.reload();
						}
					}
				});
			});

			$(document).on("click", ".update_group", function(){
				//console.log(this);
				var staff_id = $(this).parent().find(".staff_list").find("option:selected").val(),
					group_id = $(this).parent().find(".working_list").find("option:selected").val(),
					select_this = this;

				$.ajax({
					type: "POST",
					url : "requires/ajax_chart.php",
					dataType: 'json',
					data: {"staff_id" : staff_id , "group_id" : group_id, "type" : "staff_update"},
					success:function(data){
						if (data['result'] == "success"){
							// $(".display_none").
							$(".display_none.result_success ").fadeIn().delay(1000).fadeOut();
						}else{
							location.reload();
						}
					}
				});
			});

			$(document).on("click", ".exchange", function(){
				var type = '', group_id = '';
				group_id = $(this).attr("name");
				if ( $(this).parent().find(".option.hide").length > 0 ){
					$(this).parent().find(".option.hide").removeClass('hide');
					$(this).parent().find(".remark").addClass('hide');
					//$(this).parent().find("select").val('').trigger("change");
					type = "staff";

				}else{
					$(this).parent().find(".option").addClass('hide');
					$(this).parent().find(".remark").removeClass('hide');
					//$(this).parent().find(".remark_input").val('');
					type = "remark";
				}	

				$.ajax({
					type: "POST",
					url : "requires/ajax_chart.php",
					dataType: 'json',
					data: {"group_id" : group_id, "type" : "update_type", "exchange" : type},
					success:function(data){
						location.reload();
						if (data['result'] == "success"){
							//$(".display_none.result_success ").fadeIn().delay(1000).fadeOut();
						}else{
						//	location.reload();
						}
					}
				});	
			});
			$(document).on("blur", ".remark_input", function(){
				var type = '', group_id = '';
				group_id = $(this).attr("name");
				$.ajax({
					type: "POST",
					url : "requires/ajax_chart.php",
					dataType: 'json',
					data: {"group_id" : group_id, "type" : "remark_update", "remark" : $(this).val()},
					success:function(data){
						//location.reload();
						if (data['result'] == "success"){
							//$(".display_none.result_success ").fadeIn().delay(1000).fadeOut();
						}else{
							location.reload();
						}
					}
				});	
			});
		</script>
		<script type="text/javascript">
			$(document).ajaxStart(function() {
			  $(".page_loader").fadeIn();
			}).ajaxStop(function() {
			  $(".page_loader").fadeOut();
			});
		</script>

		<script src="/scripts/timepicker.js"></script>
		<?php
		break;

	case 'change_group':		

		//udpate time
		if ($_POST['hide'] == "1" && $_POST['action'] == "insert"){

			$date = $_POST['date'];

			$temp = [];
			$old_staff = [] ;
			foreach ($date as $k => $v) {
				$temp[] = " ('".explode("-", $k)[0]."', '".explode("-", $k)[1]."', '".date("Y-m-d", strtotime($v))."', '".$current_date."', '".$_SESSION['system_id']."') ";
				$old_chart[] = explode("-", $k)[0];
			}		

			// start commits
			$error      = 0 ;

			if (!$mysqli->query("UPDATE system_record_chart SET record_trash = '1' where chart_id IN (".implode(",", $old_chart).")") ){
				$error ++;
			}
			
			if (!$mysqli->query("UPDATE system_chartTitle SET chart_group = '".$type."' where chartTitle_id = '".$page."'")){
				$error ++;
			}
			if (!$mysqli->query("INSERT INTO system_record_chart (chart_id, group_id, `date`, created_at, user_id) VALUES ".implode(",", $temp))){
				$error ++;
			}
			
			if( $error == 0 ) {
			    // commit query
			    $mysqli->commit() ; 
			   	$status  = '200' ;
				$message = 'Process Successful.' ;

			}else{
				$data = $error;
				$status  = '216' ;
				$message = 'Error Occur' ;
			    $mysqli->rollback() ;
			}

			if ( $status == '200' ){
				$_SESSION['result'] = "success";
			}else{
				$_SESSION['result'] = "failed";
			}

		}


		// all data
		$data[]		= ["Name",'Parent'];
		$chart 		= [];

		// array for seaching query
		$staff_list = [];

		//parent_list
		$parent = [];

		// default parameter
		$title_name = '';
		$chart_group = '';
		$group_title = [];

		$query = $mysqli->query("SELECT a.chart_id, a.staff_id, a.chart_parent, b.group_id, c.chart_title, c.chart_group, d.date, a.type, a.remark, c.group_title, e.date as last_Record  
								 from system_orgChart a
								 LEFT JOIN (SELECT * FROM system_formula  WHERE formula_group = '".$type."') b on (a.chart_id = b.chart_id) 
								 LEFT JOIN system_chartTitle c on ( a.chartTitle_id = c.chartTitle_id )
								 LEFT JOIN (SELECT * FROM system_record_chart WHERE record_trash = '0') d on ( a.chart_id = d.chart_id)
								 LEFT JOIN (SELECT * FROM system_record_chart WHERE record_trash = '1') e on ( a.chart_id = e.chart_id)
								 where a.chartTitle_id = '".$page."' AND a.chart_trash = '0'");
		if ( $query->num_rows > 0 ){
			while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
				$chart[$row['chart_parent']][] = [
					"staff_id" => $row['staff_id'],
					"parent"   => $row['chart_parent'],
					"id"   	   => $row['chart_id'],
					"group_id" => $row['group_id'],
					"date" 	   => $row['date'],
					"last_modified" => $row['last_Record'],
					"type" 	   => $row['type'],
					"remark"   => $row['remark'],
				];		


				$group_title = json_decode( $row['group_title'], true );
				$chart_group = $row['chart_group'];
				$staff_list[$row['staff_id']] = $row['staff_id'];
				$title_name = $row['chart_title'];
			}
			$query = $mysqli->query("SELECT staff_id, staff_idno, staff_image, staff_name from staff where (staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00') AND deleted_at IS NULL");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$staff_list[$row['staff_id']] = [
						"staff_idno" 		=> $row['staff_idno'],
						"image"   			=> $row['staff_image'],
						"name"   			=> $row['staff_name'],
					];
				}
			}

			//get working hours
			$working_hours = [];
			$query = $mysqli->query("SELECT group_id, group_name FROM setting_working_group WHERE deleted_at IS NULL ORDER BY group_id ");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$working_hours[$row['group_id']] = [
						"name"   			=> $row['group_name'],			
					];
				}
			}	
		}else{
			$query = $mysqli->query("SELECT chart_title FROM system_chartTitle 
								 where chartTitle_id = '".$page."' AND chart_trash = '0'");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$title_name = $row['chart_title'];
				}
			}
		}

		

		if ( arrayCheck($chart) ){
			foreach ($chart as $k => $v) {
				foreach ($v as $k1 => $v1) {
					$data[] = 	[
									[
										"v" => "child_node_".$v1['id'],
										"f" => '<div style="position:relative">	
													<div class="option '.( $v1['type'] == "staff" || empty($v1['type']) ? "" : "hide" ).'">	
														<img class="lazy_load_img img_staff" src="'.PATH.(empty($staff_list[$v1['staff_id']]['image'] ) ? "images/NoProduct.jpg":"uploads/Staff/".$staff_list[$v1['staff_id']]['image'] ).'"/><br/>
														'.dataFilterDash($staff_list[$v1['staff_id']]['staff_idno']).'													
														<br/>
														'.dataFilterDash($working_hours[$v1['group_id']]['name']).'														
														<br/>
														'.( $v1['type'] == "staff" || empty($v1['type']) ? '<input min="'.date("Y-m-d",strtotime("+ 1 day", strtotime($current_date))).'" type="date" name="date['.$v1['id'].'-'.$v1['group_id'].']" value="'.(!empty($v1['date']) ? date("Y-m-d", strtotime($v1['date'])) : '').'" required class="form-control check_value2" >' : '').'
														'.( !empty($v1['last_modified']) ? '<div class="text-left"><span>Last Modified: '.date("Y-m-d", strtotime($v1['last_modified']))."</span></div>" : '').'
													</div>
													<div class="remark '.( $v1['type'] == "remark" ? "" : "hide" ).'">
														'.dataFilterDash($v1['remark']).'
													</div>

												</div>',
									],
									( $k == 0 ? "" : "child_node_".$v1['parent'] ),
								];
					
								
				}
			}
		}else{
			$data[] = [
						[
							"v" => "child_node_".$v1['id'],
							"f" => '<div style="position:relative">
										No Data<br/>										
									</div>',
						],
						( $k == 0 ? "" : "child_node_".$v1['parent'] ),
					];
		}
		


		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>

		<style type="text/css">
			.add-button{
				position: absolute;
			    bottom: -17px;
			    left: 45%;
			    border: 0;
			    background: none;
			    cursor: pointer;
			}
			.remove-button{
			    position: absolute;
			    top: -10px;
		    	right: -3%;
			    background: red;
			    border: 1px solid #000;
			    border-radius: 10px;
			    color: #fff;
			    font-size: 7px;
			}
			.google-visualization-orgchart-node{
				border: 0;
			}

			.img_staff{
				object-fit: cover;
				max-width: 40px;
				max-height: 40px;
				width: 100%;
				min-width: 40px;
			}
			.select2-selection{
				min-width: 250px;
				max-width: 250px;
				font-size: 14px;
			}
			.select2-container--default .select2-selection--single{
				padding: 0;
				margin: 0 auto;
			}
			.google-visualization-orgchart-table *{
				padding-bottom: 0;
			}
			.select2-selection--single{
				margin-top: -20px!important;
			}
			.select2-selection__arrow{
				padding: 0;
    			top: -6px;
			}
			.page_loader{
				z-index: 1000;
			    position: absolute;
			    width: 100%;
			    height: 100%;
			    object-fit: contain;
			    background: white;
			    opacity: 50%;
			    display: none;
			}
			.page_loader img{
				object-fit: contain;
			    position: absolute;
			    top: 50%;
			    left: 50%;
			}
			#chart_div{
			    min-height: 500px;
			    padding-bottom: 20px;
			}
			.google-visualization-orgchart-node{
				font-size: 15px;
			}

		</style>
		<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

		<script type="text/javascript">
		function drawChart(array) {
		    var data = new google.visualization.arrayToDataTable(array, false);
		    var chart = new google.visualization.OrgChart(document.querySelector('#chart_div'));
		    chart.draw(data, {allowHtml: true});
		    $('.select2-basic-single').select2();
		}

		google.load('visualization', '1', {packages:['orgchart'], callback: function(){drawChart(<?= json_encode($data) ?>);}});		
		</script>
		<div class="warper container-fluid"> 
			<div class="page-header"><h1><?=$lang['Organization Chart']?><small><?=$lang['Chart']?></small></h1></div>
			<?php
				if ( !empty($_SESSION['result']) ){
					switch ($_SESSION['result']) {
						case 'success':
							echo '<div class="result_success">
				                    '.$lang['Thank you details has been updated'].'
				                </div>';
							break;
						case 'failed':
							echo '<div class="result_error">
				                    '.$lang['Sorry something error'].'
				                </div>';
							break;
						default:
							# code...
							break;
					}
					unset( $_SESSION['result'] );
				}
			?>
			<div class="panel panel-default">
				<div class="panel-body">					
					<form method="post" class="form-horizontal" id="quotationForm" enctype="multipart/form-data" novalidate="novalidate">
						<div class="form-group">
		                    <div class="col-sm-2 control-label"></div>
		                    <div class="col-sm-9">
		                    	<?php
							   		$letter = "A";
									for ($i = 0 ; $i < $group_number ; $i++ ){
										echo '<a style="margin: 0 5px;" href="org_chart.php?page_mode='.$page_mode.'&page='.$page.'&type='.$letter.'" class="btn btn-purple '.($letter == $type ? "active" : '').'" >'.( !empty( $group_title[$letter] ) ? $group_title[$letter] : 'Group '.$letter ).'</a>';
										$letter ++;
									}
								?>
		                    </div>
		                </div>
						<div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['title']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="<?=$title_name?>">
		                    </div>
		                </div>
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['Original Group']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="Group <?=$chart_group?>">
		                    </div>
		                </div>
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['Group']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="Group <?=$type?>">
		                    </div>
		                </div>
					</form>
				</div>
			</div>
			<div class="panel panel-default">
				<div class="panel-body">
					
					<form method="post" id="valid_form" novalidate="novalidate">						
						<div class="form-group" style="overflow: auto;position: relative;">
							<div id="chart_div"></div>
						</div>
						<div class="form-group">
							<input type="hidden" name="hide" value="1">
							<input type="hidden" name="action" value="insert">
							<?= ( arrayCheck($chart)  ?  '<input type="submit" class="btn btn-purple"  value="Submit" style="float: right;">' : '' ) ?>
						</div>			
					</form>
				</div>
			</div>
		</div>
		<?php
		break;

	case 'change_group2':		

		//udpate time
		if ($_POST['hide'] == "1" && $_POST['action'] == "insert"){

			$day = $_POST['day'];

			$temp = [];
			// $old_staff = [] ;
			// foreach ($date as $k => $v) {
			// 	$temp[] = " ('".explode("-", $k)[0]."', '".explode("-", $k)[1]."', '".date("Y-m-d", strtotime($v))."', '".$current_date."', '".$_SESSION['system_id']."') ";
			// 	$old_chart[] = explode("-", $k)[0];
			// }		

			// start commits
			$error      = 0 ;
					
			foreach ($day as $key => $value) {
				$temp[0][] = 	"When formula_id = ".$key." Then '".$value."'";	
				$temp[1][] = 	$key;
			}
			
			if (!$mysqli->query("UPDATE system_formula SET chart_day = CASE ".implode(" ", $temp[0]). " END where formula_id IN (".implode(",", $temp[1]).")")){
				$error ++;
			}			
			
			if( $error == 0 ) {
			    // commit query
			    $mysqli->commit() ; 
			   	$status  = '200' ;
				$message = 'Process Successful.' ;

			}else{
				$data = $error;
				$status  = '216' ;
				$message = 'Error Occur' ;
			    $mysqli->rollback() ;
			}

			if ( $status == '200' ){
				$_SESSION['result'] = "success";
			}else{
				$_SESSION['result'] = "failed";
			}

		}


		// all data
		$data[]		= ["Name",'Parent'];
		$chart 		= [];

		// array for seaching query
		$staff_list = [];

		//parent_list
		$parent = [];

		// default parameter
		$title_name = '';
		$chart_group = '';
		$group_title = [];

		$query = $mysqli->query("SELECT a.chart_id, a.staff_id, a.chart_parent, b.group_id, c.chart_title, c.chart_group, d.date, a.type, a.remark, c.group_title, e.date as last_Record , b.chart_day, b.formula_id
								 from system_orgChart a
								 LEFT JOIN (SELECT * FROM system_formula  WHERE formula_group = '".$type."') b on (a.chart_id = b.chart_id) 
								 LEFT JOIN system_chartTitle c on ( a.chartTitle_id = c.chartTitle_id )
								 LEFT JOIN (SELECT * FROM system_record_chart WHERE record_trash = '0') d on ( a.chart_id = d.chart_id)
								 LEFT JOIN (SELECT * FROM system_record_chart WHERE record_trash = '1') e on ( a.chart_id = e.chart_id)
								 where a.chartTitle_id = '".$page."'  AND a.chart_trash = '0'");
		if ( $query->num_rows > 0 ){
			while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
				$chart[$row['chart_parent']][] = [
					"staff_id" 		=> $row['staff_id'],
					"parent"   		=> $row['chart_parent'],
					"id"   	   		=> $row['chart_id'],
					"group_id" 		=> $row['group_id'],
					"date" 	   		=> $row['date'],
					"last_modified" => $row['last_Record'],
					"day" 	   		=> $row['chart_day'],
					"type" 	   		=> $row['type'],
					"remark"   		=> $row['remark'],
					"formula_id"    => $row['formula_id'],
				];		


				$group_title = json_decode( $row['group_title'], true );
				$chart_group = $row['chart_group'];
				$staff_list[$row['staff_id']] = $row['staff_id'];
				$title_name = $row['chart_title'];
			}
			$query = $mysqli->query("SELECT staff_id, staff_idno, staff_image, staff_name from staff where (staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00') AND deleted_at IS NULL");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$staff_list[$row['staff_id']] = [
						"staff_idno" 		=> $row['staff_idno'],
						"image"   			=> $row['staff_image'],
						"name"   			=> $row['staff_name'],
					];
				}
			}

			//get working hours
			$working_hours = [];
			$query = $mysqli->query("SELECT group_id, group_name FROM setting_working_group WHERE deleted_at IS NULL ORDER BY group_id ");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$working_hours[$row['group_id']] = [
						"name"   			=> $row['group_name'],			
					];
				}
			}	
		}else{
			$query = $mysqli->query("SELECT chart_title FROM system_chartTitle 
								 where chartTitle_id = '".$page."'  AND chart_trash = '0'");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$title_name = $row['chart_title'];
				}
			}
		}

		$array_day = 	[
							1 => "Monday",
							2 => "Tuesday",
							3 => "Wednesday",
							4 => "Thursday",
							5 => "Friday",
							6 => "Saturday",
							7 => "Sunday",
						];
		

		if ( arrayCheck($chart) ){
			foreach ($chart as $k => $v) {
				foreach ($v as $k1 => $v1) {
					$day_option = '<option value="">Select</option>';
					foreach ($array_day as $key => $value) {
						$day_option .= "<option value='".$key."' ".( $key == $v1['day'] ? "selected" : '' ).">".$value."</option>";
					}
					$data[] = 	[
									[
										"v" => "child_node_".$v1['id'],
										"f" => '<div style="position:relative">	
													<div class="option '.( $v1['type'] == "staff" || empty($v1['type']) ? "" : "hide" ).'">	
														<img class="lazy_load_img img_staff" src="'.PATH.(empty($staff_list[$v1['staff_id']]['image'] ) ? "images/NoProduct.jpg":"uploads/Staff/".$staff_list[$v1['staff_id']]['image'] ).'"/><br/>
														'.dataFilterDash($staff_list[$v1['staff_id']]['staff_idno']).'													
														<br/>
														'.dataFilterDash($working_hours[$v1['group_id']]['name']).'														
														<br/>
														'.( $v1['type'] == "staff" || empty($v1['type']) ? '
															<select class="select2-basic-single form-control check_value2" name="day['.$v1['formula_id'].']">'.$day_option.'</select>' : '').'
														'.( !empty($v1['last_modified']) ? '<div class="text-left"><span>Last Modified: '.date("Y-m-d", strtotime($v1['last_modified']))."</span></div>" : '').'
													</div>
													<div class="remark '.( $v1['type'] == "remark" ? "" : "hide" ).'">
														'.dataFilterDash($v1['remark']).'
													</div>

												</div>',
									],
									( $k == 0 ? "" : "child_node_".$v1['parent'] ),
								];
					
								
				}
			}
		}else{
			$data[] = [
						[
							"v" => "child_node_".$v1['id'],
							"f" => '<div style="position:relative">
										No Data<br/>										
									</div>',
						],
						( $k == 0 ? "" : "child_node_".$v1['parent'] ),
					];
		}
		


		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>

		<style type="text/css">
			.add-button{
				position: absolute;
			    bottom: -17px;
			    left: 45%;
			    border: 0;
			    background: none;
			    cursor: pointer;
			}
			.remove-button{
			    position: absolute;
			    top: -10px;
		    	right: -3%;
			    background: red;
			    border: 1px solid #000;
			    border-radius: 10px;
			    color: #fff;
			    font-size: 7px;
			}
			.google-visualization-orgchart-node{
				border: 0;
			}

			.img_staff{
				object-fit: cover;
				max-width: 40px;
				max-height: 40px;
				width: 100%;
				min-width: 40px;
			}
			.select2-selection{
				min-width: 250px;
				max-width: 250px;
				font-size: 14px;
			}
			.select2-container--default .select2-selection--single{
				padding: 0;
				margin: 0 auto;
			}
			.google-visualization-orgchart-table *{
				padding-bottom: 0;
			}
			.select2-selection--single{
				margin-top: -20px!important;
			}
			.select2-selection__arrow{
				padding: 0;
    			top: -6px;
			}
			.page_loader{
				z-index: 1000;
			    position: absolute;
			    width: 100%;
			    height: 100%;
			    object-fit: contain;
			    background: white;
			    opacity: 50%;
			    display: none;
			}
			.page_loader img{
				object-fit: contain;
			    position: absolute;
			    top: 50%;
			    left: 50%;
			}
			#chart_div{
			    min-height: 500px;
			    padding-bottom: 20px;
			}
			.google-visualization-orgchart-node{
				font-size: 15px;
			}

		</style>
		<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

		<script type="text/javascript">
		function drawChart(array) {
		    var data = new google.visualization.arrayToDataTable(array, false);
		    var chart = new google.visualization.OrgChart(document.querySelector('#chart_div'));
		    chart.draw(data, {allowHtml: true});
		    $('.select2-basic-single').select2();
		}

		google.load('visualization', '1', {packages:['orgchart'], callback: function(){drawChart(<?= json_encode($data) ?>);}});		

		</script>
		<div class="warper container-fluid"> 
			<div class="page-header"><h1><?=$lang['Organization Chart']?><small><?=$lang['Chart']?></small></h1></div>
			<?php
				if ( !empty($_SESSION['result']) ){
					switch ($_SESSION['result']) {
						case 'success':
							echo '<div class="result_success">
				                    '.$lang['Thank you details has been updated'].'
				                </div>';
							break;
						case 'failed':
							echo '<div class="result_error">
				                    '.$lang['Sorry something error'].'
				                </div>';
							break;
						default:
							# code...
							break;
					}
					unset( $_SESSION['result'] );
				}
			?>
			<div class="panel panel-default">
				<div class="panel-body">					
					<form method="post" class="form-horizontal" id="quotationForm" enctype="multipart/form-data" novalidate="novalidate">
						<div class="form-group">
		                    <div class="col-sm-2 control-label"></div>
		                    <div class="col-sm-9">
		                    	<?php
							   		$letter = "A";
									for ($i = 0 ; $i < $group_number ; $i++ ){
										echo '<a style="margin: 0 5px;" href="org_chart.php?page_mode='.$page_mode.'&page='.$page.'&type='.$letter.'" class="btn btn-purple '.($letter == $type ? "active" : '').'" >'.( !empty( $group_title[$letter] ) ? $group_title[$letter] : 'Group '.$letter ).'</a>';
										$letter ++;
									}
								?>
		                    </div>
		                </div>
						<div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['title']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="<?=$title_name?>">
		                    </div>
		                </div>
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['Original Group']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="Group <?=$chart_group?>">
		                    </div>
		                </div>
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['Group']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="Group <?=$type?>">
		                    </div>
		                </div>
					</form>
				</div>
			</div>
			<div class="panel panel-default">
				<div class="panel-body">
					
					<form method="post" id="valid_form" novalidate="novalidate">						
						<div class="form-group" style="overflow: auto;position: relative;">
							<div id="chart_div"></div>
						</div>
						<div class="form-group">
							<input type="hidden" name="hide" value="1">
							<input type="hidden" name="action" value="insert">
							<?= ( arrayCheck($chart)  ?  '<input type="submit" class="btn btn-purple"  value="Submit" style="float: right;">' : '' ) ?>
						</div>			
					</form>
				</div>
			</div>
		</div>
		<?php
		break;
	case 'change_group3':		

		//udpate time
		if ($_POST['hide'] == "1" && $_POST['action'] == "insert"){

			$day = $_POST['day'];

			$temp = [];
			$exists = [];
			// $old_staff = [] ;
			// foreach ($date as $k => $v) {
			// 	$temp[] = " ('".explode("-", $k)[0]."', '".explode("-", $k)[1]."', '".date("Y-m-d", strtotime($v))."', '".$current_date."', '".$_SESSION['system_id']."') ";
			// 	$old_chart[] = explode("-", $k)[0];
			// }		



			// start commits
			$error      = 0 ;
			$mysqli->autocommit( false ) ;	
			$boolean = false;

			foreach ($day as $key => $value) {
				$temp[] = $key;
			}
			$query = $mysqli->query("SELECT * FROM system_chart_day WHERE chart_id IN (".implode(",", $temp).")");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC) ){
					$exists[] = $row['chart_id'];
				}
			}	

			$temp = [];
			foreach ($day as $key => $value) {
				if ( in_array($key, $exists) ){
					$temp[0][] = 	"When chart_id = ".$key." Then '".$value."'";	
					$temp[1][] = 	$key;
				}else{
					$temp[2][] = 	" ('".$key."', '".$value."', '".$_SESSION['system_id']."' ) ";	
				}
				
			}

			if ( arrayCheck($temp[0]) ){
				if (!$mysqli->query("UPDATE system_chart_day SET chart_day = CASE ".implode(" ", $temp[0]). " END where chart_id IN (".implode(",", $temp[1]).")")){
					$error ++;
				}
			}
			if ( arrayCheck($temp[2]) ){
				if (!$mysqli->query("INSERT INTO  system_chart_day ( chart_id , chart_day, updated_by ) VALUES ".implode(",", $temp[2]). "")){
					$error ++;
				}
			}
			
			if( $error == 0 ) {
			    // commit query
			    $mysqli->commit() ; 
			   	$status  = '200' ;
				$message = 'Process Successful.' ;

			}else{
				$data = $error;
				$status  = '216' ;
				$message = 'Error Occur' ;
			    $mysqli->rollback() ;
			}

			if ( $status == '200' ){
				$_SESSION['result'] = "success";
			}else{
				$_SESSION['result'] = "failed";
			}

		}


		// all data
		$data[]		= ["Name",'Parent'];
		$chart 		= [];

		// array for seaching query
		$staff_list = [];

		//parent_list
		$parent = [];

		// default parameter
		$title_name = '';
		$chart_group = '';
		$group_title = [];

		$query = $mysqli->query("SELECT b.*,a.*,c.*
								 from system_orgChart a
								 LEFT JOIN system_chart_day b ON ( b.chart_id = a.chart_id )
								 LEFT JOIN system_chartTitle c on ( a.chartTitle_id = c.chartTitle_id )								 
								 where a.chartTitle_id = '".$page."' AND a.chart_trash = '0'");		
		if ( $query->num_rows > 0 ){
			while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
				$chart[$row['chart_parent']][] = [
					"staff_id" 		=> $row['staff_id'],
					"parent"   		=> $row['chart_parent'],
					"id"   	   		=> $row['chart_id'],
					"group_id" 		=> $row['group_id'],
					"date" 	   		=> $row['date'],
					"last_modified" => $row['last_autoupdate'],
					"day" 	   		=> $row['chart_day'],
					"type" 	   		=> $row['type'],
					"remark"   		=> $row['remark'],
					"chart_id"   	=> $row['chart_id'],
				];		


				$group_title = json_decode( $row['group_title'], true );
				$chart_group = $row['chart_group'];
				$staff_list[$row['staff_id']] = $row['staff_id'];
				$title_name = $row['chart_title'];
				$type = ( !empty( $group_title[$row['chart_next_group']] ) ? $group_title[$row['chart_next_group']] : $row['chart_next_group'] );
			}
			$query = $mysqli->query("SELECT staff_id, staff_idno, staff_image, staff_name from staff where (staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00') AND deleted_at IS NULL");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$staff_list[$row['staff_id']] = [
						"staff_idno" 		=> $row['staff_idno'],
						"image"   			=> $row['staff_image'],
						"name"   			=> $row['staff_name'],
					];
				}
			}

			//get working hours
			$working_hours = [];
			$query = $mysqli->query("SELECT group_id, group_name FROM setting_working_group WHERE deleted_at IS NULL ORDER BY group_id ");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$working_hours[$row['group_id']] = [
						"name"   			=> $row['group_name'],			
					];
				}
			}	
		}else{
			$query = $mysqli->query("SELECT chart_title FROM system_chartTitle 
								 where chartTitle_id = '".$page."' AND chart_trash = '0'");
			if ( $query->num_rows > 0 ){
				while ( $row = $query->fetch_array(MYSQLI_ASSOC)){
					$title_name = $row['chart_title'];
				}
			}
		}

		$array_day = 	[
							1 => "Monday",
							2 => "Tuesday",
							3 => "Wednesday",
							4 => "Thursday",
							5 => "Friday",
							6 => "Saturday",
							7 => "Sunday",
						];
		

		if ( arrayCheck($chart) ){
			foreach ($chart as $k => $v) {
				foreach ($v as $k1 => $v1) {
					$day_option = '<option value="">Select</option>';
					foreach ($array_day as $key => $value) {
						$day_option .= "<option value='".$key."' ".( $key == $v1['day'] ? "selected" : '' ).">".$value."</option>";
					}
					$data[] = 	[
									[
										"v" => "child_node_".$v1['id'],
										"f" => '<div style="position:relative">	
													<div class="option '.( $v1['type'] == "staff" || empty($v1['type']) ? "" : "hide" ).'">	
														<img class="lazy_load_img img_staff" src="'.PATH.(empty($staff_list[$v1['staff_id']]['image'] ) ? "images/NoProduct.jpg":"uploads/Staff/".$staff_list[$v1['staff_id']]['image'] ).'"/><br/>
														'.dataFilterDash($staff_list[$v1['staff_id']]['staff_idno']).'													
																										
														<br/>
														'.( $v1['type'] == "staff" || empty($v1['type']) ? '
															<select class="select2-basic-single form-control check_value2" name="day['.$v1['chart_id'].']">'.$day_option.'</select>' : '').'
														'.( !empty($v1['last_modified']) ? '<div class="text-left"><span>Last Modified: '.date("Y-m-d", strtotime($v1['last_modified']))."</span></div>" : '').'
													</div>
													<div class="remark '.( $v1['type'] == "remark" ? "" : "hide" ).'">
														'.dataFilterDash($v1['remark']).'
													</div>

												</div>',
									],
									( $k == 0 ? "" : "child_node_".$v1['parent'] ),
								];
					
								
				}
			}
		}else{
			$data[] = [
						[
							"v" => "child_node_".$v1['id'],
							"f" => '<div style="position:relative">
										No Data<br/>										
									</div>',
						],
						( $k == 0 ? "" : "child_node_".$v1['parent'] ),
					];
		}
		


		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>

		<style type="text/css">
			.add-button{
				position: absolute;
			    bottom: -17px;
			    left: 45%;
			    border: 0;
			    background: none;
			    cursor: pointer;
			}
			.remove-button{
			    position: absolute;
			    top: -10px;
		    	right: -3%;
			    background: red;
			    border: 1px solid #000;
			    border-radius: 10px;
			    color: #fff;
			    font-size: 7px;
			}
			.google-visualization-orgchart-node{
				border: 0;
			}

			.img_staff{
				object-fit: cover;
				max-width: 40px;
				max-height: 40px;
				width: 100%;
				min-width: 40px;
			}
			.select2-selection{
				min-width: 250px;
				max-width: 250px;
				font-size: 14px;
			}
			.select2-container--default .select2-selection--single{
				padding: 0;
				margin: 0 auto;
			}
			.google-visualization-orgchart-table *{
				padding-bottom: 0;
			}
			.select2-selection--single{
				margin-top: -20px!important;
			}
			.select2-selection__arrow{
				padding: 0;
    			top: -6px;
			}
			.page_loader{
				z-index: 1000;
			    position: absolute;
			    width: 100%;
			    height: 100%;
			    object-fit: contain;
			    background: white;
			    opacity: 50%;
			    display: none;
			}
			.page_loader img{
				object-fit: contain;
			    position: absolute;
			    top: 50%;
			    left: 50%;
			}
			#chart_div{
			    min-height: 500px;
			    padding-bottom: 20px;
			}
			.google-visualization-orgchart-node{
				font-size: 15px;
			}

		</style>
		<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

		<script type="text/javascript">
		function drawChart(array) {
		    var data = new google.visualization.arrayToDataTable(array, false);
		    var chart = new google.visualization.OrgChart(document.querySelector('#chart_div'));
		    chart.draw(data, {allowHtml: true});
		    $('.select2-basic-single').select2();
		}

		google.load('visualization', '1', {packages:['orgchart'], callback: function(){drawChart(<?= json_encode($data) ?>);}});		

		</script>
		<div class="warper container-fluid"> 
			<div class="page-header"><h1><?=$lang['Organization Chart']?><small><?=$lang['Chart']?></small></h1></div>
			<?php
				if ( !empty($_SESSION['result']) ){
					switch ($_SESSION['result']) {
						case 'success':
							echo '<div class="result_success">
				                    '.$lang['Thank you details has been updated'].'
				                </div>';
							break;
						case 'failed':
							echo '<div class="result_error">
				                    '.$lang['Sorry something error'].'
				                </div>';
							break;
						default:
							# code...
							break;
					}
					unset( $_SESSION['result'] );
				}
			?>
			<div class="panel panel-default">
				<div class="panel-body">					
					<form method="post" class="form-horizontal" id="quotationForm" enctype="multipart/form-data" novalidate="novalidate">
						<div class="form-group">
		                    <div class="col-sm-2 control-label"></div>
		                    <div class="col-sm-9">
		                    	
		                    </div>
		                </div>
						<div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['title']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="<?=$title_name?>">
		                    </div>
		                </div>
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['Current Group']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="<?=( !empty( $group_title[$chart_group] ) ? $group_title[$chart_group] : "Group " .$chart_group )?>">
		                    </div>
		                </div>
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['Next Group']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control " required="" disabled="" value="<?= dataFilterDash($type)?>">
		                    </div>
		                </div>
					</form>
				</div>
			</div>
			<div class="panel panel-default">
				<div class="panel-body">
					
					<form method="post" id="valid_form" novalidate="novalidate">						
						<div class="form-group" style="overflow: auto;position: relative;">
							<div id="chart_div"></div>
						</div>
						<div class="form-group">
							<input type="hidden" name="hide" value="1">
							<input type="hidden" name="action" value="insert">
							<?= ( arrayCheck($chart)  ?  '<input type="submit" class="btn btn-purple"  value="Submit" style="float: right;">' : '' ) ?>
						</div>			
					</form>
				</div>
			</div>
		</div>
		<?php
		break;
	case 'edit_title':
		if ($_POST['page_status'] == 'new'){	
			$mysqli->query("INSERT INTO system_chartTitle (chart_organization_group,created_at, updated_at) VALUES ('hr','".TODAYDATE."', '".TODAYDATE."')") ;			
			$page = $mysqli->insert_id ;
		}

		$query = "SELECT * FROM system_chartTitle where chartTitle_id = '".$page."' LIMIT 1";
		$query = $mysqli->query($query);
		if ( $query->num_rows > 0 ){
			$row_page = $query->fetch_array(MYSQLI_ASSOC);
			$row_page['group_title'] = json_decode($row_page['group_title'],true);
			// update database
			if (isset($type) && $type == 'edit' && $_POST['hide'] == 1){

				$title 			  = escapeString($_POST['title']);
				// $post_parent_type = escapeString($_POST['post_parent_type']);
				$group 			  = $_POST['group'];
				$post_parent_type = $_POST['post_parent_type'] ;
				$post_parent_type = ( $post_parent_type != '' ? '('.implode( '),(', $post_parent_type).')' : '' ) ;

				$array_title = [];
				foreach ($group as $k => $v) {
					$array_title[$k] = $v;
				}

				$success = 'failed' ;
				// update database
				if ($mysqli->query("UPDATE system_chartTitle SET
								chart_title = '".$title."',			
								post_parent_type = '".$post_parent_type."', 	
								group_title = '".json_encode($array_title)."',		
								updated_at = '".TODAYDATE."'
								WHERE chartTitle_id = '".$page."'") ){
					$success = 'success' ;
				}
				// refresh page
				$redirect = 'org_chart.php?page_mode=edit_title&page='.$page.'&success='.$success;
				
				// header("Location:") ;
				header("Location:".$redirect) ;
				exit ;
			}
		}
		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>
		<div class="warper container-fluid"> 
			<div class="page-header"><h1><?=$lang['Organization Chart']?><small> <?=$lang['edit']?></small></h1></div>
			<?php
				if ( !empty($_GET['success']) ){
					switch ($_GET['success']) {
						case 'success':
							echo '<div class="result_success">
				                    '.$lang['Thank you details has been updated'].'
				                </div>';
							break;
						case 'failed':
							echo '<div class="result_error">
				                    '.$lang['Sorry something error'].'
				                </div>';
							break;
						default:
							# code...
							break;
					}
				}
			?>
			<div class="panel panel-default">
				<div class="panel-body">
					<form method="post" class="form-horizontal" id="quotationForm" enctype="multipart/form-data" novalidate="novalidate" action="org_chart.php?page_mode=edit_title&type=edit&page=<?=$page?>">						
						<div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['title']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control" name="title" required="" value="<?=$row_page['chart_title']?>">
		                    </div>
		                </div>
		                <?php
		                $letter = "A";
		                	for ( $i = 0 ; $i < $group_number ; $i ++ ){
		                		echo '
		                			<div class="form-group">
					                    <div class="col-sm-2 control-label">'.$lang['Group'].' '.$letter.'</div>
					                    <div class="col-sm-9">
					                    	<input class="form-control" placeholder="'.$lang['Group'].' '.$letter.'" name="group['.$letter.']" value="'.$row_page['group_title'][$letter++].'">
					                    </div>
					                </div>
		                		';
		                	}
		                ?>
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"></div>
		                    <div class="col-sm-9">
		                    	<input type="hidden" name="hide" value="1" />
								<input type="hidden" name="hide_status" value="action" />
								<input type="submit" style="float: right;" class="btn btn-purple" value="<?= $lang['submit'] ?>" />
		                    </div>
		                </div>
					</form>
				</div>
			</div>
		</div>
		<?php
		break;
	case 'new_title':

		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>
		<div class="warper container-fluid"> 
			<div class="page-header"><h1><?=$lang['Organization Chart']?><small> <?=$lang['new']?></small></h1></div>
			<div class="panel panel-default">
				<div class="panel-body">
					<form method="post" class="form-horizontal" id="quotationForm" enctype="multipart/form-data" novalidate="novalidate" action="org_chart.php?page_mode=edit_title&type=edit">						
						<div class="form-group">
		                    <div class="col-sm-2 control-label"><?= $lang['title']?></div>
		                    <div class="col-sm-9">
		                    	<input class="form-control" name="title" required="" value="<?=$row_page['chart_title']?>">
		                    </div>
		                </div>
		                <?php
		                $letter = "A";
		                	for ( $i = 0 ; $i < $group_number ; $i ++ ){
		                		echo '
		                			<div class="form-group">
					                    <div class="col-sm-2 control-label">'.$lang['Group'].' '.$letter.'</div>
					                    <div class="col-sm-9">
					                    	<input class="form-control" placeholder="'.$lang['Group'].' '.$letter.'" name="group['.$letter.']" value="'.$row_page['group_title'][$letter++].'">
					                    </div>
					                </div>
		                		';
		                	}
		                ?>
		                <div class="form-group">
		                    <div class="col-sm-2 control-label"></div>
		                    <div class="col-sm-9">
								<input type="hidden" name="hide" value="1" />
								<input type="hidden" name="page_status" value="new" />
								<input type="submit" style="float: right;" class="btn btn-purple" value="<?= $lang['submit'] ?>" />
		                    </div>
		                </div>
					</form>
				</div>
			</div>
		</div>
		<?php
	break;

	case "all":
	default:
		if ( !empty($search) ){

			$search_query = ' AND ( chart_title LIKE "%'.$search.'%"';


			$query_staff = $mysqli->query("SELECT a.chartTitle_id FROM system_orgChart a 
											LEFT JOIN system_chartTitle b ON ( a.chartTitle_id = b.chartTitle_id ) 
											LEFT JOIN staff c ON ( a.staff_id = c.staff_id )
											WHERE a.chart_trash = '0' AND b.chart_trash = '0' AND c.staff_idno = '".$search."' ");
			
			$chart_list = [];
			if ( $query_staff->num_rows > 0 ){
				while ( $row_staff = $query_staff->fetch_array(MYSQLI_ASSOC) ){
					$chart_list[]  = $row_staff['chartTitle_id'];
				}
				$search_query .= " OR chartTitle_id IN (".implode(",", $chart_list).") )";
			}else{
				$search_query .= " )";
			}

			
		}

		if ( $_POST['hide'] == "1" && $_POST['hide_status'] == "action" ){
			switch ($_POST['page_action']) {
				case 'update':
					$id = $_POST['update'];
					foreach ($id as $k => $v) {
						$mysqli->query('UPDATE '.system_chartTitle.' set chart_next_group = "'.$v.'" where chartTitle_id = "'.$k.'"');
					}
					break;
				case 'trash':
					$id = $_POST['multiple_trash'];
					foreach ($id as $k => $v) {
						$mysqli->query('UPDATE '.system_chartTitle.' set chart_trash = "1" where chartTitle_id = "'.$k.'"');
					}
					break;

				case 'sortable':
					$id = $_POST['sortable'];
					foreach ($id as $k => $v) {
						$mysqli->query('UPDATE '.system_chartTitle.' set chart_order = "'.$v.'" where chartTitle_id = "'.$k.'"');
					}
					break;
				default:
					# code...
					break;
			}
		}

		$query = "SELECT * FROM system_chartTitle where chart_trash = '0' AND chart_organization_group='hr' AND chart_title != ''".$search_query;
		// pagination
		if (isset($page) && !empty($page)) { $product_page = $page ; } else { $product_page = 1 ; } // next and prev page (5 thing need to change)
		$start_from = ($product_page - 1) * LIMIT ; // end next and prev page

		// load pagination
		$page_pagination = nextPrevious($product_page, LIMIT, $search_url, $query) ;

		$query = $mysqli->query($query." order by chartTitle_id asc LIMIT $start_from, " . LIMIT);
		if ( $query->num_rows > 0 ){
			while ( $row = $query->fetch_array(MYSQLI_ASSOC) ){
				$array_data[] = $row;
			}
		}

		// print_R($array_data) ;
		// exit ;
		
		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>
		<div class="warper container-fluid"> 
			<div class="page-header">
				<h1><?=$lang['Organization Chart']?><small><?=$lang['list']?></small></h1>
				<a href="org_chart.php?page_mode=new_title" class="btn btn-purple" target="_blank"><?=$lang['add_new']?></a>	
			</div>
			<form method="post">
				<!-- trash -->
					<div class="panel panel-default">
						<div class="panel-body">
							<select name="page_action" class="form-control selectpicker" id="page_action_form">
								<option value=""><?= $lang['select'] ?></option>
								<option value="update"><?= $lang['Update Group Next Month'] ?></option>
								<option value="trash"><?= $lang['move_to_trash'] ?></option>
								<option value="sortable"><?= $lang['sortable'] ?></option>
							</select>
							<input type="hidden" name="hide" value="1" />
							<input type="hidden" name="hide_status" value="action" />
							<input type="submit" class="btn btn-purple" value="<?= $lang['submit'] ?>" />
						</div>
					</div>
				<!-- end trash -->	
				<div class="panel panel-default">
					<div class="panel-body">
						<table cellpadding="0" cellspacing="0" border="0" class="responsive table table-striped table-bordered" id="basic-datatable">
						<thead>
							<tr>
								<th width="50"><?= $lang['trash'] ?></th>
								<th width="60"><?= $lang['Action'] ?></th>		
								<th><?= $lang['title'] ?></th>	
								<th width="50"><?= $lang['Current Group'] ?></th>	
								<th width="100"><?= $lang['Next Group'] ?></th>
								<th width="50"><?= $lang['sortable'] ?></th>	
							</tr>
						</thead>
						<tbody>
							<?php
								if ( arrayCheck($array_data) ){
									foreach ($array_data as $k => $v) {
										$group_title = array();
										$group_title = json_decode( $v['group_title'], true );
										echo '
										<tr>
											<td>
												<div class="checkbox multiple_trash">
													<input type="checkbox" name="multiple_trash['.$v['chartTitle_id'].']" class="trash_button" value="1">
													<label for="checkbox1"></label>
												</div>
											</td>
											<td class="align_center">
												<a title="Edit Current Title" target="_blank" href="org_chart.php?page_mode=edit_title&page='.$v['chartTitle_id'].'"><i class="fa fa-edit"></i></a>
												<span>&nbsp;|&nbsp;</span>
												<a title="Edit Current Chart" target="_blank" href="org_chart.php?page_mode=edit_chart&page='.$v['chartTitle_id'].'"><i class="fa fa-sitemap"></i></a>
												<span>&nbsp;|&nbsp;</span>
												<a title="Edit Day" target="_blank" href="org_chart.php?page_mode=change_group3&page='.$v['chartTitle_id'].'&type='.$v['chart_group'].'"><i class="fa fa-exchange"></i></a>
											</td>
											<td>
												<a href="org_chart.php?page_mode=edit_chart&page='.$v['chartTitle_id'].'" target="_blank">'.$v['chart_title'].'</a>
											</td>											
											<td class="align_center">
												'.( !empty($v['chart_group']) ? ( !empty($group_title[$v['chart_group']]) ? $group_title[$v['chart_group']] : $v['chart_group'] ) : '').'
											</td>
											<td class="align_center">
												<select class="form-control selectpicker" name="update['.$v['chartTitle_id'].']">
													<option value="">'.$lang['select'].'</option>
													';
													
													print_r($v);
									                $letter = "A";
								                	for ( $i = 0 ; $i < $group_number ; $i ++ ){
								                		echo '<option value="'.$letter.'" '.( $v['chart_next_group'] == $letter ? 'selected' : '').'>'.( !empty($group_title[$letter]) ? $group_title[$letter] : $lang['Group'].' '.  $letter ) .'</option>';
								                		$letter++;
								                	}
									                echo '
												</select>
											</td>
											<td class="align_center">
												<input type="text" name="sortable['.$v['chartTitle_id'].']" class="form-control text-center" value="'.$v['chart_order'].'" placeholder="'.$lang['sortable'].'"/>
											</td>
											
										</tr>';
									}
								}else{
									echo '
										<tr class="odd gradeX">
											<td class="border_none">No data.</td>
											<td class="border_none"></td>
											<td class="border_none"></td>
											<td class="border_none"></td>
										</tr>';
								}
								?>
							</tbody>
						</table>
						<?= $page_pagination['page_pagination'] ?>
					</div>
				</div>
			</form>
		</div>
		<?php
	break;
}
?>

<script>
$(document).ready(function(){
	// jquery validate form
	$("#valid_form").validate({
		ignore: ".ignore",
		invalidHandler: function (form, validator) {
			// full error = 24
			if ( $('.check_value1').hasClass('error') ){

			}else if ( $('.check_value2').hasClass('error') ){
				$('.nav_item_group_2 a').click() ;
			}else if ( $('.check_value3').hasClass('error') ){
				$('.nav_item_group_3 a').click() ;
			}
        },
        unhighlight: function (element, errorClass, validClass) {
			console.log(2) ;
      //       $(element).removeClass(errorClass);
      //       $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
      //       var $panel = $(element).closest(".ui-tabs-panel", element.form);
      //       if ($panel.size() > 0) {
      //           if ($panel.find("." + errorClass + ":visible").size() == 0) {
      //               $panel.siblings(".ui-tabs-nav").find("a[href='#" + $panel[0].id + "']")
      // .parent().removeClass("ui-state-error");
      //           }
      //       }
        }
	});
}) ;
</script>

<?php
// footer
include 'requires/page_footer.php' ;
?>