<?php
/**
 * 清除登录锁定状态的工具脚本
 * 仅在已登录状态下可用
 */
require __DIR__ . '/../app/bootstrap.php';
require __DIR__ . '/../app/database.php';

if (!is_logged_in() || !is_super_admin()) {
    die('Access denied');
}

$action = isset($_GET['action']) ? trim((string)$_GET['action']) : '';
$username = isset($_GET['username']) ? trim((string)$_GET['username']) : '';

if ($action === 'clear_all') {
    // 清除所有锁定
    $dir = __DIR__ . '/../runtime/login_throttle';
    if (is_dir($dir)) {
        foreach (glob($dir . '/*.json') as $file) {
            @unlink($file);
        }
    }
    echo json_encode(['success' => true, 'message' => '已清除所有登录锁定记录']);
    exit;
}

if ($action === 'clear_file') {
    // 清除特定文件的锁定
    $file = isset($_GET['file']) ? trim((string)$_GET['file']) : '';
    $filepath = __DIR__ . '/../runtime/login_throttle/' . $file;
    
    // 安全检查：确保文件在正确的目录中
    $realpath = realpath($filepath);
    $expectedDir = realpath(__DIR__ . '/../runtime/login_throttle');
    
    if ($realpath && strpos($realpath, $expectedDir) === 0 && file_exists($realpath)) {
        @unlink($realpath);
        echo json_encode(['success' => true, 'message' => '已清除锁定记录']);
    } else {
        echo json_encode(['success' => false, 'message' => '文件不存在或路径无效']);
    }
    exit;
}

if ($action === 'clear_user' && $username !== '') {
    // 清除特定用户的锁定
    require_once __DIR__ . '/../app/bootstrap.php';
    
    // 重建 login_throttle_key 逻辑
    $ip = request_remote_addr();
    $key = md5(strtolower($username) . '|' . $ip);
    $file = __DIR__ . '/../runtime/login_throttle/' . $key . '.json';
    
    if (file_exists($file)) {
        @unlink($file);
        echo json_encode(['success' => true, 'message' => '已清除 ' . e($username) . ' 的登录锁定记录']);
    } else {
        echo json_encode(['success' => false, 'message' => '未找到 ' . e($username) . ' 的锁定记录']);
    }
    exit;
}

// 显示当前锁定状态
$dir = __DIR__ . '/../runtime/login_throttle';
$locks = array();
if (is_dir($dir)) {
    foreach (glob($dir . '/*.json') as $file) {
        $data = @json_decode((string)@file_get_contents($file), true);
        if (is_array($data)) {
            $locks[] = array(
                'file' => basename($file),
                'count' => isset($data['count']) ? (int)$data['count'] : 0,
                'locked_until' => isset($data['locked_until']) ? (int)$data['locked_until'] : 0,
                'updated_at' => isset($data['updated_at']) ? (string)$data['updated_at'] : '',
                'remaining_seconds' => max(0, (isset($data['locked_until']) ? (int)$data['locked_until'] : 0) - time())
            );
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>清除登录锁定</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 20px; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        h1 { color: #333; }
        .button { display: inline-block; padding: 8px 16px; margin: 5px; border-radius: 4px; cursor: pointer; text-decoration: none; border: none; font-size: 14px; }
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; }
        .btn-primary { background: #2563eb; color: white; }
        .btn-primary:hover { background: #1d4ed8; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #e5e7eb; }
        th { background: #f9fafb; font-weight: 600; }
        .status-locked { color: #dc2626; font-weight: 600; }
        .status-free { color: #16a34a; }
        .empty { text-align: center; padding: 40px; color: #999; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 清除登录锁定状态</h1>
        
        <div style="margin: 20px 0;">
            <button class="button btn-danger" onclick="clearAll()">清除所有锁定</button>
        </div>

        <h2>当前锁定状态</h2>
        <?php if (empty($locks)): ?>
            <div class="empty">暂无锁定记录</div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>文件</th>
                        <th>失败次数</th>
                        <th>锁定状态</th>
                        <th>剩余秒数</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($locks as $lock): ?>
                    <tr>
                        <td><code><?php echo e($lock['file']); ?></code></td>
                        <td><?php echo (int)$lock['count']; ?></td>
                        <td>
                            <?php if ($lock['remaining_seconds'] > 0): ?>
                                <span class="status-locked">已锁定</span>
                            <?php else: ?>
                                <span class="status-free">已解锁</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo (int)$lock['remaining_seconds']; ?>s</td>
                        <td><?php echo e($lock['updated_at']); ?></td>
                        <td>
                            <button class="button btn-primary" onclick="clearByFile('<?php echo e($lock['file']); ?>')">清除</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <script>
    function clearAll() {
        if (!confirm('确定要清除所有登录锁定记录吗？')) return;
        fetch('clear-login-lock.php?action=clear_all')
            .then(r => r.json())
            .then(d => {
                alert(d.message);
                location.reload();
            })
            .catch(e => alert('错误: ' + e));
    }

    function clearByFile(filename) {
        if (!confirm('确定要清除此锁定记录吗？')) return;
        fetch('clear-login-lock.php?action=clear_file&file=' + encodeURIComponent(filename))
            .then(r => r.json())
            .then(d => {
                alert(d.message);
                location.reload();
            })
            .catch(e => alert('错误: ' + e));
    }
    </script>
</body>
</html>
