<?php 
require_once 'library/top_application.php';
require_once 'library/logged.php';

if (isset($_GET['action'])) {
  $action=$_GET['action'];
}

if (isset($_GET['id'])) {
  $id=$_GET['id'];
}

if ($action != 'add' && $action != 'edit'){
	$action='add';
}
//權限 
$sql_right = mysql_query('SELECT `manage_user` FROM `'.TBL_USER.'` WHERE `uid` = '.$_SESSION['Logged_Uid']);
$row_right = mysql_fetch_assoc($sql_right);

if($row_right['manage_user'] != 1){
	header("Location: listUser.php");
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "fHtmlEditor")){
	$new_username = txt_only($_POST['username']);
	$new_salt = getRandomString();
	$new_password = getRandomString();
	$hashed_password = hash_pw($new_password, $new_salt);
	$new_email = isEmail(trim($_POST['email']));
	
	//validate before send
	if(!$new_username){
		die ('Error: 請輸入管理員 ID');
	}

	sendNewAdmin($new_username, $new_email, $new_password);
	mysql_query("INSERT INTO `".TBL_USER."` (username, password, salt, email, create_date) VALUES ('$new_username', '$hashed_password', '$new_salt', '$new_email', NOW())", $connePaper) or die(mysql_error());
	header("Location: close_iframe.html");
	
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "fHtmlEditor")){
	$u_id = $_POST['u_id'];
	$new_username = $_POST['username'];
	$new_email = $_POST['email'];
	
	mysql_query("UPDATE `".TBL_USER."` SET `username` = '$new_username', `email` = '$new_email' WHERE `uid` = '$u_id'", $connePaper) or die(mysql_error());
	header("Location: close_iframe.html");
}


if ($action == 'edit'){
	$sql = mysql_query("SELECT `uid`, `username`, `email` FROM `".TBL_USER."` WHERE uid = ".$id);
	$row = mysql_fetch_assoc($sql);
} 
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Artech Creative</title>

<link href="css/css_admin.css" rel="stylesheet" type="text/css">




<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui-min.js"></script>
<script type="text/javascript" src="../js/check_function.js"></script>
<!--[if IE]>
    <script src="../js/html5.js"></script>
<![endif]--> 
<script type="text/javascript" src="../js2/password.js"></script>
<script type="text/javascript" src="../js2/pGenerator.jquery.js"></script>

<script type="text/javascript">

function OnFormSubmit(){
	var error = false;															
	var email = $('input[name=email]').val();
	var confirm_email = $('input[name=confirm_email]').val();
	
	//var new_pw = $.trim($('input[name=new_password]').val());
	var u_name = $.trim($('input[name=username]').val());
	
	if(!u_name){
		error = true;
		$('#er_u_name').html('<span style="color:red">請輸入管理員 ID</span>')
		$('input[name=username]').addClass("error");
	}
	if(!confirm_email){
		error = true;
		$('#er_confirm_email').html('<span style="color:red">請重複輸入電郵</span>')
		$('input[name=confirm_email]').addClass("error");
	}
	if(confirm_email != email){
		error = true;
		$('#er_confirm_email').html('<span style="color:red">電郵不符</span>')
		$('input[name=confirm_email]').addClass("error");
	}
	
	if(!email){
		error = true;
		$('#er_email').html('<span style="color:red">請輸入電郵</span>')
		$('input[name=email]').addClass("error");
	} else {
		if (checkEmail(email) == false){
			error = true;
			$('input[name=email]').addClass("error");
			$('#er_email').show();
			$('#er_email').html('<span style="color: red">電郵格式錯誤</span>');
		} else {
			$('#er_email').hide();
			$('input[name=email]').removeClass("error");
		}
	}
	
	if (error == true){
		return
	} else {
		document.fHtmlEditor.submit();
	}
}
$(document).ready(function(){
    $("input[name=email]").change(function(){
		var this_value = $(this).val();	
	
		if (checkEmail(this_value) == false){
			$(this).addClass("error");
			$('#er_email').show();
			$('#er_email').html('<span style="color: red">電郵格式錯誤</span>');
		} else {
			$('#er_email').hide();
			$(this).removeClass("error");
		}
	})
	
    $('#myLink').pGenerator({
        'bind': 'click',
        'passwordElement': 'input[name=new_password]',
        'passwordLength': 10,
        'uppercase': true,
        'lowercase': true,
        'numbers':   true,
        'specialChars': false,
        'onPasswordGenerated': function(generatedPassword) {
        	
        }
    });
});


function clearError(){
	$('input[name=email]').removeClass('error');
	$('input[name=confirm_email]').removeClass('error');
	$('input[name=username]').removeClass('error');
}
</script>
</head>
<body  style="background:#fff">
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="padding:20px;" >
  <tr>
    <td><h2><?php if ($action=='add'){ echo '新增管理員';} else { echo '修改管理員';}?></h2></td>
  </tr>
  <tr>
    <td><hr></td>
  </tr>
  <tr>
    <td><table width="100%" border="0" cellpadding="4" cellspacing="0" >
      <tr>
        <td>
          <form name="fHtmlEditor" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
            <table width="100%"  border="0" cellpadding="2" cellspacing="1" class="content">
                <tr>
                <td width="120">管理員 ID:</td>
                <td><input name="username" type="text"  maxlength="50" style="width:150px;" value="<?php if ($action=='add'){ echo '';} else {echo $row['username'];}?>"> <span id="er_u_name"></span></td>
              </tr>
              <tr>
                <td>電郵:</td>
                <td><input name="email" type="text"  maxlength="100" style="width:300px;" value="<?php if ($action=='add'){ echo '';} else {echo $row['email'];}?>"> <span id="er_email"></span></td>
              </tr>
              <tr>
                <td>確認電郵:</td>
                <td><input name="confirm_email" type="text"  maxlength="100" style="width:300px;" > <span id="er_confirm_email"></span></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
              </table>
            <table width="100%" border="0" cellpadding="0" cellspacing="0" class="content">
              <tr>
              <td height="15"></td>
            </tr>
          </table>
          <?php if ($action =='edit'){?><input type="hidden" name="u_id" value="<?php echo $row['uid'];?>"><?php }?>
           <input type="hidden" name="<?php if ($action =='add'){ echo 'MM_insert';} else { echo 'MM_update';}?>" value="fHtmlEditor">
            <input type="button" name="Submit"  onClick="OnFormSubmit()" id="btn_submit">
          </form>
        </td>
      </tr>
      <tr>
        <td>&nbsp;</td>
      </tr>
    </table></td>
  </tr>
</table>


</body>
</html>
