<?php
/**
 * IP封禁管理
**/
include("../includes/common.php");
$title='IP封禁管理';

if(isset($_POST['ids']) && isset($_POST['do'])){
	$ids = $_POST['ids'];
	$do = $_POST['do'];
	if($do=='del'){
		$sql="";
		foreach($ids as $id){
			if($sql) $sql.=",";
			$sql.="'".$id."'";
		}
		$DB->exec("DELETE FROM pre_ip_ban WHERE id IN ($sql)");
		exit('{"code":0,"msg":"删除成功"}');
	}
}

if(isset($_GET['do'])){
	if($_GET['do']=='del'){
		$id = $_GET['id'];
		$DB->exec("DELETE FROM pre_ip_ban WHERE id='{$id}'");
		exit('{"code":0,"msg":"删除成功"}');
	}
}

if(isset($_POST['action']) && $_POST['action']=='add'){
	$ip = $_POST['ip'];
	$remark = $_POST['remark'];
	$expire = intval($_POST['expire']);
	
	if(empty($ip) || !filter_var($ip, FILTER_VALIDATE_IP)){
		exit('{"code":-1,"msg":"请输入有效的IP地址"}');
	}
	
	$expire_time = null;
	if($expire > 0){
		$expire_time = date('Y-m-d H:i:s', strtotime("+{$expire} days"));
	}
	
	$DB->exec("INSERT INTO pre_ip_ban (ip,ban_reason,ban_start,ban_end,ban_type,status,created_at,updated_at) VALUES ('{$ip}','{$remark}',NOW(),'{$expire_time}','manual',1,NOW(),NOW())");
	exit('{"code":0,"msg":"封禁成功"}');
}

include './head.php';

if($islogin==1){
}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

// 获取筛选参数
$kw = isset($_GET['kw']) ? trim($_GET['kw']) : '';

// 构建查询条件
$sql = "1=1";
if($kw){
	$sql .= " AND (ip LIKE '%{$kw}%' OR ban_reason LIKE '%{$kw}%')";
}

// 分页
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$pagesize = 20;
$total = $DB->getColumn("SELECT count(*) FROM pre_ip_ban WHERE {$sql}");
$pages = ceil($total / $pagesize);
$page = max(1, min($page, $pages));
$offset = ($page - 1) * $pagesize;

// 获取封禁列表
$rs = $DB->query("SELECT * FROM pre_ip_ban WHERE {$sql} ORDER BY id DESC LIMIT {$offset},{$pagesize}");
if($rs === false) {
    $rs = null;
}

// 检查IP是否已过期
function isExpired($ban_end){
	if(empty($ban_end)) return false;
	return strtotime($ban_end) < time();
}

// 获取剩余时间
function getRemainingTime($ban_end){
	if(empty($ban_end)) return '永久';
	$diff = strtotime($ban_end) - time();
	if($diff <= 0) return '已过期';

	$days = floor($diff / 86400);
	$hours = floor(($diff % 86400) / 3600);

	if($days > 0) return $days . '天' . $hours . '小时';
	return $hours . '小时';
}
?>
<div class="container">
    <!-- 页面标题 -->
    <div class="page-header-section">
        <div class="page-title">
            <div class="page-title-icon"><i class="fa fa-ban"></i></div>
            <h1>IP封禁管理</h1>
        </div>
        <div class="page-actions">
            <button type="button" class="btn btn-danger" onclick="showAddModal()"><i class="fa fa-plus"></i> 添加封禁</button>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon blue">
                    <i class="fa fa-list-ol"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_ip_ban"); ?></div>
                    <div class="stat-label">封禁总数</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon green">
                    <i class="fa fa-check-circle"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_ip_ban WHERE ban_end IS NULL OR ban_end>NOW()"); ?></div>
                    <div class="stat-label">生效中</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon orange">
                    <i class="fa fa-clock-o"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_ip_ban WHERE ban_end IS NOT NULL AND ban_end<=NOW()"); ?></div>
                    <div class="stat-label">已过期</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon red">
                    <i class="fa fa-calendar"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_ip_ban WHERE ban_start>'".date("Y-m-d")."'"); ?></div>
                    <div class="stat-label">今日封禁</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
        <form class="filter-form" method="get" action="">
            <div class="filter-group">
                <label>关键词搜索</label>
                <input type="text" class="form-control" name="kw" value="<?php echo htmlspecialchars($kw); ?>" placeholder="IP地址/备注">
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> 搜索</button>
                <a href="./ipban.php" class="btn btn-secondary"><i class="fa fa-refresh"></i> 重置</a>
            </div>
        </form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar-section">
        <div class="batch-actions">
            <button type="button" class="btn-batch delete" onclick="batchAction('del')"><i class="fa fa-trash"></i> 批量删除</button>
        </div>
        <div class="selected-count">已选择 <span id="selectedCount">0</span> 项</div>
    </div>

    <!-- 封禁列表 -->
    <div class="table-section">
        <div class="table-container">
            <table class="data-table" id="ipbanTable">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll"></th>
                        <th>ID</th>
                        <th>IP地址</th>
                        <th>备注</th>
                        <th>封禁时间</th>
                        <th>过期时间</th>
                        <th>剩余时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if($rs): while($row = $rs->fetch()):
                    $expired = isExpired($row['ban_end']);
                ?>
                    <tr>
                        <td><input type="checkbox" name="ids[]" value="<?php echo $row['id']; ?>"></td>
                        <td class="col-id"><?php echo $row['id']; ?></td>
                        <td>
                            <code style="font-family: monospace; background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-size: 13px;">
                                <?php echo htmlspecialchars($row['ip']); ?>
                            </code>
                        </td>
                        <td><?php echo htmlspecialchars($row['ban_reason'] ?: '-'); ?></td>
                        <td class="col-date">
                            <div class="primary"><?php echo $row['ban_start']; ?></div>
                        </td>
                        <td class="col-date">
                            <?php if($row['ban_end']): ?>
                            <div class="primary"><?php echo $row['ban_end']; ?></div>
                            <?php else: ?>
                            <span class="text-muted">永久</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span style="color: <?php echo $expired?'#ef4444':'#10b981'; ?>;">
                                <?php echo getRemainingTime($row['ban_end']); ?>
                            </span>
                        </td>
                        <td class="col-status">
                            <?php if($expired): ?>
                            <span class="status-badge banned">已过期</span>
                            <?php else: ?>
                            <span class="status-badge active">生效中</span>
                            <?php endif; ?>
                        </td>
                        <td class="col-actions">
                            <div class="action-group">
                                <button type="button" class="btn-action delete" onclick="delIpban('<?php echo $row['id']; ?>')" title="删除"><i class="fa fa-trash"></i></button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                    <tr>
                        <td colspan="9" style="text-align: center; padding: 40px; color: #6b7280;">
                            <i class="fa fa-exclamation-circle" style="font-size: 48px; margin-bottom: 16px; display: block;"></i>
                            数据加载失败，请稍后重试
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-wrapper">
            <div class="pagination-info">共 <?php echo $total; ?> 条记录，第 <?php echo $page; ?>/<?php echo max(1, $pages); ?> 页</div>
            <ul class="pagination">
                <?php if($page>1): ?>
                <li><a href="?page=<?php echo $page-1; ?>&kw=<?php echo urlencode($kw); ?>"><i class="fa fa-angle-left"></i></a></li>
                <?php else: ?>
                <li class="disabled"><span><i class="fa fa-angle-left"></i></span></li>
                <?php endif; ?>
                
                <?php
                $start = max(1, $page-2);
                $end = min($pages, $page+2);
                for($i=$start; $i<=$end; $i++):
                ?>
                <?php if($i==$page): ?>
                <li class="active"><span><?php echo $i; ?></span></li>
                <?php else: ?>
                <li><a href="?page=<?php echo $i; ?>&kw=<?php echo urlencode($kw); ?>"><?php echo $i; ?></a></li>
                <?php endif; ?>
                <?php endfor; ?>
                
                <?php if($page<$pages): ?>
                <li><a href="?page=<?php echo $page+1; ?>&kw=<?php echo urlencode($kw); ?>"><i class="fa fa-angle-right"></i></a></li>
                <?php else: ?>
                <li class="disabled"><span><i class="fa fa-angle-right"></i></span></li>
                <?php endif; ?>
            </ul>
        </div>
    </div>
</div>

<!-- 添加封禁模态框 -->
<div class="custom-modal-overlay" id="addModal">
    <div class="custom-modal">
        <div class="custom-modal-header" style="background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);">
            <h4><i class="fa fa-ban"></i> 添加IP封禁</h4>
            <button type="button" class="custom-modal-close" onclick="closeAddModal()">&times;</button>
        </div>
        <div class="custom-modal-body">
            <form id="addForm">
                <div class="form-row">
                    <label class="form-label">IP地址 <span style="color: #ef4444;">*</span></label>
                    <input type="text" class="form-input" name="ip" placeholder="例如: 192.168.1.1" required>
                    <div class="help-text">支持IPv4地址格式</div>
                </div>
                <div class="form-row">
                    <label class="form-label">封禁时长</label>
                    <select class="form-select" name="expire">
                        <option value="0">永久封禁</option>
                        <option value="1">1天</option>
                        <option value="3">3天</option>
                        <option value="7">7天</option>
                        <option value="15">15天</option>
                        <option value="30">30天</option>
                    </select>
                </div>
                <div class="form-row">
                    <label class="form-label">封禁原因/备注</label>
                    <input type="text" class="form-input" name="remark" placeholder="可选，记录封禁原因">
                </div>
            </form>
        </div>
        <div class="custom-modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeAddModal()">取消</button>
            <button type="button" class="btn btn-danger" onclick="addIpban()"><i class="fa fa-ban"></i> 确认封禁</button>
        </div>
    </div>
</div>

<script>
// 全选/取消全选
document.getElementById('selectAll').addEventListener('change', function() {
    var checkboxes = document.querySelectorAll('input[name="ids[]"]');
    checkboxes.forEach(function(cb) {
        cb.checked = this.checked;
    }, this);
    updateSelectedCount();
});

// 监听单个复选框变化
document.querySelectorAll('input[name="ids[]"]').forEach(function(cb) {
    cb.addEventListener('change', updateSelectedCount);
});

// 更新已选择数量
function updateSelectedCount() {
    var count = document.querySelectorAll('input[name="ids[]"]:checked').length;
    document.getElementById('selectedCount').textContent = count;
}

// 获取选中的ID
function getSelectedIds() {
    var ids = [];
    document.querySelectorAll('input[name="ids[]"]:checked').forEach(function(cb) {
        ids.push(cb.value);
    });
    return ids;
}

// 批量操作
function batchAction(action) {
    var ids = getSelectedIds();
    if(ids.length === 0) {
        alert('请选择要操作的封禁记录');
        return;
    }
    
    if(!confirm('确定要删除选中的 ' + ids.length + ' 条封禁记录吗？')) return;
    
    $.post('./ipban.php', {ids: ids, do: action}, function(data) {
        if(data.code === 0) {
            alert(data.msg);
            location.reload();
        } else {
            alert('操作失败');
        }
    }, 'json');
}

// 删除封禁
function delIpban(id) {
    if(!confirm('确定要删除该封禁记录吗？')) return;
    $.get('./ipban.php?do=del&id=' + id, function(data) {
        if(data.code === 0) {
            alert(data.msg);
            location.reload();
        } else {
            alert('删除失败');
        }
    }, 'json');
}

// 显示添加模态框
function showAddModal() {
    document.getElementById('addModal').classList.add('show');
}

// 关闭添加模态框
function closeAddModal() {
    document.getElementById('addModal').classList.remove('show');
}

// 添加封禁
function addIpban() {
    var form = document.getElementById('addForm');
    var formData = new FormData(form);
    
    var ip = formData.get('ip').trim();
    if(!ip) {
        alert('请输入IP地址');
        return;
    }
    
    // 简单的IP格式验证
    var ipPattern = /^(\d{1,3}\.){3}\d{1,3}$/;
    if(!ipPattern.test(ip)) {
        alert('请输入有效的IPv4地址');
        return;
    }
    
    $.ajax({
        url: './ipban.php',
        type: 'POST',
        data: {
            action: 'add',
            ip: ip,
            expire: formData.get('expire'),
            remark: formData.get('remark')
        },
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                closeAddModal();
                location.reload();
            } else {
                alert(data.msg || '添加失败');
            }
        },
        error: function() {
            alert('网络错误，请重试');
        }
    });
}

// 点击遮罩关闭模态框
document.getElementById('addModal').addEventListener('click', function(e) {
    if(e.target === this) {
        closeAddModal();
    }
});
</script>

</body>
</html>
