<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */


session_start();
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    unset($_SESSION['admin_id']);
    unset($_SESSION['admin_name']);
    unset($_SESSION['admin_realname']);
    unset($_SESSION['admin_role']);
    session_destroy();
    header('Location: /admin/login.php');
    exit;
}
require_once dirname(__DIR__) . '/core/db/db.php';

if (isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id'])) {
    header('Location: /admin/index.php');
    exit;
}

$error = '';

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

    if (empty($captcha) || !isset($_SESSION['captcha']) || strtolower($captcha) !== strtolower($_SESSION['captcha'])) {
        $error = '验证码错误';
    } elseif (empty($username) || empty($password)) {
        $error = '请输入用户名和密码';
    } else {
        try {
            $db = \Core\Db\DB::getInstance();
            $admin = $db->fetch("SELECT * FROM {$db->table('admin')} WHERE username = ? AND is_enabled = 1 LIMIT 1", [$username]);

            if ($admin) {
                if (password_verify($password, $admin['password']) || md5($password) === $admin['password']) {
                    $_SESSION['admin_id'] = $admin['id'];
                    $_SESSION['admin_name'] = $admin['username'];
                    $_SESSION['admin_realname'] = $admin['realname'];
                    $_SESSION['admin_role'] = $admin['role_id'];
                    $_SESSION['last_activity'] = time();
                    $db->update('admin', ['last_login_time' => time(), 'last_login_ip' => $_SERVER['REMOTE_ADDR'] ?? ''], 'id = ?', [$admin['id']]);
                    header('Location: /admin/index.php');
                    exit;
                } else {
                    $error = '密码错误';
                }
            } else {
                $error = '用户名不存在或已被禁用';
            }
        } catch (Exception $e) {
            $error = '系统错误，请稍后再试';
        }
    }
}

// 生成验证码
$captchaCode = substr(md5(uniqid()), 0, 4);
$_SESSION['captcha'] = $captchaCode;

$imgWidth = 140;
$imgHeight = 50;
$img = imagecreatetruecolor($imgWidth, $imgHeight);
$bgColor = imagecolorallocate($img, 245, 247, 250);
imagefill($img, 0, 0, $bgColor);
for ($i = 0; $i < 3; $i++) {
    $lineColor = imagecolorallocate($img, rand(200, 220), rand(200, 220), rand(200, 220));
    imageline($img, rand(0, $imgWidth), rand(0, $imgHeight), rand(0, $imgWidth), rand(0, $imgHeight), $lineColor);
}
$textColor = imagecolorallocate($img, 102, 126, 234);
$fontSize = 5;
$x = 15;
$y = 15;
for ($i = 0; $i < strlen($captchaCode); $i++) {
    imagestring($img, $fontSize, $x + $i * 28, $y, $captchaCode[$i], $textColor);
}
for ($i = 0; $i < 50; $i++) {
    $dotColor = imagecolorallocate($img, rand(180, 200), rand(180, 200), rand(180, 200));
    imagesetpixel($img, rand(0, $imgWidth), rand(0, $imgHeight), $dotColor);
}
ob_start();
imagepng($img);
$captchaBase64 = base64_encode(ob_get_clean());
imagedestroy($img);

$siteName = '企业CMS';
try {
    $db = \Core\Db\DB::getInstance();
    $nameConfig = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'site_name'");
    if ($nameConfig) $siteName = $nameConfig['config_value'];
} catch (Exception $e) {}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理登录 - <?php echo htmlspecialchars($siteName); ?></title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; }
        .login-container { width: 100%; max-width: 420px; padding: 20px; }
        .login-box { background: #fff; border-radius: 16px; box-shadow: 0 20px 60px rgba(0,0,0,0.15); overflow: hidden; }
        .login-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 30px; text-align: center; color: #fff; }
        .login-logo { font-size: 48px; margin-bottom: 12px; }
        .login-header h1 { font-size: 22px; font-weight: 600; margin-bottom: 8px; }
        .login-header p { font-size: 13px; opacity: 0.85; }
        .login-body { padding: 30px; }
        .error-message { background: #fef2f2; border: 1px solid #fecaca; color: #dc2626; padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; display: flex; align-items: center; gap: 8px; font-size: 14px; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; font-size: 14px; font-weight: 500; color: #374151; margin-bottom: 8px; }
        .form-group input { width: 100%; padding: 12px 16px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 14px; outline: none; transition: border-color 0.2s; }
        .form-group input:focus { border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        .captcha-group { display: flex; gap: 12px; }
        .captcha-group input { flex: 1; }
        .captcha-img { width: 120px; height: 46px; border-radius: 8px; cursor: pointer; border: 1px solid #e5e7eb; object-fit: fill; }
        .btn-login { width: 100%; padding: 14px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; transition: transform 0.2s, box-shadow 0.2s; }
        .btn-login:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4); }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-box">
            <div class="login-header">
                <div class="login-logo">🏢</div>
                <h1><?php echo htmlspecialchars($siteName); ?></h1>
                <p>企业内容管理系统</p>
            </div>
            <div class="login-body">
                <?php if ($error): ?>
                <div class="error-message"><span>⚠️</span><span><?php echo htmlspecialchars($error); ?></span></div>
                <?php endif; ?>
                <form method="post">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" name="username" placeholder="请输入用户名" required autocomplete="username">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" name="password" placeholder="请输入密码" required autocomplete="current-password">
                    </div>
                    <div class="form-group">
                        <label>验证码</label>
                        <div class="captcha-group">
                            <input type="text" name="captcha" placeholder="请输入验证码" required>
                            <img src="data:image/png;base64,<?php echo $captchaBase64; ?>" alt="验证码" class="captcha-img" id="captchaImg" title="点击刷新">
                        </div>
                    </div>
                    <button type="submit" class="btn-login">登 录</button>
                </form>
            </div>
        </div>
    </div>
    <script>
    document.getElementById('captchaImg').addEventListener('click', function() {
        this.src = '/admin/captcha.php?t=' + Math.random();
    });
    </script>
</body>
</html>