<?php include_once($_SERVER['DOCUMENT_ROOT'].'/_ps2020/_global/dir_root.php'); ?>
<?php include_once($_SERVER['DOCUMENT_ROOT'].'/_ps2020/config/cfg_loggedUser.php'); ?>
<?php include($_SERVER['DOCUMENT_ROOT'] ."/_ps2020/config/connect.php"); ?>

<!DOCTYPE HTML>
<!--
	Hielo by TEMPLATED
	templated.co @templatedco
	Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
-->
<html>
	<head>
		<title>Users | GEESE</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />

		<?php include_once(dir_rootPHP.'_global/icon.php'); ?>


		<!-- libs -->
			<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
			<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/fontAwesome/css/font-awesome.min.css" /> -->
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/animate.css" /> -->

			<!-- animation -->
				<link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate.css" />
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_bounce.css" /> -->
				<link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_fade.css" />
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_flip.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_other.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_rotate.css" /> -->
				<link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_slide.css" />
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_zoom.css" /> -->

			<!-- table-fucntions -->
				<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4-4.1.1/jq-3.3.1/jszip-2.5.0/dt-1.10.21/af-2.3.5/b-1.6.3/b-colvis-1.6.3/b-flash-1.6.3/b-html5-1.6.3/b-print-1.6.3/cr-1.5.2/fc-3.3.1/fh-3.1.7/kt-2.5.2/r-2.2.5/rg-1.1.2/rr-1.2.7/sc-2.0.2/sb-1.0.0/sp-1.1.1/sl-1.3.1/datatables.min.css"/>

				<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
				<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
				<script type="text/javascript" src="https://cdn.datatables.net/v/bs4-4.1.1/jq-3.3.1/jszip-2.5.0/dt-1.10.21/af-2.3.5/b-1.6.3/b-colvis-1.6.3/b-flash-1.6.3/b-html5-1.6.3/b-print-1.6.3/cr-1.5.2/fc-3.3.1/fh-3.1.7/kt-2.5.2/r-2.2.5/rg-1.1.2/rr-1.2.7/sc-2.0.2/sb-1.0.0/sp-1.1.1/sl-1.3.1/datatables.min.js"></script>

		<!-- css -->
			<link rel="stylesheet" href="<?php echo dir_root; ?>css/template-hielo/main.css" />
			<link rel="stylesheet" href="<?php echo dir_root; ?>css/template-hielo/dataTable.css" />

		<!-- css (custom) -->
			<link rel="stylesheet" href="<?php echo dir_root; ?>css/henry_style.css" />
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/tanuj_style.css" /> -->
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/karl_style.css" /> -->
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/harsh_style.css" /> -->

			<style type="text/css">

				.animated{
				  -webkit-animation-duration: .6s;
				  animation-duration: .6s;
				}
				
				input[type="text"]{height: 2rem;}

				table{
					min-width: 1200px;
				}

				.table thead th{
					border-bottom: 0px;
				}

				table td{
					padding-right: 3rem;
				}

				table tbody tr:hover{
					background-color: #58ff582e !important; /*#47cd475c*/
				}

				select{
					height: 2rem;
					padding: 0 .5rem;
					cursor: pointer;
				}
					.select-wrapper{
						display: inline-block;
						width: 80%;
					}
					.select-wrapper::before{
						width: 2rem; height: 2rem;
						line-height: 2rem;
					}

				#thDel{
					pointer-events: none;
				}
					#thDel::before, #thDel::after{
						content: '';
					}

				#btnAdd{
					width: 100%; height: 40px;
					padding: 0 10px;

					border: 1px dashed grey; border-radius: 5px;
					background-color: #ffffff40;
					
					transition: all .2s ease;
				}
						#btnAdd>iconPlus{
							color: green;
							transition: all .2s ease;
						}

					#btnAdd:hover{
						background-color: #548B54; /*background-color: #eaeaea40;*/
						border-style: solid;
						cursor: pointer;
					}
						#btnAdd:hover >iconPlus{
							color: white;
							transform: scale(1.02);
						}

				#btnDel{
					padding-right: 1rem;
					border-left: 1px solid #cbcbcb;

					cursor: pointer;
					transition: all .4s ease;
				}
					#btnDel:hover{
						background-color: #f55757;
					}
					#btnDel:hover >i{
						color: white;
					}

					#btnDel >i{
						color: #e80000;
						padding-left: 2px;
					}

				.tField_Url{
					display: inline-block !important;
					width: 90% !important;
				}

				#surveyAdd_row{
					display: flex;
					padding: 20px;
				}
					.surveyAdd_rowInner{
						display: inherit;
						width: 100%; padding: 20px;

						border: 1px solid #eee; border-radius: 15px;
						box-shadow: 0 0 15px #ececec;
					}
					@media all and (max-width: 992px){
						#surveyAdd_row{
							display: block;
							padding: 10px;
						}
					}

				#btnClose{
					position: absolute;
				    top: 10px;
				    right: 15px;

				    cursor: pointer;
				}
					@media all and (max-width: 992px){
						#btnClose{
						    top: 55px;
						    right: 0;
						}
					}

				@media all and (max-width: 576px) {
					.inner{ width: 95% !important; }
					.content{ padding: 2rem 1rem !important; }
				}

			</style>

	</head>
	<!-- <body class="subpage"> -->
	<body>

		<!-- Header | Nav -->
			<?php include_once(dir_rootPHP.'_global/navbar/navbar.php'); ?>
			<?php include_once(dir_rootPHP.'_global/navbar/navbar-mobile.php'); ?>

		
		<!-- Page-Title -->
			<section id="One" class="wrapper style3" style="padding-top: 9rem;">
				<div class="inner">
					<header class="align-center">
						<p>Greenscape Environmental Experience & Learning Survey Experiments</p>
						<h2>Manage Users</h2>
					</header>
				</div>
			</section>

		<!-- Content -->
			<section id="two" class="wrapper style2">
				<div class="inner">

					<div class="box ctm-box">
						<div class="content">

							<!-- Table -->
							<div class="table-wrapper">
								
								<!-- <h2>Manage Users</h2> -->

								<div style="padding: 5px; overflow-x: auto;">
									
									<?php
					                	$result = $conn->query("SELECT user_id AS 'ID', username AS 'Username', email AS 'Email', password AS 'Password', accountType AS 'Account Type', school_id AS 'School', class_id AS 'Class', active AS 'Status' FROM user_account ORDER BY user_id ASC;");

											$tablesAndTheirData = array();
										    array_push($tablesAndTheirData, array(
										        'fields' => $result->fetch_fields(),
										        'data' => $result
										    ));

					                	foreach($tablesAndTheirData as $table){
					                		if($table['data']->num_rows){
		                			?>
					                			<table id="data_table" class="table table-striped" style="width:100%;">

					                                <thead class="animated fadeInUp">
					                                    <tr>
						                                    <?php
						                                    	foreach($table['fields'] as $field){
						                                    ?>
						                                        	<th><?php echo $field->name;?></th>
						                                    <?php
						                                    	}
						                                    ?>
						                                    <!-- <th id="thDel" class="1u 1u$(xsmall)"></th> -->
					                                    </tr>
					                                </thead>

					                                <tbody>
							                            <?php
															$order_num = 0;
							                            	while($row = $table['data']->fetch_assoc()){
							                            		$order_num++;
							                            ?>
								                                <tr class="animated fadeIn">
								                                    <?php
								                                    	$index = 0;
								                                    	$keyUser = $keyPass = $keyAcType = $keySchool = $keyClass = '';

								                                    	foreach($row as $key => $value){

								                                    		if ($key == 'ID'){
								                                    			$index = $value;
								                                    		}
								                                    ?>
								                                    		<td>
								                                    			<?php
								                                    				if ($key == 'Username'){
								                                    			?>
									                                    			<!-- label -->
																						<div id="nameRow_<?php echo $index; ?>">
																							<label id="name_<?php echo $index; ?>" style="display: inline-block; margin: 0 !important;"><?php echo $value; ?></label>
																							<i class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;" onclick="surveyEdit('name','<?php echo $index; ?>')"></i>
																						</div>
																					<!-- txtfield -->
																						<div id="nameTField_row<?php echo $index; ?>" class="ctm-toCenter" style="display: none;">
																							<input id="nameTField_<?php echo $index; ?>" name="nameTField_<?php echo $index; ?>" type="text" value="<?php echo $value; ?>" />
																						</div>
																				<?php
																					}
																					else if ($key == 'Email'){
																				?>
																						<!-- label -->
																						<div id="emailRow_<?php echo $index; ?>">
																							<label id="email_<?php echo $index; ?>" style="display: inline-block; margin: 0 !important;"><?php echo $value; ?></label>
																							<i class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;" onclick="surveyEdit('email','<?php echo $index; ?>')"></i>
																						</div>
																						<!-- txtfield -->
																							<div id="emailTField_row<?php echo $index; ?>" class="ctm-toCenter" style="display: none;">
																								<input id="emailTField_<?php echo $index; ?>" name="emailTField_<?php echo $index; ?>" type="text" value="<?php echo $value; ?>" />
																							</div>
																				<?php
																					}
																					else if ($key == 'Password'){
																				?>
																						<!-- <input id="password_<?php echo $index; ?>" name="password_<?php echo $index; ?>" type="text" class="ctm-disable tField_Url" value="" placeholder="<?php echo $value; ?>" />
																						<i id="passwordIc_<?php echo $index; ?>" class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;"
																							onclick="urlEdit('<?php echo $index; ?>')"></i> -->
																						<button id="btnPasswordChange" class="button special" style="height: 1.9rem; line-height: 2rem; background-color: #8c8c8c; padding: 0 .8rem; font-size: 12px; text-transform: unset; border-radius: 5px;" onclick="passwordEdit('<?php echo $index; ?>')">Change</button>
																				<?php
																					}
																					else if ($key == 'Account Type'){
																						$keyAcType = $value;
																				?>
																						<!-- Dropdown -->
																						<div id="roleRow_<?php echo $index; ?>" class="select-wrapper ctm-disable" style="">
																							<select>
																				<?php
																								$result = $conn->query("SELECT * FROM user_role");

																								while ( $row = $result->fetch_assoc() ){

																									$typeSelected = $row['role_id'] == $value ? 'selected="true"' : '';
																				?>
																										<option id="role_<?php echo $row['role_id'] ?>" value="<?php echo $row['role_id'] ?>" <?php echo $typeSelected ?> ><?php echo $row['role_id'].'/ '.$row['role'] ?></option>
																				<?php
																								}
																				?>
																							</select>
																						</div>
																						<!-- Icon -->
																						<i id="roleIc_<?php echo $index; ?>" class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;"
																							onclick="selectEdit('role','<?php echo $index; ?>')"></i>
																				<?php
																					}
																					else if ($key == 'School'){
																						$keySchool = $value;

																						if ( $keyAcType != 5 && $keyAcType != 4 && $keyAcType != 0 ){
																							$section_display = '';
																							$unload_display = 'display: none;';
																						}
																						else{
																							$section_display = 'display: none;';
																							$unload_display = '';
																						}

																				?>
																						<!-- Dropdown -->
																						<div id="schoolRowWrap_<?php echo $index; ?>" style="<?php echo $section_display; ?>">
																							<div id="schoolRow_<?php echo $index; ?>" class="select-wrapper ctm-disable">
																								<select>
																									<option id="school_0" value="0">---</option>
																				<?php
																									$result = $conn->query("SELECT * FROM school");

																									while ( $row = $result->fetch_assoc() ){

																										$typeSelected = $row['school_id'] == $value ? 'selected="true"' : '';
																				?>
																										<option id="school_<?php echo $row['school_id'] ?>" value="<?php echo $row['school_id'] ?>" <?php echo $typeSelected ?> ><?php echo $row['school_id'].'/ '.$row['school_name'] ?></option>
																				<?php
																									}
																				?>
																								</select>
																							</div>
																							<!-- Icon -->
																							<i id="schoolIc_<?php echo $index; ?>" class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;"
																								onclick="selectEdit('school','<?php echo $index; ?>')"></i>
																						</div>

																						<!-- Not Applicable -->
																						<div id="schoolUnload_<?php echo $index; ?>" style="<?php echo $unload_display; ?>" >Not Applicable</div>
																				<?php
																					}
																					else if ($key == 'Class'){
																						if ( $keySchool != 0 && ($keyAcType == 1) ){  //$keySchool != 0 && ($keyAcType != 5 && $keyAcType != 4)
																							$section_display = '';
																							$unload_display = 'display: none;';
																						}
																						else{
																							$section_display = 'display: none;';
																							$unload_display = '';
																						}

																				?>
																						<!-- Dropdown -->
																						<div id="classRowWrap_<?php echo $index; ?>" style="<?php echo $section_display; ?>">
																							<div id="classRow_<?php echo $index; ?>" class="select-wrapper ctm-disable">
																								<select>
																									<option id="class_0" value="0">---</option>
																				<?php
																									$classIndex = 0;
																									$result = $conn->query("SELECT * FROM school_class WHERE school_id = '$keySchool'");

																									while ( $row = $result->fetch_assoc() ){
																										$classIndex++;

																										$typeSelected = $row['class_id'] == $value ? 'selected="true"' : '';
																				?>
																										<option id="class_<?php echo $row['class_id'] ?>" value="<?php echo $row['class_id'] ?>" <?php echo $typeSelected ?> ><?php echo $classIndex.'. '.$row['class_name'] ?></option>
																				<?php
																									}
																				?>
																								</select>
																							</div>
																							<!-- Icon -->
																							<i id="classIc_<?php echo $index; ?>" class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;"
																								onclick="selectEdit('class','<?php echo $index; ?>')"></i>
																						</div>

																						<!-- Not Applicable -->
																						<div id="classUnload_<?php echo $index; ?>" style="<?php echo $unload_display; ?> width: max-content;">Not Applicable</div>
																				<?php
																					}
																					else if ($key == 'Status'){
																						if ($value == 1){
																							$bColor = 'green';
																							$statusVal = 'Active';
																							$statusIc = 'on';
																						}
																						else{
																							$bColor = '#bdbdbd';
																							$statusVal = 'Inactive';
																							$statusIc = 'off';
																						}
																				?>
																						<div style="display: block;">
																							<!-- <div style="display: inline-block; width: 70px; text-align: center; background-color: <?php echo $bColor; ?>; color: white; font-size: 14px; padding: 2px 5px; border-radius: 5px;"><?php echo $statusVal; ?></div> -->
																							<i id="statusIc_<?php echo $index; ?>" class="fas fa-toggle-<?php echo $statusIc; ?>" style="display: inline-block; color: <?php echo $bColor; ?>; font-size: 32px; padding-left: 2px; transition: .2s; cursor: pointer;"
																								onclick="iconEdit('<?php echo $index; ?>','<?php echo $value; ?>')"></i>
																						</div>
																				<?php
																					}
																					else
																						echo $value;
																				?>
								                                    		</td>
								                                    <?php
								                                    	}
								                                    ?>

																	<!-- Delete -->
																	<!-- <td id="btnDel" class="1u 1u$(xsmall)" onclick="userDelete('<?php echo $index; ?>','<?php echo $index; ?>')">
																		<i id="icDel_<?php echo $index; ?>" class="fa fa-trash" ></i>
																	</td> -->
								                                </tr>
							                            <?php
							                            	}
							                            ?>
					                                </tbody>
					                            </table>
		                			<?php
					                		}
					                	}
					                ?>

								</div>

								<div style="height: 10px;"></div>

								<!-- ==== (Add) button ==== -->
									<div id="btnAdd" class="animated fadeIn ctm-toCenter" onclick="userAdd()">
										<iconPlus><i class="fa fa-plus-circle"></i>   add user</iconPlus>
									</div>

									<!-- ==== New-User ==== -->
										<div id="surveyAdd_row" class="animated fadeInDown ctm-hide">
											<div class="3u 12u$(medium)"><h2>New User</h2></div>
											<div class="9u 9u$(medium) surveyAdd_rowInner">
												<!-- User-Name -->
													<div class="4u 12u$(medium)" style="padding: 10px;">
														<div class=""><label for="newName">User-name</label></div>
														<input id="newName" name="newName" type="text" style="border-color: #9f9f9f; border-radius: 5px;" value="" />
													</div>
														
												<!-- URL -->
													<div class="8u 12u$(medium)" style="padding: 10px;">
														<div class=""><label for="newUrl">URL</label></div>
														<input id="newUrl" name="newUrl" type="text" class="" style="border-color: #9f9f9f; border-radius: 5px;" value="" placeholder="" />
													</div>

												<!-- ==== (Complete) button ==== -->
													<div class="2u 12u$(medium)" style="padding: 10px;">
														<div style="height: 2rem;"></div>
														<div id="btnComplete" class="animated fadeIn ctm-toCenter" onclick="surveyAdd_toDb()">
															<div class="button special fit" style="text-transform: unset; border-radius: 5px; margin: 0;">Complete</div>
														</div>
													</div>

												<!-- ==== (Close) button ==== -->
													<div id="btnClose"><i class="fa fa-times-circle-o" style="font-size: 32px; color: #ff00009e;" onclick="surveyAdd_close()"></i></div>
											</div>
										</div>

							</div>

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

		<!-- Footer -->
			<?php include_once(dir_rootPHP.'_global/footer/footer.php'); ?>

		<script type="text/javascript">
			$(document).ready(function() {
	            $('#data_table').DataTable( {
	                dom: 'frtip'
	            });
	        });
		</script>

		<!-- Scripts -->
			<!-- <script src="<?php echo dir_root; ?>js/template-hielo/jquery.min.js"></script> -->
			<script src="<?php echo dir_root; ?>js/template-hielo/jquery.scrollex.min.js"></script>
			<script src="<?php echo dir_root; ?>js/template-hielo/skel.min.js"></script>
			<script src="<?php echo dir_root; ?>js/template-hielo/util.js"></script>
			<script src="<?php echo dir_root; ?>js/template-hielo/main.js"></script>


		<!-- ==========  <- Pop-Notification ->  ========== -->
			<?php include_once(dir_rootPHP.'_global/tools/popNotif.php'); ?>

		<!-- ==========  <- Pop-up ->  ========== -->
			<?php include_once(dir_rootPHP.'_global/tools/popAlert.php'); ?>

		<!-- ==========  <- Pop-Window ->  ========== -->
			<?php include_once(dir_rootPHP.'_global/tools/popWindow.php'); ?>

		<!-- Scripts (custom) -->
			<script type="text/javascript">

				// disable 'Tab' key [for all textfield]
				$(document).keydown(function(e){
					if (e.which == 9){
						e.preventDefault();
					}
				});
				
				/* -----  Edit-Name  ----- */
				function surveyEdit($id,$index){
					// hide 'label'
					$('#'+$id+'Row_'+$index).hide();
					// show 'txtfield'
					$('#'+$id+'TField_row'+$index).show();
					// edit in 'txtfield'
					$('#'+$id+'TField_'+$index).focus();


						$('#'+$id+'TField_'+$index).focusout(function(){  // click outside txtfield
							if ($id == 'name'){
								updateName($index);
							}

							if ($id == 'email'){
								updateEmail($index);
							}
						});
						$('#'+$id+'TField_'+$index).keypress(function(e){
							if(e.which == 13){  // the enter key code
								if ($id == 'name'){
									updateName($index);
								}

								if ($id == 'email'){
									updateEmail($index);
								}
							}
						});

				}
						function updateName($sid){
							$newName = $('#nameTField_'+$sid).val();
							$.ajax({
								type :'POST',
								url  :'<?php echo dir_root; ?>php/ajax/post_userUpdate.php?act=update_username&sid='+$sid+'&sName='+$newName,
								date :'',
								success:function(m){
									// hide 'txtfield'
									$('#nameTField_row'+$sid).hide();
									// update 'label'
									$nameVal = $('#nameTField_'+$sid).val();
									$('#name_'+$sid).text($nameVal);
									// show 'label'
									$('#nameRow_'+$sid).show();

									// Notification
										$icon = 1;
										$msg = '<b>Username: "'+$nameVal+'"</b>&ensp;is updated';
									popNotif_show($icon,$msg);
								}
							});
						}
						function updateEmail($sid){
							$newName = $('#emailTField_'+$sid).val();
							$.ajax({
								type :'POST',
								url  :'<?php echo dir_root; ?>php/ajax/post_userUpdate.php?act=update_email&sid='+$sid+'&sEmail='+$newName,
								date :'',
								success:function(m){
									// hide 'txtfield'
									$('#emailTField_row'+$sid).hide();
									// update 'label'
									$nameVal = $('#emailTField_'+$sid).val();
									$('#email_'+$sid).text($nameVal);
									// show 'label'
									$('#emailRow_'+$sid).show();

									// Notification
										$icon = 1;
										$msg = '<b>Email: "'+$nameVal+'"</b>&ensp;is updated';
									popNotif_show($icon,$msg);
								}
							});
						}

				/* -----  Change-Password  ----- */
				function passwordEdit($sid){
					// show pop-pWin
						$pWUrl = '<?php echo dir_root; ?>_global/html/getForm_manageUser_passwordChange.php';
						$pWTitle = 'Password';
						$pWHeader = 'Change Password';
						$pWMsg = '';
						$pWConfirm = 'Confirm';
						$pWCancel = 'Cancel';
						$pWIcon = 0;
					
					popWindow_show($pWUrl,$pWTitle,$pWHeader,$pWMsg,$pWConfirm,$pWCancel,$pWIcon);

					$('#popWinBtn_confirm').click(function(e){
						// console.log('clicked');
						
						var iFrame_func = $('#popWin_iFrame')[0].contentWindow;

						if (!iFrame_func.error_inPassword() && !iFrame_func.error_inPasswordConfirm()){
							// console.log('password correct');
							
							$password = iFrame_func.$('#password').val();
							
							// show pop-alert
								$title = 'Change Password?';
								$msg = 'Are you sure to change password for user: '+$('#name_'+$sid).text()+'?';
								$confirm = 'Confirm';
								$cancel = 'Cancel';
								$icon = 0;
							
							popAlert_show($title,$msg,$confirm,$cancel,$icon);

							$('#popBtn_confirm').click(function(){
								$.ajax({
									type :'POST',
									url  :'<?php echo dir_root; ?>php/ajax/post_userUpdate.php?act=update_password&sid='+$sid+'&password='+$password,
									date :'',
									success:function(m){
										// console.log(m);
										if (m == 1){
											// location.reload();
											popWindow_hide();

											// Notification
												$icon = 1;
												$msg = 'Success: password changed!!';
											popNotif_show($icon,$msg);
										}
										else{
											// Notification
												$icon = 2;
												$msg = 'Failed to add user to database';
											popNotif_show($icon,$msg);
										}
									}
								});
							});
						}
					});
				}
						function updateUrl($sid){
							$newUrl = $('#url_'+$sid).val();

							$.ajax({
								type :'POST',
								url  :'<?php echo dir_root; ?>php/ajax/post_surveyUpdate.php?act=update_sUrl&sid='+$sid+'&sUrl='+$newUrl,
								date :'',
								success:function(m){
									$('#url_'+$sid).attr('placeholder', $newUrl);
									$('#icUrl_'+$sid).removeClass('ctm-disable');
									$('#url_'+$sid).addClass('ctm-disable');

									// Notification
										$icon = 1;
										$msg = '"Survey-URL" is updated';
									popNotif_show($icon,$msg);
								}
							});
						}

				/* -----  Edit-select  ----- */
				$s_selected			= '';
				$init_id			= '';
				$init_value			= '';
				$init_selectedVal	= '';

				$editClass_bySchool = false;

				function selectEdit($cHead,$index){
					// hide 'icon'
					$('#'+$cHead+'Ic_'+$index).addClass('ctm-disable');
					// enable 'select-row'
					$('#'+$cHead+'Row_'+$index).removeClass('ctm-disable');
					// focus on 'select'
					$('#'+$cHead+'Row_'+$index+'>select').focus();

						$row_username		= $('#name_'+$index).html();

						$s_selected			= $('#'+$cHead+'Row_'+$index+'>select option:selected');
						$init_id			= $s_selected.attr('id');
						$init_value			= $s_selected.val();
						$init_selectedVal	= $s_selected.html();

						// when 'ESC' is pressed
							$('#'+$cHead+'Row_'+$index+'>select').keydown(function(e){
								if(e.key == 'Escape'){  // the key-code for 'ESC'
									$('#'+$cHead+'Row_'+$index+'>select').val($init_value);
									$('#'+$cHead+'Row_'+$index+'>select').blur();
								}
							});

						// Dropdown is blur
							$('#'+$cHead+'Row_'+$index+'>select').blur(function(){  // click outside select

								$s_selected				= $('#'+$cHead+'Row_'+$index+'>select option:selected');
								$current_id				= $s_selected.attr('id');
								$current_value			= $s_selected.val();
								$current_selectedVal	= $s_selected.html();
								
								// the value inside the dropdown has changed
								if ($current_value == 0 && $cHead == 'school'){
									// show pop-alert
										$title = 'Please choose a '+$cHead;
										$msg = 'The field, "'+$cHead+'" cannot be empty.';
										$confirm = 'Confirm';
										$cancel = 'Cancel';
										$icon = 3;
									
									popAlert_btnSingle();
									popAlert_show($title,$msg,$confirm,$cancel,$icon);

									$('#popBtn_confirm').click(function(){
										setTimeout(function() {

											$('#'+$cHead+'Row_'+$index+'>select').focus();

										}, animTime);
									});
								}
								else if ($init_id != $current_id || $editClass_bySchool == true){
									// show pop-alert
										if ($init_value == 0){
											$title = 'Assign to '+$cHead+'?';
											$msg = 'Are you sure to assign user: <b>"'+$row_username+'"</b><br>to '+$cHead+': <b>"'+$current_selectedVal+'"</b>';
										}
										else if ($current_value == 0){
											$title = 'Discharge from '+$cHead+'?';
											$msg = 'Are you sure to discharge user: <b>"'+$row_username+'"</b><br>from '+$cHead+': <b>"'+$current_selectedVal+'"</b>';
										}
										else{
											$title = 'Change '+$cHead+'?';
											$msg = 'Are you sure to change<br><b>"'+$init_selectedVal+'"</b> to <b>"'+$current_selectedVal+'"</b>';
										}
										$confirm = 'Save';
										$cancel = 'Cancel';
										$icon = 0;
									
									popAlert_show($title,$msg,$confirm,$cancel,$icon);

									// button 'Confirm'
									$('#popBtn_confirm').click(function(){
										setTimeout(function() {
											select_determine($cHead,$index);
										}, animTime);
									});
									// button 'Cancle'
									$('#popBtn_cancel').click(function(){
										setTimeout(function() {
											
											if ($init_value != 0){
												$('#'+$cHead+'Row_'+$index+'>select').val($init_value);
												select_disable($cHead,$index);
											}
											else
												$('#'+$cHead+'Row_'+$index+'>select').focus();

										}, animTime);
									});
									// $(this).unbind('blur');
								}
								else
									select_disable($cHead,$index);
							});
				}
					function select_determine($cHead,$index){

						$s_selectedRole		= $('#roleRow_'+$index+'>select');
						$role_value			= $s_selectedRole.val();
						$role_selectedVal	= $s_selectedRole.html();

						$rVal =$sVal = $cVal = '';

						console.log('role of this row: '+$role_value);

						// Account-Type
						if ($cHead == 'role'){
							console.log('dropdown is: Role');
							
							if ($role_value == 1 || $role_value == 2 || $role_value == 3){ // Student, Teacher, School-Admin
								console.log('role: Student, Teacher, School-Admin');

								// show dropdown 'School'
								$('#schoolRowWrap_'+$index).show();
								$('#schoolUnload_'+$index).hide();
								$('#schoolRow_'+$index+'>select').val(0);

								if ($role_value != 1){
									// hide dropdown 'Class'
									$('#classRowWrap_'+$index).hide();
									$('#classUnload_'+$index).show();
									$('#classRow_'+$index+'>select').val(0);
								}

								selectEdit('school',$index);
							}
							else{
								console.log('role: Participant, Researcher, Super-Admin');

								// hide dropdown 'School'
								$('#schoolRowWrap_'+$index).hide();
								$('#schoolUnload_'+$index).show();
								$('#schoolRow_'+$index+'>select').val(0);
								// hide dropdown 'Class'
								$('#classRowWrap_'+$index).hide();
								$('#classUnload_'+$index).show();
								$('#classRow_'+$index+'>select').val(0);

								// update to database
								$rVal = $('#roleRow_'+$index+'>select').val();
								select_update($index,$rVal,$sVal,$cVal);
							}
							select_disable($cHead,$index);
						}
						
						// School
						if ($cHead == 'school'){
							if ($role_value == 1){ // Student
								
								select_ajaxClass($cHead,$index);

								// show dropdown 'Class'
								$('#classRowWrap_'+$index).show();
								$('#classUnload_'+$index).hide();
								
								$editClass_bySchool = true;
							}
							else{
								select_disable($cHead,$index);
								
								// update to database
								$rVal = $('#roleRow_'+$index+'>select').val();
								$sVal = $('#schoolRow_'+$index+'>select').val();
								select_update($index,$rVal,$sVal,$cVal);
							}
						}

						// Class
						if ($cHead == 'class'){
							select_disable($cHead,$index);
							select_disable('school',$index);
							$editClass_bySchool = false;
							
							// update to database
							$rVal = $('#roleRow_'+$index+'>select').val();
							$sVal = $('#schoolRow_'+$index+'>select').val();
							$cVal = $('#classRow_'+$index+'>select').val();
							select_update($index,$rVal,$sVal,$cVal);
						}
					}
						function select_ajaxClass($cHead,$index){
							$get_sid = $('#schoolRow_'+$index+'>select').val();
							// console.log('school: '+$get_sid);

							$.ajax({
								type :'GET',
								url  :'<?php echo dir_root; ?>php/ajax/get_selectClass.php?sid='+$get_sid,
								dataType :'json',
								success:function(m){
									
									// console.log(m.length);
									if (m.length > 0){
										$("#classRow_"+$index+'>select>option[value=0]').siblings('option').remove();

										$.each(m, function(key, value){
											var str = "<option value='"+this.cID+"'>"+this.cIndex+". "+this.cName+"</option>";
											$("#classRow_"+$index+">select").append(str);
										});

										$s_selected			= $('#classRow_'+$index+'>select option:selected');
										$init_id			= $s_selected.attr('id');
										$init_value			= $s_selected.val();
										$init_selectedVal	= $s_selected.html();

										selectEdit('class',$index);
									}
									else{
										select_disable($cHead,$index);
										$('#classIc_'+$index).addClass('ctm-disable');
									}
								}
							});
						}
					function select_update($index,$rVal,$sVal,$cVal){
						$.ajax({
							type :'POST',
							url  :'<?php echo dir_root; ?>php/ajax/post_userUpdate.php?act=update_select&index='+$index+'&rVal='+$rVal+'&sVal='+$sVal+'&cVal='+$cVal,
							date :'',
							success:function(m){
								// Notification
								if (m == 1){
									$icon = 1;
									$msg = '<b>Success: </b>The row of <b>"'+$('#name_'+$index).html()+'"</b> is updated';
								}
								else{
									$icon = 2;
									$msg = 'Failed updating to database';
								}
								popNotif_show($icon,$msg);
							}
						});
					}
					function select_enable($cHead,$index){
						$('#'+$cHead+'Ic_'+$index).addClass('ctm-disable');
						$('#'+$cHead+'Row_'+$index).removeClass('ctm-disable');
					}
					function select_disable($cHead,$index){
						$('#'+$cHead+'Ic_'+$index).removeClass('ctm-disable');
						$('#'+$cHead+'Row_'+$index).addClass('ctm-disable');
					}

				/* -----  Active-Status  ----- */
				function iconEdit($index,$value){

					var newVal;

					if ($value == 1){
						$title = 'Disable an Account?';
						$msg = 'Are you sure to <b style="color: red;">disable</b> the account for <b>"'+$('#name_'+$index).html()+'"</b>?';
						newVal = -1;
					}
					else{
						$title = 'Active an Account?';
						$msg = 'Are you sure to <b style="color: #00a500;">active</b> the account for <b>"'+$('#name_'+$index).html()+'"</b>?';
						newVal = 1;
					}

					// show pop-alert
						$confirm = 'Confirm';
						$cancel = 'Cancel';
						$icon = 0;
					
					popAlert_show($title,$msg,$confirm,$cancel,$icon);

					$('#popBtn_confirm').click(function(){setTimeout(function() {
							updateStatus($index,newVal);
					}, animTime);});
				}
					function updateStatus($index,$value){
						$.ajax({
							type :'POST',
							url  :'<?php echo dir_root; ?>php/ajax/post_userUpdate.php?act=update_status&index='+$index+'&statVal='+$value,
							date :'',
							success:function(m){
								// Notification
								if (m == 1){
									location.reload();
									// $icon = 1;
									// $msg = '<b>Success: </b>The row of <b>"'+$('#name_'+$index).html()+'"</b> is updated';

									// if ($value == 1){
									// 	$('#statusIc_'+$index).removeClass('fa-toggle-on').addClass('fa-toggle-off').css({ 'color': '#bdbdbd' });
									// }
									// else
									// 	$('#statusIc_'+$index).removeClass('fa-toggle-off').addClass('fa-toggle-on').css({ 'color': 'green' });
								}
								else{
									$icon = 2;
									$msg = 'Failed updating to database';
								}
								popNotif_show($icon,$msg);
							}
						});
					}

				/* -----  Delete  ----- */
				function userDelete($sid,$sOrder){

					// style 'Confirm'
						$('#popBtn_confirm').css({'color': 'red'});
							
						$('#popBtn_confirm').hover(function(){
							$(this).css({'background-color': 'red','color': 'white'});
						},function(){
							$(this).css({'background-color': '','color': 'red'});
						});

					// style 'Cancel'
						$('#popBtn_cancel').hover(function(){
							$(this).css({'background-color': 'white','color': 'unset','font-weight': 'bold'});
						},function(){
							$(this).css({'background-color': '','color': '','font-weight': ''});
						});

					// show pop-alert
						$title = 'Are you sure?';
						$msg = 'This user will be permanently deleted';
						$confirm = 'Delete';
						$cancel = 'Cancel';
						$icon = 0;
					
					popAlert_show($title,$msg,$confirm,$cancel,$icon);

					$('#popBtn_confirm').click(function(){
						$.ajax({
							type :'POST',
							url  :'<?php echo dir_root; ?>php/ajax/post_userDelete.php?sid='+$sid,
							date :'',
							success:function(m){
								if (m == 1){
									location.reload();
								}
								else{
									// Notification
										$icon = 2;
										$msg = 'Failed to add user to database';
									popNotif_show($icon,$msg);
								}
							}
						});
					});
				}

				/* -----  Add-section  ----- */
				function userAdd(){

					// show pop-pWin
						$pWUrl = '<?php echo dir_root; ?>_global/html/getForm_manageUser_add.php';
						$pWTitle = 'Add User';
						$pWHeader = 'New User';
						$pWMsg = '';
						$pWConfirm = 'Add';
						$pWCancel = 'Cancel';
						$pWIcon = 5;
					
					popWindow_show($pWUrl,$pWTitle,$pWHeader,$pWMsg,$pWConfirm,$pWCancel,$pWIcon);

					$('#popWinBtn_confirm').click(function(e){
						
						var iFrame_func = $('#popWin_iFrame')[0].contentWindow;

						if (!iFrame_func.error_inUsername() && !iFrame_func.error_inEmail() && !iFrame_func.error_inPassword() && !iFrame_func.error_inPasswordConfirm() && !iFrame_func.error_inRole() && !iFrame_func.error_inSchool()){
							
							$username = iFrame_func.$('#username').val();
							$email = iFrame_func.$('#email').val();
							$password = iFrame_func.$('#password').val();
							
							$role_id = iFrame_func.$('#role').val();
							$school_id = iFrame_func.$('#school').val();
							$class_id = iFrame_func.$('#class').val();

							$role_val = iFrame_func.$('#role option:selected').html();
							$school_val = iFrame_func.$('#school option:selected').html();
							$class_val = iFrame_func.$('#class option:selected').html();

							$school_msg = '',$class_msg = '';

							// show pop-alert
								$title = 'Add New User?';
								
								if ($school_id != 0){
									$school_msg = '<span style="text-align:left;">'+'<b>School: </b>'+$school_val+'</span><br>';
								}
								else
									$school_msg = '';

								if ($class_id != 0){
									$class_msg = '<span style="text-align:left;">'+'<b>Class: </b>'+$class_val+'</span>';
								}
								else
									$class_msg = '';

								var msgP = [
									'Are you sure to add new user with the following details:<br>',
									'<b>Username: </b>'+$username+'<br>',
									'<b>Email: </b>'+$email+'<br>',
									'<b>Account-Type: </b>'+$role_val+'<br>',
									$school_msg,$class_msg
								].join('\n');
								
								$msg = msgP;
								
								$confirm = 'Confirm';
								$cancel = 'Cancel';
								$icon = 0;
							
							$('alertmsg').removeClass('popMsgEl_toCenter'); // make it to left
							popAlert_show($title,$msg,$confirm,$cancel,$icon);

							$('#popBtn_confirm').click(function(){
								$.ajax({
									type :'POST',
									url  :'<?php echo dir_root; ?>php/ajax/post_userAdd.php?username='+$username+'&email='+$email+'&password='+$password+'&role_id='+$role_id+'&school_id='+$school_id+'&class_id='+$class_id,
									date :'',
									success:function(m){
										console.log(m);
										if (m == 1){
											location.reload();
										}
										else{
											// Notification
												$icon = 2;
												$msg = 'Failed to add user to database';
											popNotif_show($icon,$msg);
										}
									}
								});
							});
						}
					});

					// $('#surveyAdd_row').removeClass('ctm-hide');
					// $('#btnAdd').addClass('ctm-hide');
				}
					/* -----  Add  ----- */
					$('#newName,#newUrl').keypress(function(e){
						if(e.which == 13){  // the enter key code
							// surveyAdd_toDb();
						}
					});
					function surveyAdd_toDb(){
						$newName = $('#newName').val();
						$newUrl = $('#newUrl').val();

						// (validate) 'Survey-Name' cannot be empty
						if ($newName == ''){
							
							// style 'Confirm'
								$('#popBtn_confirm').css({'background-color': 'white','color': 'black','font-weight': 'normal'});

								$('#popBtn_confirm').hover(function(){
									$(this).css({'font-weight': 'bold'});
								},function(){
									$(this).css({'font-weight': 'normal'});
								});

							// show pop-alert
								$title = 'Enter Survey-Name';
								$msg = 'Please enter the "survey-name" to add new survey';
								$confirm = 'Okay';
								$cancel = 'Cancel';
								$icon = 3;

							popAlert_btnSingle();
							popAlert_show($title,$msg,$confirm,$cancel,$icon);
						}
						else{
							$.ajax({
								type :'POST',
								url  :'<?php echo dir_root; ?>php/ajax/post_surveyAdd.php?newName='+$newName+'&newUrl='+$newUrl+'&newOrder=<?php echo($order_num); ?>',
								date :'',
								success:function(m){
									location.reload();
								}
							});
						}
					}
			/* -----  Add-section (close)  ----- */
			function surveyAdd_close(){
				$('#surveyAdd_row').addClass('ctm-hide');
				$('#btnAdd').removeClass('ctm-hide');
			}

			</script>

	</body>
</html>