<?php
include "conn.php";
checkLogin("信息管理");

$act = $_GET['act'] ?? '';

// Handle all actions that might need header redirects first
if($act == "save") {
    $isEdit = false;
    $id = $_POST['id'] ?? '';
    if($id != '' && is_numeric($id)) {
        $isEdit = true;
    }
    
    $em_user = textEncode($_POST['em_user']);
    $em_password = textEncode($_POST['em_password']);
    $re_password = textEncode($_POST['re_password']);
    $em_role = $_POST['em_role'];
    $em_code = textEncode($_POST['em_code']);
    $em_email = textEncode($_POST['em_email']);
    $em_tel = textEncode($_POST['em_tel']);
    $nullPwd = false;

    if(empty($em_password)) {
        $nullPwd = true;
    }

    if($em_password != $re_password) {
        echo "<script>alert('两次密码输入不一致');history.back();</script>";
        exit;
    }

    if($isEdit) {
        $query = "SELECT * FROM employee WHERE id=$id";
        $result = $conn->query($query);
        if($result->num_rows > 0) {
            $password_sql = $nullPwd ? "" : ",em_password='".md5($em_password)."'";
            $sql = "UPDATE employee SET em_user='$em_user'$password_sql,em_role=$em_role,
                    em_code='$em_code',em_email='$em_email',em_tel='$em_tel' WHERE id=$id";
            $conn->query($sql);
        }
        
        $page = $_GET['Page'] ?? '';
        $keys = urlencode($_GET['Keys'] ?? '');
        $ord = urlencode($_GET['Ord'] ?? '');
        header("Location: ?keys=$keys&Ord=$ord&Page=$page");
        exit;
    } else {
        if($nullPwd) {
            $em_password = "MTB".$em_code;
        }
        
        $sql = "INSERT INTO employee(em_user,em_password,em_role,em_code,em_email,em_tel) 
                VALUES('$em_user','".md5($em_password)."',$em_role,'$em_code','$em_email','$em_tel')";
        $conn->query($sql);
        header("Location: ?");
        exit;
    }
}

if($act == "postchk") {
    $keys = urlencode($_GET['Keys'] ?? '');
    $ord = urlencode($_GET['Ord'] ?? '');
    $page = $_GET['Page'] ?? '';
    $chkact = $_POST['chkact'] ?? '';
    
    if(isset($_POST['chkbox']) && is_array($_POST['chkbox'])) {
        $sqlStr = "DELETE FROM employee WHERE id IN (" . implode(',', $_POST['chkbox']) . ")";
        $conn->query($sqlStr);
    }
    
    header("Location: ?Keys=$keys&Ord=$ord&Page=$page");
    exit;
}

// Now start HTML output
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>管理区域</title>
<link rel="stylesheet" href="css/common.css" type="text/css" />
<script language="javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/js.js"></script>
<script type="text/javascript" src="xheditor-1.1.9/xheditor-1.1.9-zh-cn.min.js"></script>
</head>

<body>
<div id="man_zone">
<?php
if($act == "add" || $act == "edit") {
    $id = $_GET['id'] ?? '';
    $isEdit = false;
    if($id != '' && is_numeric($id)) {
        $isEdit = true;
    }
    
    if($isEdit) {
        $query = "SELECT * FROM employee WHERE id=$id";
        $result = $conn->query($query);
        if($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $em_user = textUncode($row['em_user']);
            $em_role = $row['em_role'];
            $em_code = textUncode($row['em_code']);
            $em_email = textUncode($row['em_email']);
            $em_tel = textUncode($row['em_tel']);
        } else {
            $isEdit = false;
        }
    }

    $page = $_GET['Page'] ?? '';
    $keys = urlencode($_GET['Keys'] ?? '');
    $ord = urlencode($_GET['Ord'] ?? '');
    $hrefstr = "?keys=$keys&Ord=$ord&Page=$page";
    ?>
    
    <form name="form1" method="post" action="<?php echo $hrefstr; ?>&act=save" onSubmit="return subform2();">
    <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
        <tbody>
            <tr>
                <th width="8%">用户名</th>
                <td><input type="text" id="em_user" name="em_user" value="<?php echo $em_user ?? ''; ?>" required class="txt-short" />
                <input type="hidden" name="id" value="<?php echo $id; ?>" /></td>
            </tr>
            <tr>
                <th width="8%">密码</th>
                <td><input type="password" id="em_password" name="em_password" value="" class="txt-short"/></td>
            </tr>
            <tr>
                <th width="8%">重复密码</th>
                <td><input type="password" id="re_password" name="re_password" value="" class="txt-short"/></td>
            </tr>
            <tr>
                <th width="8%">工号</th>
                <td><input type="text" id="em_code" name="em_code" value="<?php echo $em_code ?? ''; ?>" class="txt1" /></td>
            </tr>
            <tr>
                <th width="8%">角色</th>
                <td><select name="em_role">
                    <option value="0">组长</option>
                    <?php
                    $query = "SELECT id,em_user FROM employee WHERE em_role=0";
                    $result = $conn->query($query);
                    while($row = $result->fetch_assoc()) {
                        $selected = ($row['id'] == ($em_role ?? '')) ? ' selected="selected"' : '';
                        echo "<option value=\"{$row['id']}\"$selected>组长:{$row['em_user']}</option>";
                    }
                    ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th width="8%">邮箱</th>
                <td><input type="text" id="em_email" name="em_email" value="<?php echo $em_email ?? ''; ?>" class="txt1" /></td>
            </tr>
            <tr>
                <th width="8%">手机</th>
                <td><input type="text" id="em_tel" name="em_tel" value="<?php echo $em_tel ?? ''; ?>" class="txt1" /></td>
            </tr>
            <tr>
                <th></th>
                <td>
                    <input type="submit" name="save" id="save" value="确定" class="btn1" />
                    <input type="reset" name="save" id="save" value="重置" class="btn1" />
                    <input type="button" value="返回" class="btn1" onClick="location.href='<?php echo $hrefstr; ?>'" />
                </td>
            </tr>
        </tbody>
    </table>
    </form>
    </div>
    </body>
    </html>
    <?php
    exit;
}

$keys = $_GET['Keys'] ?? '';
$keyscode = textEncode($keys);
$ord = $_GET['Ord'] ?? '';
$page = $_GET['Page'] ?? '';

$query = "SELECT id,em_user,em_code,em_role FROM employee 
          WHERE em_user LIKE '%$keyscode%' OR em_code LIKE '%$keyscode%' 
          ORDER BY Id DESC";
$result = $conn->query($query);

$keys = urlencode($keys);
$ord = urlencode($ord);
$hrefstr = "?keys=$keys";
?>

<form id="form1" method="post" action="?act=postchk&Keys=<?php echo $keys; ?>&Ord=<?php echo $ord; ?>&Page=<?php echo $page; ?>" onSubmit="return false">
<table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
    <thead>
        <tr>
            <th width="4%"><input type="checkbox" name="chkall" id="chkall" onClick="chkboxall(this,'chkbox')" /></th>
            <th width="6%">序号</th>
            <th>姓名</th>
            <th>工号</th>
            <th>角色</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
    <?php
    if($result->num_rows > 0) {
        $pageSize = 13;
        $totalRows = $result->num_rows;
        $totalPages = ceil($totalRows / $pageSize);
        
        if($page == '') $page = 1;
        if($page == 'end') $page = $totalPages;
        if(!is_numeric($page) || $page < 1) $page = 1;
        $page = (int)$page;
        if($page > $totalPages) $page = $totalPages;
        
        $offset = ($page - 1) * $pageSize;
        $query .= " LIMIT $offset, $pageSize";
        $result = $conn->query($query);
        
        $tempNum = $offset;
        while($row = $result->fetch_assoc()) {
            $tempNum++;
            ?>
            <tr onMouseOver="this.style.background='#F7FCFF'" onMouseOut="this.style.background='#FFFFFF'">
                <td align="center"><input type="checkbox" name="chkbox[]" value="<?php echo $row['id']; ?>" /></td>
                <td align="center"><?php echo $tempNum; ?></td>
                <td align="center"><?php echo $row['em_user']; ?></td>
                <td align="center"><?php echo $row['em_code']; ?></td>
                <td align="center"><?php echo $row['em_role'] == 0 ? '组长' : '组员'; ?></td>
                <th><a class="ico_edit" href="?act=edit&Keys=<?php echo $keys; ?>&Ord=<?php echo $ord; ?>&Page=<?php echo $page; ?>&id=<?php echo $row['id']; ?>">修改</a></th>
            </tr>
            <?php
        }
    } else {
        if($keys == '') {
            echo '<tr><td align="center" colspan="6">Sorry,当前暂无信息</td></tr>';
        } else {
            echo '<tr><td align="center" colspan="6"><a href="?">Sorry,没有找到"'.$keyscode.'"相关的信息,点击返回</a></td></tr>';
        }
    }
    ?>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="6">
                <div class="showpagebox">
                <?php
                if($totalPages > 1) {
                    $pageName = "?Keys=$keys&Ord=$ord&";
                    $pageLen = 3;
                    
                    if($page > 1) {
                        echo "<a href=\"{$pageName}Page=1\">首页</a>";
                        echo "<a href=\"{$pageName}Page=".($page-1)."\">上一页</a>";
                    }
                    
                    if($pageLen * 2 + 1 >= $totalPages) {
                        $startPage = 1;
                        $endPage = $totalPages;
                    } else {
                        if($page <= $pageLen + 1) {
                            $startPage = 1;
                            $endPage = $pageLen * 2 + 1;
                        } else {
                            $startPage = $page - $pageLen;
                            $endPage = $page + $pageLen;
                        }
                        if($page + $pageLen > $totalPages) {
                            $startPage = $totalPages - $pageLen * 2;
                            $endPage = $totalPages;
                        }
                    }
                    
                    for($i = $startPage; $i <= $endPage; $i++) {
                        if($i == $page) {
                            echo "<a class=\"current\">$i</a>";
                        } else {
                            echo "<a href=\"{$pageName}Page=$i\">$i</a>";
                        }
                    }
                    
                    if($page < $totalPages) {
                        if($totalPages - $page > $pageLen) {
                            echo "<a href=\"{$pageName}Page=$totalPages\">...$totalPages</a>";
                        }
                        echo "<a href=\"{$pageName}Page=".($page+1)."\">下一页</a>";
                        echo "<a href=\"{$pageName}Page=$totalPages\">尾页</a>";
                    }
                    
                    echo "<input type=\"text\" id=\"Pagego\" value=\"$page\" onFocus=\"if(this.value == '$page'){this.value='';}\" onBlur=\"if(this.value == ''){this.value='$page';}\" onKeyUp=\"this.value=this.value.replace(/\D/g,'')\" onKeyDown=\"if(event.keyCode==13){location.href='{$pageName}Page='+document.getElementById('Pagego').value}\" />";
                }
                ?>
                </div>
                <div class="searchbox">
                    <input type="text" id="keys" value="<?php echo $keyscode == '' ? '请输入搜索关键词' : $keyscode; ?>" 
                           onFocus="if(this.value == '<?php echo $keyscode == '' ? '请输入搜索关键词' : $keyscode; ?>'){this.value='';}" 
                           onBlur="if(this.value == ''){this.value='<?php echo $keyscode == '' ? '请输入搜索关键词' : $keyscode; ?>';}" 
                           onKeyDown="if(event.keyCode==13){location.href='?Keys='+escape(document.getElementById('keys').value)}" />
                    <input type="button" id="searchgo" value="go" onClick="location.href='?Keys='+escape(document.getElementById('keys').value)" />
                </div>
                <div class="postchkbox">
                    <select id="chkact" name="chkact">
                        <option value="1">显示</option>
                        <option value="0">隐藏</option>
                        <option value="-1">删除</option>
                    </select>
                    <input type="button" value="执行" onClick="postchk(1)" class="btn1" />
                    <input type="button" value="新增" onClick="location.href='?act=add'" class="btn1" />
                </div>
            </td>
        </tr>
    </tfoot>
</table>
</form>
</div>
</body>
</html>