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

// Move all header-modifying operations to the top
$act = $_GET['act'] ?? '';

if ($act == "save") {
    $isedit = false;
    $id = $_POST['id'] ?? '';
    if ($id != "" && is_numeric($id)) {
        $isedit = true;
    }
    $IPAddress = textEncode($_POST['IPAddress']);

    if ($isedit) {
        $sql = "SELECT * FROM allowip WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $sql = "UPDATE allowip SET IPAddress = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("si", $IPAddress, $id);
            $stmt->execute();
        } else {
            $sql = "INSERT INTO allowip (IPAddress) VALUES (?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("s", $IPAddress);
            $stmt->execute();
        }

        $page = $_GET['Page'] ?? '';
        $keys = urlencode($_GET['Keys'] ?? '');
        $ord = urlencode($_GET['Ord'] ?? '');
        header("Location: ?keys=$keys&Ord=$ord&Page=$page");
        exit;
    } else {
        $sql = "INSERT INTO allowip (IPAddress) VALUES (?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $IPAddress);
        $stmt->execute();
        
        header("Location: ?");
        exit;
    }
}

if ($act == "postchk") {
    $keys = urlencode($_GET['Keys'] ?? '');
    $ord = urlencode($_GET['Ord'] ?? '');
    $page = $_GET['Page'] ?? '';
    
    if (isset($_POST['chkbox']) && is_array($_POST['chkbox'])) {
        $ids = array_map('intval', $_POST['chkbox']);
        $sql = "DELETE FROM allowip WHERE id IN (" . implode(',', array_fill(0, count($ids), '?')) . ")";
        $types = str_repeat('i', count($ids));
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$ids);
        $stmt->execute();
    }
    
    header("Location: ?Keys=$keys&Ord=$ord&Page=$page");
    exit;
}

?>
<!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" />
<link rel="stylesheet" href="css/jquery.galpop.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="js/jquery.galpop.min.js"></script>
</head>
<body>
<div id="man_zone">
<?php
if ($act == "add" || $act == "edit") {
    $id = $_GET['id'] ?? '';
    $isedit = false;
    $IPAddress = '';
    
    if ($id != "" && is_numeric($id)) {
        $isedit = true;
        $sql = "SELECT * FROM allowip WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            $IPAddress = textUncode($row['IPAddress']);
        } 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">
    <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
        <tbody>
            <tr>
                <th width="8%">IP</th>
                <td><input type="text" id="IPAddress" name="IPAddress" value="<?php echo $IPAddress; ?>" class="txt1" /><input type="hidden" name="id" value="<?php echo $id; ?>" /></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'] ?? '';

// Get total count first
$sql = "SELECT COUNT(*) as total FROM allowip WHERE IPAddress LIKE ?";
$stmt = $conn->prepare($sql);
$search = '%' . $keyscode . '%';
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$total_records = $row['total'];

// Pagination settings
$records_per_page = 10;
$total_pages = ceil($total_records / $records_per_page);

if ($page == "") $page = 1;
if ($page == "end") $page = $total_pages;
if (!is_numeric($page) || $page < 1) $page = 1;
$page = (int)$page;
if ($page > $total_pages) $page = $total_pages;

$start = ($page - 1) * $records_per_page;

// Get paginated results
$sql = "SELECT * FROM allowip WHERE IPAddress LIKE ? ORDER BY id DESC LIMIT ?, ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sii", $search, $start, $records_per_page);
$stmt->execute();
$results = $stmt->get_result();

$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 width="60%">IP</th>
            <th width="30%">操作</th>
        </tr>
    </thead>
    <tbody>
    <?php
    if ($results->num_rows > 0) {
        $tempNum = ($page - 1) * $records_per_page;
        while ($row = $results->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['IPAddress']; ?></td>
                <td align="center"><a href="?Keys=<?php echo $keys; ?>&Ord=<?php echo $ord; ?>&Page=<?php echo $page; ?>&act=edit&id=<?php echo $row['id']; ?>" class="ico_edit ico">修改</a></td>
            </tr>
            <?php
        }
    } else {
        if ($keys == "") {
            ?>
            <tr>
                <td align="center" colspan="4">Sorry,当前暂无信息</td>
            </tr>
            <?php
        } else {
            ?>
            <tr>
                <td align="center" colspan="4"><a href="?">Sorry,没有找到"<?php echo $keyscode; ?>"相关的信息,点击返回</a></td>
            </tr>
            <?php
        }
    }
    ?>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="5">
                <div class="showpagebox">
                <?php
                if ($total_pages > 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 >= $total_pages) {
                        $startPage = 1;
                        $endPage = $total_pages;
                    } else {
                        if ($page <= $pagelen + 1) {
                            $startPage = 1;
                            $endPage = $pagelen * 2 + 1;
                        } else {
                            $startPage = $page - $pagelen;
                            $endPage = $page + $pagelen;
                        }
                        if ($page + $pagelen > $total_pages) {
                            $startPage = $total_pages - $pagelen * 2;
                            $endPage = $total_pages;
                        }
                    }

                    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 < $total_pages) {
                        if ($total_pages - $page > $pagelen) {
                            echo "<a href=\"{$pageName}Page=$total_pages\">...$total_pages</a>";
                        }
                        echo "<a href=\"{$pageName}Page=" . ($page+1) . "\">下一页</a>";
                        echo "<a href=\"{$pageName}Page=$total_pages\">尾页</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='+encodeURIComponent(document.getElementById('keys').value)}" />
                    <input type="button" id="searchgo" value="go" onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)" />
                </div>
                <div class="postchkbox">
                    <select id="chkact" name="chkact">
                        <option value="1">请选择</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>