<?php
require_once __DIR__ . '/../MPHX/common.php';

// 处理管理员直接登录
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_login']) && $_POST['admin_login'] === '1') {
    // 验证管理员是否已登录 - 优先使用session验证
    $admin_user = false;
    
    // 调试信息
    $debug = [];
    $debug[] = "SESSION ID: " . session_id();
    $debug[] = "SESSION 内容: " . print_r($_SESSION, true);
    $debug[] = "COOKIE 内容: " . print_r($_COOKIE, true);
    
    // 方法1: 检查session中的管理员信息
    if (isset($_SESSION['admin_user']) && !empty($_SESSION['admin_user'])) {
        $admin_user = $_SESSION['admin_user'];
        $debug[] = "通过SESSION验证，管理员: " . $admin_user;
    }
    // 方法2: 检查cookie中的admin_token
    elseif (isset($_COOKIE['admin_token'])) {
        $admin_user = is_admin_login();
        $debug[] = "通过COOKIE验证，管理员: " . var_export($admin_user, true);
    } else {
        $debug[] = "未找到SESSION或COOKIE中的管理员信息";
    }
    
    if (!$admin_user) {
        exit('<pre>管理员未登录，无法执行此操作。请先登录后台管理系统。

调试信息:
' . implode("\n", $debug) . '</pre>');
    }
    
    $user = $DB->escape($_POST['user']);
    $pass = $DB->escape($_POST['pass']);
    
    // 验证用户信息
    $row = $DB->get_row("SELECT * FROM `zj` WHERE `user`='{$user}' AND `pass`='{$pass}' LIMIT 1");
    if ($row) {
        global $password_hash;
        // 使用与正常登录相同的token格式
        $session = md5($row['user'] . $row['pass'] . $password_hash);
        $token = authcode("{$row['user']}\t{$session}", 'ENCODE', SYS_KEY);
        setcookie('user_token', $token, time() + 86400 * 30, '/');
        $_SESSION['user_token'] = $token;
        $_SESSION['user_id'] = $row['id'];
        $_SESSION['user_name'] = $row['user'];
        
        // 记录登录日志
        logjl($row['id'], '用户登录', '管理员代登录: ' . $admin_user, true);
        
        header('Location: /user/index.php');
        exit;
    } else {
        exit('用户信息验证失败');
    }
}

if (isset($_GET['logout']) && $_GET['logout'] == '1') {
    setcookie('user_token', 'deleted', time() - 3600, '/');
    setcookie('user_token', 'deleted', time() - 3600, '/user');
    setcookie('user_token', 'deleted', time() - 3600, '/user/');
    if (isset($_SESSION['user_token'])) {
        unset($_SESSION['user_token']);
    }
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_destroy();
    }
} else {
    if (is_user_login()) {
        header('Location: /user/index.php');
        exit;
    }
}
?>
<!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 L('user', 'menu'); ?><?php echo L('login', 'menu'); ?> - <?php echo L('title', 'dashboard'); ?></title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=20260220_4">
    <style>
        /* 登录页面专用样式 */
        .login-container {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: calc(100vh - 60px);
            padding: 20px;
        }
        
        .login-box {
            width: 100%;
            max-width: 420px;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            padding: 40px;
        }
        
        .login-header {
            text-align: center;
            margin-bottom: 32px;
        }
        
        .login-header i {
            font-size: 48px;
            color: #188038;
            margin-bottom: 16px;
            background: #e6f4ea;
            width: 80px;
            height: 80px;
            line-height: 80px;
            border-radius: 50%;
            display: inline-block;
        }
        
        .login-header h2 {
            font-size: 22px;
            font-weight: 600;
            color: #202124;
            margin: 0 0 8px 0;
        }
        
        .login-header p {
            color: #5f6368;
            font-size: 14px;
            margin: 0;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: #5f6368;
            margin-bottom: 6px;
        }
        
        .form-control {
            width: 100%;
            height: 44px;
            padding: 0 14px;
            border: 1px solid #dadce0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.2s;
            background-color: #fff;
            box-sizing: border-box;
        }
        
        .form-control:focus {
            border-color: #188038;
            box-shadow: 0 0 0 2px rgba(24, 128, 56, 0.1);
            outline: none;
        }
        
        /* 验证码区域 */
        .captcha-box {
            display: flex;
            gap: 10px;
        }
        
        .captcha-box input {
            flex: 1;
        }
        
        .captcha-box img {
            height: 44px;
            border-radius: 8px;
            cursor: pointer;
            border: 1px solid #dadce0;
            transition: opacity 0.2s;
        }
        
        .captcha-box img:hover {
            opacity: 0.8;
        }
        
        .btn-login {
            width: 100%;
            height: 44px;
            background: #188038;
            border: none;
            border-radius: 8px;
            color: #fff;
            font-size: 15px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .btn-login:hover {
            background: #137333;
        }
        
        .btn-login:disabled {
            background: #dadce0;
            cursor: not-allowed;
        }
        
        .login-footer {
            text-align: center;
            margin-top: 24px;
            padding-top: 20px;
            border-top: 1px solid #e8eaed;
        }
        
        .login-footer a {
            color: #5f6368;
            font-size: 13px;
            text-decoration: none;
            transition: color 0.2s;
        }
        
        .login-footer a:hover {
            color: #188038;
        }
        
        /* 头部样式 */
        .header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: 60px;
            background: #fff;
            border-bottom: 1px solid #e8eaed;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 24px;
            z-index: 1000;
        }
        
        .header-brand {
            display: flex;
            align-items: center;
            gap: 12px;
            color: #202124;
            font-size: 16px;
            font-weight: 600;
        }
        
        .header-brand i {
            color: #188038;
            font-size: 20px;
        }
        
        .main-content {
            margin-left: 0;
            padding-top: 60px;
            min-height: 100vh;
            background: #f5f7fa;
        }

        /* 扫码登录样式 */
        .qr-login-box {
            text-align: center;
            padding: 20px 0;
        }

        .qr-code-container {
            position: relative;
            width: 200px;
            height: 200px;
            margin: 0 auto 16px;
            background: #fff;
            border: 1px solid #e8eaed;
            border-radius: 8px;
            padding: 10px;
        }

        #qrcode {
            width: 180px;
            height: 180px;
        }

        #qrcode img, #qrcode canvas {
            width: 180px !important;
            height: 180px !important;
        }

        .qr-code-mask {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.95);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
        }

        .qr-code-mask p {
            color: #5f6368;
            margin-bottom: 12px;
            font-size: 14px;
        }

        .btn-refresh-qr {
            padding: 8px 20px;
            background: #188038;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-refresh-qr:hover {
            background: #137333;
        }

        .qr-tip {
            color: #5f6368;
            font-size: 13px;
            margin-bottom: 20px;
        }

        .qr-code-input-box {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e8eaed;
        }

        .qr-code-input-box label {
            display: block;
            font-size: 13px;
            color: #5f6368;
            margin-bottom: 10px;
        }

        .qr-code-input {
            text-align: center;
            font-size: 24px !important;
            font-weight: 600;
            letter-spacing: 8px !important;
            margin-bottom: 16px !important;
        }

        .login-switch {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e8eaed;
        }

        .login-switch a {
            color: #188038;
            font-size: 14px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .login-switch a:hover {
            text-decoration: underline;
        }

        /* Toast 提示样式 */
        .login-toast {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: #fff;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 14px;
            z-index: 9999;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translate(-50%, -40%); }
            to { opacity: 1; transform: translate(-50%, -50%); }
        }
    </style>
    <!-- QRCode.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
</head>
<body>
    <!-- 头部 -->
    <div class="header">
        <div class="header-brand">
            <i class="fas fa-laptop"></i>
            <span><?php echo $conf['name']; ?></span>
        </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
        <div class="login-container">
            <div class="login-box">
                <div class="login-header">
                    <i class="fas fa-user-circle"></i>
                    <h2><?php echo L('user', 'menu'); ?><?php echo L('login', 'menu'); ?></h2>
                    <p><?php echo L('title', 'dashboard'); ?></p>
                </div>
                <!-- 扫码登录区域 -->
                <div id="qrLoginSection" style="display: none;">
                    <div class="qr-login-box">
                        <div class="qr-code-container">
                            <div id="qrcode"></div>
                            <div class="qr-code-mask" id="qrCodeMask" style="display: none;">
                                <p>二维码已过期</p>
                                <button class="btn-refresh-qr" onclick="refreshQRCode()">刷新</button>
                            </div>
                        </div>
                        <p class="qr-tip">请使用APP扫描二维码</p>
                        <div class="qr-code-input-box">
                            <label>或输入APP显示的6位验证码</label>
                            <input type="text" class="form-control qr-code-input" id="qrCodeInput" maxlength="6" placeholder="请输入6位验证码">
                            <button type="button" class="btn-login" onclick="verifyQRCode()">
                                <i class="fas fa-check"></i> 确认登录
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 普通登录表单 -->
                <form id="loginForm">
                    <div class="form-group">
                        <label for="user"><?php echo L('username', 'profile'); ?></label>
                        <input type="text" class="form-control" id="user" name="user" required autofocus placeholder="<?php echo L('please_input', 'form') . L('username', 'profile'); ?>">
                    </div>
                    <div class="form-group">
                        <label for="pass"><?php echo L('password', 'profile'); ?></label>
                        <input type="password" class="form-control" id="pass" name="pass" required placeholder="<?php echo L('please_input', 'form') . L('password', 'profile'); ?>">
                    </div>
                    <?php if ($conf['yzme'] == 'true'): ?>
                    <div class="form-group">
                        <label for="code">验证码</label>
                        <div class="captcha-box">
                            <input type="text" class="form-control" id="code" name="code" required placeholder="请输入验证码">
                            <img src="code.php" data-action="refresh-captcha" title="点击刷新">
                        </div>
                    </div>
                    <?php endif; ?>
                    <button type="button" class="btn-login" data-action="login">
                        <i class="fas fa-sign-in-alt"></i> <?php echo L('login', 'menu'); ?>
                    </button>
                </form>

                <!-- 登录方式切换 -->
                <div class="login-switch">
                    <a href="javascript:void(0)" id="switchLoginType" data-type="qr">
                        <i class="fas fa-qrcode"></i> 扫码登录
                    </a>
                </div>

            </div>
        </div>
    </div>
    
    <script src="/static/js/jquery.min.js"></script>
    <script src="js/login.js"></script>
    <script>
        // 登录页事件代理
        $(document).on('click', '[data-action="refresh-captcha"]', function(e){
            e.preventDefault();
            $(this).attr('src', 'code.php?t=' + Math.random());
        });
        $(document).on('click', '[data-action="login"]', function(e){
            e.preventDefault();
            login(this);
        });

        // ==================== 扫码登录功能 ====================
        let currentQRToken = '';
        let qrCheckInterval = null;

        // 切换登录方式
        $('#switchLoginType').on('click', function() {
            const type = $(this).data('type');
            if (type === 'qr') {
                $('#loginForm').hide();
                $('#qrLoginSection').show();
                $(this).data('type', 'normal').html('<i class="fas fa-user"></i> 账号密码登录');
                generateQRCode();
            } else {
                $('#qrLoginSection').hide();
                $('#loginForm').show();
                $(this).data('type', 'qr').html('<i class="fas fa-qrcode"></i> 扫码登录');
                stopQRCheck();
            }
        });

        // 生成二维码
        function generateQRCode() {
            $.post('/api/app_api.php?action=generate_qr_login', function(res) {
                if (res.code === 200) {
                    currentQRToken = res.data.qr_token;
                    
                    // 清空之前的二维码
                    $('#qrcode').empty();
                    
                    // 生成二维码
                    new QRCode(document.getElementById('qrcode'), {
                        text: JSON.stringify({
                            type: 'login',
                            token: currentQRToken,
                            url: window.location.origin
                        }),
                        width: 180,
                        height: 180,
                        colorDark: '#000000',
                        colorLight: '#ffffff',
                        correctLevel: QRCode.CorrectLevel.M
                    });
                    
                    $('#qrCodeMask').hide();
                    
                    // 开始轮询检查状态
                    startQRCheck();
                } else {
                    alert('生成二维码失败：' + res.msg);
                }
            });
        }

        // 刷新二维码
        function refreshQRCode() {
            generateQRCode();
        }

        // 开始轮询检查登录状态
        function startQRCheck() {
            stopQRCheck();
            qrCheckInterval = setInterval(function() {
                if (!currentQRToken) return;
                
                $.get('/api/app_api.php?action=check_qr_login_status&qr_token=' + currentQRToken, function(res) {
                    if (res.code === 200) {
                        if (res.data.status === 'verified') {
                            // APP已确认，自动完成登录
                            completeLogin();
                        }
                    } else if (res.code === -1) {
                        // 二维码过期
                        $('#qrCodeMask').show();
                        stopQRCheck();
                    }
                });
            }, 2000);
            
            // 5分钟后自动停止
            setTimeout(stopQRCheck, 300000);
        }

        // 停止轮询
        function stopQRCheck() {
            if (qrCheckInterval) {
                clearInterval(qrCheckInterval);
                qrCheckInterval = null;
            }
        }

        // 验证验证码
        function verifyQRCode() {
            const code = $('#qrCodeInput').val().trim();
            if (!code || code.length !== 6) {
                alert('请输入6位验证码');
                return;
            }
            
            if (!currentQRToken) {
                alert('二维码已失效，请刷新');
                return;
            }
            
            $.post('/api/app_api.php?action=complete_qr_login', {
                qr_token: currentQRToken,
                code: code
            }, function(res) {
                if (res.code === 200) {
                    window.location.href = res.data.redirect || '/user/index.php';
                } else {
                    alert(res.msg || '登录失败');
                }
            });
        }

        // 自动完成登录（APP已确认时）
        function completeLogin() {
            // APP已确认，直接聚焦到验证码输入框，让用户输入
            $('#qrCodeInput').focus();
            showToast('APP已确认，请输入验证码完成登录');
        }

        // 显示提示信息
        function showToast(message) {
            // 创建提示元素
            const toast = $('<div class="login-toast">' + message + '</div>');
            $('body').append(toast);

            // 自动移除
            setTimeout(function() {
                toast.fadeOut(function() {
                    $(this).remove();
                });
            }, 3000);
        }

        // 验证码输入框自动提交
        $('#qrCodeInput').on('keyup', function(e) {
            if (e.key === 'Enter' && $(this).val().length === 6) {
                verifyQRCode();
            }
        });
    </script>
</body>
</html>
