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

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

// Process all actions that might need headers/redirects first
if ($act == 'save') {
    $isEdit = false;
    $id = $_POST['id'] ?? '';
    if (!empty($id) && is_numeric($id)) {
        $isEdit = true;
    }
    
    $ch_name = textEncode($_POST['ch_name'] ?? '');

    if ($isEdit) {
        $stmt = $conn->prepare("SELECT * FROM qudao WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $stmt = $conn->prepare("UPDATE qudao SET ch_name = ? WHERE id = ?");
            $stmt->bind_param("si", $ch_name, $id);
            $stmt->execute();
        }
        
        $page = $_GET['Page'] ?? '';
        $keys = urlencode($_GET['Keys'] ?? '');
        $ord = urlencode($_GET['Ord'] ?? '');
        header("Location: ?keys=$keys&Ord=$ord&Page=$page");
        exit;
    } else {
        $stmt = $conn->prepare("INSERT INTO qudao (ch_name) VALUES (?)");
        $stmt->bind_param("s", $ch_name);
        $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']);
        $idList = implode(',', $ids);
        
        if (!empty($idList)) {
            $stmt = $conn->prepare("DELETE FROM qudao WHERE id IN ($idList)");
            $stmt->execute();
        }
    }
    
    header("Location: ?Keys=$keys&Ord=$ord&Page=$page");
    exit;
}

// Now we can start HTML output
?>
<!DOCTYPE html>
<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="xheditor-1.1.9/xheditor-1.1.9-zh-cn.min.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;
    $ch_name = '';
    
    if (!empty($id) && is_numeric($id)) {
        $isEdit = true;
        $stmt = $conn->prepare("SELECT * FROM qudao WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            $ch_name = textUncode($row['ch_name']);
        } 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%">来源</th>
                <td><input type="text" id="ch_name" name="ch_name" value="<?php echo $ch_name; ?>" 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;
}

// Main listing page
$keys = $_GET['Keys'] ?? '';
$keyscode = textEncode($keys);
$ord = $_GET['Ord'] ?? '';
$page = $_GET['Page'] ?? '';
$ordStr = !empty($ord) ? "$ord," : "";

$sql = "SELECT * FROM qudao WHERE ch_name LIKE ? ORDER BY id DESC";
$stmt = $conn->prepare($sql);
$searchTerm = "%$keyscode%";
$stmt->bind_param("s", $searchTerm);
$stmt->execute();
$result = $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%">渠道来源</th>
            <th width="30%">操作</th>
        </tr>
    </thead>
    <tbody>
    <?php
    if ($result->num_rows > 0) {
        $pageSize = 10;
        $totalRecords = $result->num_rows;
        $totalPages = ceil($totalRecords / $pageSize);
        
        if (empty($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;
        $sql .= " LIMIT ?, ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sii", $searchTerm, $offset, $pageSize);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $tempNum = $pageSize * ($page - 1);
        
        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['ch_name']; ?></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 (empty($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="4">
                <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 empty($keyscode) ? '请输入搜索关键词' : $keyscode; ?>" 
                           onFocus="if(this.value == '<?php echo empty($keyscode) ? '请输入搜索关键词' : $keyscode; ?>'){this.value='';}" 
                           onBlur="if(this.value == ''){this.value='<?php echo empty($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>
<script>
$('.click-open-iframe').galpop({
    contentType: 'iframe',
});
</script>
</body>
</html>