<?php
/**
 * 炎酷CMS - 后台登录页
 * 验证码 + 账号密码；连续输错 5 次锁定 10 分钟（锁定状态存 data/ 下文件，持久化）
 */
define('YKCMS', 1);
session_start();
require_once dirname(dirname(__DIR__)) . '/inc/functions.php';

// 已登录直接进后台
if (!empty($_SESSION['yk_admin_id'])) {
    header('Location: index.php');
    exit;
}

$err = '';
$maxFails = 5;
$lockSecs = 600; // 10 分钟

// 锁定/失败计数文件（按用户名持久化）
function yk_lock_file($username) {
    return dirname(dirname(__DIR__)) . '/data/login_' . md5(strtolower(trim($username))) . '.json';
}
function yk_lock_read($username) {
    $f = yk_lock_file($username);
    if (is_file($f)) {
        $d = json_decode((string)file_get_contents($f), true);
        if (is_array($d)) return $d;
    }
    return array('fails' => 0, 'lock_until' => 0);
}
function yk_lock_write($username, $data) {
    @file_put_contents(yk_lock_file($username), json_encode($data));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? (string)$_POST['password'] : '';
    $captcha  = isset($_POST['captcha']) ? trim($_POST['captcha']) : '';

    // 验证码校验（一次性）
    $sessCap = isset($_SESSION['yk_captcha']) ? $_SESSION['yk_captcha'] : '';
    unset($_SESSION['yk_captcha']);
    if ($sessCap === '' || strtolower($captcha) !== strtolower($sessCap)) {
        $err = '验证码错误';
    } elseif ($username === '' || $password === '') {
        $err = '请输入账号和密码';
    } else {
        $lock = yk_lock_read($username);
        if (!empty($lock['lock_until']) && $lock['lock_until'] > time()) {
            $err = '连续输错次数过多，账号已锁定，请 ' . ceil(($lock['lock_until'] - time()) / 60) . ' 分钟后再试';
        } else {
            $admin = db_one('SELECT * FROM ' . DB_PREFIX . 'admin WHERE username = ?', array($username));
            if ($admin && $admin['password'] === md5($password . PWD_SALT)) {
                // 登录成功：清除锁定、写日志、跳转
                @unlink(yk_lock_file($username));
                session_regenerate_id(true);
                $_SESSION['yk_admin_id']   = (int)$admin['id'];
                $_SESSION['yk_admin_name'] = $admin['username'];
                db_insert('INSERT INTO ' . DB_PREFIX . 'log (admin, action, detail, ip, add_time) VALUES (?, ?, ?, ?, ?)', array(
                    $admin['username'], '登录', '登录后台成功',
                    isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', time(),
                ));
                header('Location: index.php');
                exit;
            }
            // 失败计数
            $lock['fails'] = (int)$lock['fails'] + 1;
            if ($lock['fails'] >= $maxFails) {
                $lock['lock_until'] = time() + $lockSecs;
                $lock['fails'] = 0;
                yk_lock_write($username, $lock);
                $err = '连续输错 ' . $maxFails . ' 次，账号已锁定 10 分钟';
            } else {
                yk_lock_write($username, $lock);
                $err = '账号或密码错误（还可尝试 ' . ($maxFails - $lock['fails']) . ' 次）';
            }
        }
    }
}

$hasGd = function_exists('imagecreatetruecolor');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>后台登录 - 炎酷CMS</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:"Microsoft YaHei","PingFang SC",sans-serif;background:#232a35;display:flex;align-items:center;justify-content:center;min-height:100vh}
.login-box{background:#fff;border-radius:8px;padding:36px 34px;width:360px;box-shadow:0 8px 30px rgba(0,0,0,.3)}
.login-box h1{font-size:20px;text-align:center;margin-bottom:6px}
.login-box h1 span{color:#ff7d2a}
.login-box .sub{text-align:center;color:#999;font-size:12px;margin-bottom:24px}
.login-box .row{margin-bottom:16px}
.login-box input{width:100%;padding:10px 12px;border:1px solid #d5dae3;border-radius:4px;font-size:14px}
.login-box input:focus{border-color:#1e6fff;outline:none}
.cap-row{display:flex;gap:10px;align-items:center}
.cap-row input{flex:1}
.cap-row img,.cap-row .cap-txt{height:40px;border:1px solid #d5dae3;border-radius:4px;cursor:pointer;background:#f5f7fa;display:flex;align-items:center;padding:0 10px;font-size:15px;color:#1e6fff;white-space:nowrap}
.err{background:#fdecea;color:#d93025;border:1px solid #f5c6c2;padding:9px 12px;border-radius:4px;margin-bottom:16px;font-size:13px}
.btn{width:100%;padding:11px;background:#1e6fff;color:#fff;border:none;border-radius:4px;font-size:15px;cursor:pointer}
.btn:hover{background:#0f5ae0}
.tip{text-align:center;color:#bbb;font-size:12px;margin-top:16px}
</style>
</head>
<body>
<div class="login-box">
  <h1>炎酷<span>CMS</span></h1>
  <div class="sub">管理后台登录</div>
  <?php if ($err !== ''): ?><div class="err"><?php echo e($err); ?></div><?php endif; ?>
  <form method="post" action="login.php">
    <div class="row"><input type="text" name="username" placeholder="管理员账号" autocomplete="off"></div>
    <div class="row"><input type="password" name="password" placeholder="登录密码"></div>
    <div class="row cap-row">
      <input type="text" name="captcha" placeholder="验证码" autocomplete="off">
      <?php if ($hasGd): ?>
      <img src="captcha.php" id="capImg" onclick="this.src='captcha.php?r='+Math.random()" title="点击刷新" alt="验证码">
      <?php else: ?>
      <span class="cap-txt" id="capTxt" onclick="ykRefCap()" title="点击刷新">加载中…</span>
      <?php endif; ?>
    </div>
    <button class="btn" type="submit">登 录</button>
  </form>
  <div class="tip">连续输错 5 次将锁定 10 分钟</div>
</div>
<?php if (!$hasGd): ?>
<script>
function ykRefCap(){
  var x=new XMLHttpRequest();
  x.open('GET','captcha.php?r='+Math.random(),true);
  x.onreadystatechange=function(){if(x.readyState===4&&x.status===200){document.getElementById('capTxt').textContent=x.responseText;}};
  x.send(null);
}
ykRefCap();
</script>
<?php endif; ?>
</body>
</html>
