<?php
declare(strict_types=1);
include("./includes/common.php");

if(!$conf['userlogin']){
    @header('Content-Type: text/html; charset=UTF-8');
	exit('<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://s4.zstatic.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script></head><body><script>layer.alert("未开启用户登录", {icon: 2, closeBtn: 0}, function(){ window.location.href="./"; });</script></body></html>');
}

// 处理退出登录
if(isset($_GET['logout'])){
	if(!checkRefererHost())exit();
	setcookie("user_token", "", [
		'expires' => time() - 1,
		'path' => '/',
		'secure' => is_https(),
		'httponly' => true,
		'samesite' => 'Lax',
	]);
	@header('Content-Type: text/html; charset=UTF-8');
	exit('<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://s4.zstatic.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script></head><body><script>layer.alert("您已成功注销本次登录！", {icon: 1, closeBtn: 0}, function(){ window.location.href="./login.php"; });</script></body></html>');
}

// 处理第三方登录连接请求
elseif(isset($_GET['act']) && $_GET['act']=='connect'){
    if(ob_get_length()) ob_clean();
    header('Content-Type: application/json; charset=UTF-8');
    
    // 允许 AJAX 请求（可能没有 Referer）
    $type = isset($_POST['type']) ? $_POST['type'] : (isset($_GET['type']) ? $_GET['type'] : null);
    if(!$type)exit(json_encode(['code'=>-1,'msg'=>'no type']));
    $bind_mode = isset($_POST['bind_mode']) ? $_POST['bind_mode'] : (isset($_GET['bind_mode']) ? $_GET['bind_mode'] : null);
    $flow = isset($_POST['flow']) ? $_POST['flow'] : (isset($_GET['flow']) ? $_GET['flow'] : null);
    
    if(!in_array($type, ['qq','wx'], true))exit(json_encode(['code'=>-1,'msg'=>'no valid type']));
    if($flow !== null && !in_array($flow, ['quick_register'], true))exit(json_encode(['code'=>-1,'msg'=>'no valid flow']));
    
    if(!$conf['login_apiurl'] || !$conf['login_appid'] || !$conf['login_appkey']) {
        exit(json_encode(['code'=>-1,'msg'=>'未配置好快捷登录接口信息']));
    }
    
    $Oauth = new \lib\Oauth($conf['login_apiurl'], $conf['login_appid'], $conf['login_appkey']);
    $state = md5(uniqid('', true) . time() . mt_rand());
    $callback = $siteurl.'login.php?type='.$type;
    $ctx = [
        'state' => $state,
        'type' => $type,
        'bind_mode' => $bind_mode,
        'flow' => $flow,
        'return' => ($bind_mode === 'bind' ? 'user_center.php' : './'),
        'ts' => time(),
    ];
    $ctxToken = authcode(json_encode($ctx, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'ENCODE', SYS_KEY, 600);
    setcookie('clogin_ctx', $ctxToken, time() + 600, '/');
    $_SESSION['bind_mode'] = $bind_mode;
    $_SESSION['Oauth_type'] = $type;
    $_SESSION['Oauth_state'] = $state;
    if($flow === 'quick_register'){
        $_SESSION['Oauth_flow'] = 'quick_register';
    }else{
        unset($_SESSION['Oauth_flow']);
    }
    
    $res = $Oauth->login($type, $callback, $state);
    
    if(isset($res['code']) && $res['code']==0){
        $result = ['code'=>0, 'url'=>$res['url']];
    }elseif(isset($res['code'])){
        $result = ['code'=>-1, 'msg'=>$res['msg']];
    }elseif($res === null || $res === ''){
        $result = ['code'=>-1,'msg'=>'快捷登录接口无响应，请检查接口地址是否正确: '.$conf['login_apiurl']];
    }else{
        $result = ['code'=>-1, 'msg'=>'快捷登录接口返回未知格式: '.substr($res, 0, 100)];
    }
    exit(json_encode($result));
}

// 处理账号密码登录
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'login'){
    if(ob_get_length()) ob_clean();
    header('Content-Type: application/json; charset=UTF-8');
    
    if(!checkRefererHost())exit(json_encode(['code'=>-1, 'msg'=>'请求来源非法']));
    
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $remember = isset($_POST['remember'])?1:0;
    $csrf_token = $_POST['csrf_token'];
    
    if(!$csrf_token || $csrf_token != $_SESSION['csrf_token']){
        exit(json_encode(['code'=>-1, 'msg'=>'请求验证失败，请刷新页面重试']));
    }
    
    if(empty($username) || empty($password)){
        exit(json_encode(['code'=>-1, 'msg'=>'请输入用户名和密码']));
    }
    
    // 查找用户
    $userrow = $DB->getRow("SELECT * FROM pre_user WHERE username=:username LIMIT 1", [':username'=>$username]);
    
    if(!$userrow){
        exit(json_encode(['code'=>-1, 'msg'=>'用户名或密码错误']));
    }
    
    if($userrow['enable']==0){
        exit(json_encode(['code'=>-1, 'msg'=>'该账户已被封禁']));
    }
    
    if(!password_verify($password, $userrow['password'])){
        exit(json_encode(['code'=>-1, 'msg'=>'用户名或密码错误']));
    }
    
    // 更新登录信息
    $DB->exec("UPDATE pre_user SET loginip=:loginip, login_count=login_count+1, lasttime=NOW() WHERE uid=:uid", [
        ':loginip' => $clientip,
        ':uid' => $userrow['uid']
    ]);
    
    // 处理游客文件关联
    $guestIds = get_guest_file_ids();
    $sessionIds = (isset($_SESSION['fileids']) && count($_SESSION['fileids'])>0) ? $_SESSION['fileids'] : [];
    $mergeIds = array_values(array_unique(array_merge($guestIds, $sessionIds)));
    $guest_token = get_guest_token();

    if(count($mergeIds) > 0){
        $ids = array_reverse($mergeIds);
        $ids = array_values(array_filter(array_map('intval', $ids), function ($id) { return $id > 0; }));
        if(count($ids) > 200){
            $ids = array_splice($ids, 0, 200);
        }

        $params = [':uid' => (int) $userrow['uid']];
        $placeholders = [];
        foreach ($ids as $i => $fileId) {
            $key = ':id' . $i;
            $placeholders[] = $key;
            $params[$key] = $fileId;
        }

        if ($placeholders !== []) {
            $DB->exec(
                "UPDATE pre_file SET uid=:uid WHERE id IN (" . implode(',', $placeholders) . ") AND uid=0",
                $params
            );
        }
    }

    if ($guest_token) {
        $DB->exec("UPDATE pre_file SET uid=:uid WHERE guest_token=:token AND uid=0", [
            ':uid' => (int) $userrow['uid'],
            ':token' => $guest_token,
        ]);
    }

    set_guest_file_ids([]);
    
    // 生成登录token
    $session=md5($userrow['username'].$userrow['password'].$password_hash);
    $expiretime = $remember ? time()+2592000 : time()+86400; // 记住我则30天，否则1天
    $token=authcode("{$userrow['uid']}\t{$session}\t{$expiretime}", 'ENCODE', SYS_KEY);
    setcookie("user_token", $token, [
        'expires' => $expiretime,
        'path' => '/',
        'secure' => is_https(),
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    
    unset($_SESSION['csrf_token']);
    exit(json_encode(['code'=>0, 'msg'=>'登录成功！', 'uid'=>$userrow['uid']]));
}

// 处理第三方登录回调
elseif(isset($_GET['code'], $_GET['state'])){
    $ctx = null;
    if(isset($_COOKIE['clogin_ctx'])){
        $ctxRaw = authcode(daddslashes($_COOKIE['clogin_ctx']), 'DECODE', SYS_KEY);
        if($ctxRaw){
            $decoded = json_decode($ctxRaw, true);
            if(is_array($decoded)){
                $ctx = $decoded;
            }
        }
    }

    $stateExpected = null;
    if(is_array($ctx) && isset($ctx['state']) && is_string($ctx['state'])){
        $stateExpected = $ctx['state'];
    }elseif(isset($_SESSION['Oauth_state'])){
        $stateExpected = $_SESSION['Oauth_state'];
    }
    if($stateExpected === null || $_GET['state'] !== $stateExpected){
        sysmsg("<h2>The state does not match. You may be a victim of CSRF.</h2>");
    }

    if(isset($_GET['type']) && in_array($_GET['type'], ['qq', 'wx'], true)){
        $type = $_GET['type'];
    }elseif(is_array($ctx) && isset($ctx['type']) && in_array($ctx['type'], ['qq', 'wx'], true)){
        $type = $ctx['type'];
    }elseif(isset($_SESSION['Oauth_type']) && in_array($_SESSION['Oauth_type'], ['qq', 'wx'], true)){
        $type = $_SESSION['Oauth_type'];
    }else{
        $type = 'qq';
    }
	$typename = $type=='wx'?'微信':'QQ';
	$bind_mode = is_array($ctx) && isset($ctx['bind_mode']) ? $ctx['bind_mode'] : (isset($_SESSION['bind_mode'])?$_SESSION['bind_mode']:null);
	$oauth_flow = is_array($ctx) && isset($ctx['flow']) ? $ctx['flow'] : (isset($_SESSION['Oauth_flow'])?$_SESSION['Oauth_flow']:null);
    $return_url = is_array($ctx) && isset($ctx['return']) && is_string($ctx['return']) ? $ctx['return'] : './';
    if(!in_array($return_url, ['./', 'user_center.php'], true)){
        $return_url = './';
    }
	
	$Oauth = new \lib\Oauth($conf['login_apiurl'], $conf['login_appid'], $conf['login_appkey']);
	$arr = $Oauth->callback();
	
	if(isset($arr['code']) && $arr['code']==0){
		$openid = $arr['social_uid'];
        if(empty($openid) || !is_string($openid)){
            sysmsg('获取'.$typename.'账号标识失败');
        }
		$nickname = trim($arr['nickname']);
		if(empty($nickname) || $nickname=='-') $nickname = $typename.'用户';
		$faceimg = $arr['faceimg'];
	}elseif(isset($arr['code'])){
		sysmsg('<h3>error:</h3>'.$arr['errcode'].'<h3>msg  :</h3>'.$arr['msg']);
	}else{
		sysmsg('获取登录数据失败');
	}

	// 绑定模式处理
	if($bind_mode === 'bind' && $islogin2){
		// 绑定第三方账号到当前用户
		$field = $type.'_openid';
		if($DB->getColumn("SELECT COUNT(*) FROM pre_user WHERE {$field}=:openid", [':openid'=>$openid]) > 0){
			sysmsg('该'.$typename.'账号已被其他用户绑定');
		}
		
		$DB->exec("UPDATE pre_user SET {$field}=:openid, faceimg=:faceimg WHERE uid=:uid", [
			':openid' => $openid,
			':faceimg' => $faceimg,
			':uid' => $uid
		]);
		
		setcookie('clogin_ctx', '', time() - 1, '/');
		unset($_SESSION['bind_mode'], $_SESSION['Oauth_flow'], $_SESSION['Oauth_type'], $_SESSION['Oauth_state']);
		exit('<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://s4.zstatic.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script></head><body><script>layer.alert("'.$typename.'账号绑定成功！", {icon: 1, closeBtn: 0}, function(){ window.location.href="user_center.php"; });</script></body></html>');
	}

    if($bind_mode === 'bind' && !$islogin2){
        setcookie('clogin_ctx', '', time() - 1, '/');
        unset($_SESSION['bind_mode'], $_SESSION['Oauth_flow'], $_SESSION['Oauth_type'], $_SESSION['Oauth_state']);
        sysmsg('登录状态已失效，请先登录后再发起绑定。');
    }
	
	// 快速注册模式处理
	if($oauth_flow === 'quick_register'){
		setcookie('clogin_ctx', '', time() - 1, '/');
		unset($_SESSION['bind_mode'], $_SESSION['Oauth_flow'], $_SESSION['Oauth_type'], $_SESSION['Oauth_state']);
		// 生成随机用户名和密码
		$username = $type . '_' . substr($openid, -8);
		$password = substr(md5($openid.time()), 0, 8);
		
		// 检查用户名是否存在
		$counter = 1;
		$base_username = $username;
		while($DB->getColumn("SELECT COUNT(*) FROM pre_user WHERE username=:username", [':username'=>$username]) > 0){
			$username = $base_username . $counter;
			$counter++;
		}
		
		// 创建用户
		$password_hash = password_hash($password, PASSWORD_DEFAULT);
		$field = $type.'_openid';
		$result = $DB->exec("INSERT INTO pre_user (username, password, nickname, {$field}, faceimg, enable, regip, loginip, addtime, lasttime) 
		                     VALUES (:username, :password, :nickname, :openid, :faceimg, 1, :regip, :regip, NOW(), NOW())", [
		                     ':username' => $username,
		                     ':password' => $password_hash,
		                     ':nickname' => $nickname,
		                     ':openid' => $openid,
		                     ':faceimg' => $faceimg,
		                     ':regip' => $clientip
		                     ]);
		
		if(!$result){
			sysmsg('快速注册失败：'.$DB->error());
		}
		
		$uid = $DB->lastInsertId();
		
		// 显示生成的账号信息
		@header('Content-Type: text/html; charset=UTF-8');
		echo '<!DOCTYPE html>
<html>
<head><title>注册成功 - '.$conf['title'].'</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://s4.zstatic.net/ajax/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://s4.zstatic.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="margin-top:100px;">
<div class="col-sm-6 col-md-4 center-block" style="float: none;">
<div class="panel panel-success">
<div class="panel-heading"><h3>注册成功</h3></div>
<div class="panel-body">
<h4><i class="fa fa-check-circle text-success"></i> 恭喜您注册成功！</h4>
<p><strong>您的登录账号：</strong>'.$username.'</p>
<p><strong>您的登录密码：</strong><span class="text-danger">'.$password.'</span></p>
<div class="alert alert-warning">
<i class="fa fa-exclamation-triangle"></i> 请妥善保存您的账号密码，系统不会再次显示！
</div>
<p><a href="login.php" class="btn btn-primary">立即登录</a></p>
</div>
</div>
</div>
</div>
</body>
</html>';
		exit;
	}
	
	// 如果未绑定，自动注册（普通第三方登录）
	$field = $type.'_openid';
	$userrow = $DB->getRow("SELECT * FROM pre_user WHERE {$field}=:openid LIMIT 1", [':openid'=>$openid]);
	
	if(!$userrow){
		setcookie('clogin_ctx', '', time() - 1, '/');
		unset($_SESSION['bind_mode'], $_SESSION['Oauth_flow'], $_SESSION['Oauth_type'], $_SESSION['Oauth_state']);
		
		// 生成随机用户名和密码
		$username = $type . '_' . substr($openid, -8);
		$password = substr(md5($openid.time()), 0, 8);
		
		// 检查用户名是否存在
		$counter = 1;
		$base_username = $username;
		while($DB->getColumn("SELECT COUNT(*) FROM pre_user WHERE username=:username", [':username'=>$username]) > 0){
			$username = $base_username . $counter;
			$counter++;
		}
		
		// 创建用户
		$pwd_hash = password_hash($password, PASSWORD_DEFAULT);
		$result = $DB->exec("INSERT INTO pre_user (username, password, nickname, {$field}, faceimg, enable, regip, loginip, addtime, lasttime) 
		                     VALUES (:username, :password, :nickname, :openid, :faceimg, 1, :regip, :regip, NOW(), NOW())", [
		                     ':username' => $username,
		                     ':password' => $pwd_hash,
		                     ':nickname' => $nickname,
		                     ':openid' => $openid,
		                     ':faceimg' => $faceimg,
		                     ':regip' => $clientip
		                     ]);
		
		if(!$result){
			sysmsg('自动注册失败：'.$DB->error());
		}
		
		$uid = $DB->lastInsertId();
		$userrow = [
			'uid' => $uid,
			'username' => $username,
			'password' => $pwd_hash,
			'enable' => 1
		];
	}
	
	if($userrow['enable']==0){
		sysmsg('当前用户已被禁止登录');
	}
	
	// 更新登录信息
	$DB->exec("UPDATE pre_user SET loginip=:loginip, login_count=login_count+1, lasttime=NOW() WHERE uid=:uid", [
		':loginip' => $clientip,
		':uid' => $userrow['uid']
	]);
	
	// 处理游客文件关联
    $guest_token = get_guest_token();
    
	if(isset($_SESSION['fileids']) && count($_SESSION['fileids'])>0){
		$ids = array_reverse($_SESSION['fileids']);
		$ids = array_values(array_filter(array_map('intval', $ids), function ($id) { return $id > 0; }));
		if(count($ids) > 200){
			$ids = array_splice($ids, 0, 200);
		}

		$params = [':uid' => (int) $userrow['uid']];
		$placeholders = [];
		foreach ($ids as $i => $fileId) {
			$key = ':id' . $i;
			$placeholders[] = $key;
			$params[$key] = $fileId;
		}

		if ($placeholders !== []) {
			$DB->exec(
				"UPDATE pre_file SET uid=:uid WHERE id IN (" . implode(',', $placeholders) . ") AND uid=0",
				$params
			);
		}
	}
    
    if ($guest_token) {
        $DB->exec("UPDATE pre_file SET uid=:uid WHERE guest_token=:token AND uid=0", [
			':uid' => (int) $userrow['uid'],
			':token' => $guest_token,
		]);
    }
    
    $guestIds = get_guest_file_ids();
    if(count($guestIds) > 0){
		$guestIds = array_values(array_filter(array_map('intval', $guestIds), function ($id) { return $id > 0; }));
		if (count($guestIds) > 200) {
			$guestIds = array_splice($guestIds, 0, 200);
		}

		$params = [':uid' => (int) $userrow['uid']];
		$placeholders = [];
		foreach ($guestIds as $i => $fileId) {
			$key = ':gid' . $i;
			$placeholders[] = $key;
			$params[$key] = $fileId;
		}

		if ($placeholders !== []) {
			$DB->exec(
				"UPDATE pre_file SET uid=:uid WHERE id IN (" . implode(',', $placeholders) . ") AND uid=0",
				$params
			);
		}
        set_guest_file_ids([]);
    }
	
	// 生成登录token
	$session=md5($userrow['username'].$userrow['password'].$password_hash);
	$expiretime=time()+2592000;
	$token=authcode("{$userrow['uid']}\t{$session}\t{$expiretime}", 'ENCODE', SYS_KEY);
	ob_clean();
	setcookie("user_token", $token, [
		'expires' => $expiretime,
		'path' => '/',
		'secure' => is_https(),
		'httponly' => true,
		'samesite' => 'Lax',
	]);
	setcookie('clogin_ctx', '', time() - 1, '/');
	unset($_SESSION['bind_mode'], $_SESSION['Oauth_flow'], $_SESSION['Oauth_type'], $_SESSION['Oauth_state']);
	exit("<script language='javascript'>window.location.href='".addslashes($return_url)."';</script>");
}

// 已登录用户跳转
elseif($islogin2==1){
	@header('Content-Type: text/html; charset=UTF-8');
	exit('<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://s4.zstatic.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script></head><body><script>layer.alert("您已登录！", {icon: 1, closeBtn: 0}, function(){ window.location.href="./"; });</script></body></html>');
}

// 登录页面显示
$title = '用户登录 - ' . $conf['title'];
include SYSTEM_ROOT.'header.php';

// 生成CSRF Token
$csrf_token = bin2hex(random_bytes(16));
$_SESSION['csrf_token'] = $csrf_token;

// 检查是否从快速注册链接过来
$quick_register_type = isset($_GET['quick_register'])?$_GET['quick_register']:null;
?>
<style>
.login-wrapper {
    min-height: calc(100vh - 200px);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
}
.login-card {
    background: #fff;
    border-radius: 20px;
    box-shadow: 0 20px 60px rgba(15, 118, 110, 0.15);
    overflow: hidden;
    width: 100%;
    max-width: 420px;
    animation: slideUp 0.5s ease-out;
}
@keyframes slideUp {
    from { opacity: 0; transform: translateY(30px); }
    to { opacity: 1; transform: translateY(0); }
}
.login-header {
    background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
    padding: 40px 30px;
    text-align: center;
}
.login-header .logo-icon {
    width: 70px;
    height: 70px;
    background: rgba(255,255,255,0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 15px;
    backdrop-filter: blur(10px);
}
.login-header .logo-icon i {
    font-size: 32px;
    color: #fff;
}
.login-header h2 {
    color: #fff;
    font-size: 24px;
    font-weight: 600;
    margin: 0;
}
.login-header p {
    color: rgba(255,255,255,0.85);
    margin: 8px 0 0;
    font-size: 14px;
}
.login-body {
    padding: 35px 30px;
}
.login-input-group {
    position: relative;
    margin-bottom: 20px;
}
.login-input-group .input-icon {
    position: absolute;
    left: 16px;
    top: 14px;
    color: #0f766e;
    font-size: 16px;
    z-index: 2;
    pointer-events: none;
}
.login-input-group input {
    width: 100%;
    padding: 14px 16px 14px 45px;
    border: 2px solid #e8e8e8;
    border-radius: 12px;
    font-size: 15px;
    transition: all 0.3s;
    background: #fafafa;
    box-sizing: border-box;
}
.login-input-group input:focus {
    border-color: #14b8a6;
    background: #fff;
    box-shadow: 0 0 0 4px rgba(20, 184, 166, 0.1);
    outline: none;
}
.login-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
}
.login-options label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    color: #666;
    font-size: 14px;
    margin: 0;
}
.login-options input[type="checkbox"] {
    width: 16px;
    height: 16px;
    accent-color: #14b8a6;
}
.btn-login {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
    border: none;
    border-radius: 12px;
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}
.btn-login:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(15, 118, 110, 0.35);
}
.btn-login:active {
    transform: translateY(0);
}
.login-divider {
    display: flex;
    align-items: center;
    margin: 25px 0;
    color: #999;
    font-size: 13px;
}
.login-divider::before,
.login-divider::after {
    content: '';
    flex: 1;
    height: 1px;
    background: #eee;
}
.login-divider span {
    padding: 0 15px;
}
.social-login {
    display: flex;
    gap: 12px;
}
.btn-social {
    flex: 1;
    padding: 12px;
    border-radius: 12px;
    border: 2px solid #eee;
    background: #fff;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: #555;
    text-decoration: none;
}
.btn-social:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.btn-social.qq {
    border-color: #12b7f5;
    color: #12b7f5;
}
.btn-social.qq:hover {
    background: #12b7f5;
    color: #fff;
}
.btn-social.wx {
    border-color: #07c160;
    color: #07c160;
}
.btn-social.wx:hover {
    background: #07c160;
    color: #fff;
}
.login-footer {
    text-align: center;
    padding: 20px 30px 30px;
    color: #888;
    font-size: 14px;
}
.login-footer a {
    color: #14b8a6;
    font-weight: 600;
    text-decoration: none;
}
.login-footer a:hover {
    color: #0f766e;
}

/* 响应式适配 */
@media (max-width: 992px) {
    .login-wrapper {
        padding: 20px;
    }
    .login-card {
        max-width: 100%;
    }
}

@media (max-width: 768px) {
    .login-wrapper {
        padding: 15px;
        min-height: 100vh;
        display: flex;
        align-items: center;
    }
    .login-card {
        width: 100%;
        border-radius: 16px;
    }
    .login-header {
        padding: 30px 20px 20px;
    }
    .login-header .logo-icon {
        width: 60px;
        height: 60px;
    }
    .login-header .logo-icon i {
        font-size: 28px;
    }
    .login-header h2 {
        font-size: 22px;
    }
    .login-header p {
        font-size: 13px;
    }
    .login-body {
        padding: 25px 20px;
    }
    .login-input-group {
        margin-bottom: 15px;
    }
    .login-input-group input {
        padding: 14px 16px 14px 42px;
        font-size: 15px;
    }
    .login-input-group .input-icon {
        left: 14px;
        top: 12px;
        font-size: 14px;
    }
    .login-options {
        margin-bottom: 20px;
        font-size: 13px;
    }
    .btn-login {
        padding: 14px;
        font-size: 15px;
        min-height: 48px;
    }
    .login-divider {
        margin: 20px 0;
        font-size: 12px;
    }
    .social-login {
        flex-direction: column;
        gap: 10px;
    }
    .btn-social {
        padding: 12px;
        font-size: 14px;
    }
    .login-footer {
        padding: 15px 20px 25px;
        font-size: 13px;
    }
}

@media (max-width: 480px) {
    .login-header {
        padding: 25px 15px 15px;
    }
    .login-header .logo-icon {
        width: 50px;
        height: 50px;
    }
    .login-header .logo-icon i {
        font-size: 24px;
    }
    .login-header h2 {
        font-size: 20px;
    }
    .login-body {
        padding: 20px 15px;
    }
    .login-input-group input {
        font-size: 14px;
    }
    .btn-login {
        font-size: 14px;
    }
}
</style>

<div class="login-wrapper">
    <div class="login-card">
        <div class="login-header">
            <div class="logo-icon">
                <i class="fa fa-cloud"></i>
            </div>
            <h2>欢迎回来</h2>
            <p>登录您的账户继续使用</p>
        </div>
        
        <div class="login-body">
            <form id="loginForm" method="post">
                <input type="hidden" name="action" value="login">
                <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                
                <div class="login-input-group">
                    <i class="fa fa-user input-icon"></i>
                    <input type="text" name="username" placeholder="请输入用户名" required>
                </div>
                
                <div class="login-input-group">
                    <i class="fa fa-lock input-icon"></i>
                    <input type="password" name="password" placeholder="请输入密码" required>
                </div>
                
                <div class="login-options">
                    <label>
                        <input type="checkbox" name="remember"> 记住我（30天）
                    </label>
                </div>
                
                <button type="submit" class="btn-login">
                    <i class="fa fa-sign-in"></i> 登录
                </button>
            </form>

            <?php if($conf['login_qq'] || $conf['login_wx']){?>
            <div class="login-divider"><span>或使用以下方式登录</span></div>
            
            <div class="social-login">
                <?php if($conf['login_qq']){?>
                <a href="javascript:connect('qq')" class="btn-social qq">
                    <i class="fa fa-qq"></i> QQ登录
                </a>
                <?php } ?>
                <?php if($conf['login_wx']){?>
                <a href="javascript:connect('wx')" class="btn-social wx">
                    <i class="fa fa-wechat"></i> 微信登录
                </a>
                <?php } ?>
            </div>
            <?php } ?>
        </div>
        
        <div class="login-footer">
            还没有账号？<a href="register.php">立即注册</a>
        </div>
    </div>
</div>

<?php include SYSTEM_ROOT.'footer.php';?>
<script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script>
<script>
$(document).ready(function(){
    // 账号密码登录表单提交
    $('#loginForm').on('submit', function(e){
        e.preventDefault();
        
        var formData = $(this).serialize();
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        
        // 禁用提交按钮
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 登录中...');
        
        $.ajax({
            type: 'POST',
            url: 'login.php',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if(response.code === 0) {
                    layer.alert(response.msg, {icon: 1}, function(){
                        window.location.href = './';
                    });
                } else {
                    layer.alert(response.msg, {icon: 2});
                    submitBtn.prop('disabled', false).html(originalText);
                }
            },
            error: function() {
                layer.alert('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    <?php if($quick_register_type): ?>
    setTimeout(function(){
        connect('<?php echo $quick_register_type; ?>', 'quick_register');
    }, 300);
    <?php endif; ?>
});

// 第三方登录连接
function connect(type, flow){
    var ii = layer.load(2, {shade:[0.1,'#fff']});
    var postData = {type:type};
    if(flow){
        postData.flow = flow;
    }
    $.ajax({
        type: "POST",
        url: "login.php?act=connect",
        data: postData,
        dataType: 'json',
        success: function(data) {
            layer.close(ii);
            if(data.code == 0){
                window.location.href = data.url;
            } else {
                layer.alert(data.msg, {icon: 7});
            }
        },
        error: function(xhr, status, error) {
            layer.close(ii);
            var errorMsg = '网络错误，请稍后重试';
            try {
                var response = JSON.parse(xhr.responseText);
                if(response && response.msg) {
                    if(response.msg.indexOf('未配置') !== -1) {
                        errorMsg = '快捷登录接口未配置，请联系管理员';
                    } else if(response.msg.indexOf('来源非法') !== -1) {
                        errorMsg = '请求被拒绝，请刷新页面后重试';
                    } else {
                        errorMsg = response.msg;
                    }
                }
            } catch(e) {
                if(xhr.status === 0) {
                    errorMsg = '无法连接到服务器，请检查网络';
                } else if(xhr.status === 500) {
                    errorMsg = '服务器内部错误，请稍后重试';
                }
            }
            layer.alert(errorMsg, {icon: 2});
        }
    });
}
</script>
</body>
</html>

