<?php
include dirname(__DIR__) . '/includes/common.php';
if($islogin2==1){
    @header('Content-Type: text/html; charset=UTF-8');
    exit("<script language='javascript'>alert('您已登陆！');window.location.href='./index.php';</script>");
}
if($_GET['reg'] == 'submits'){
    $qq=daddslashes($_POST['qq']);
    $phone=daddslashes($_POST['phone']);
    $type=isset($_POST['type'])?daddslashes($_POST['type']):null;
    $verifycode=strtolower(daddslashes($_POST['verifycode']));
    $key=daddslashes($_POST['key']);
    if($key=='')exit('{"code":-1,"msg":"秘钥不能为空"}');
    if(strlen($key)!=32)exit('{"code":-1,"msg":"秘钥不正确"}');
    if($_SESSION["validate_key"] != $key)exit('{"code":-1,"msg":"验证失败，请刷新网页"}');
    if($_SESSION['vc_code'] != $verifycode)exit('{"code":-1,"msg":"验证码错误:'.$_SESSION['vc_code'].'----'.$verifycode.'"}');
    $regphonecode = $conf['regphonecode'] ?? 0;
    if($type == 'phone'){
        if($regphonecode != '1')exit('{"code":-1,"msg":"当前未开启手机找回"}');
        if(strlen($phone)!=11)exit('{"code":-1,"msg":"请填写正确的手机号码！"}');
        if($_SESSION['send_sms_time'] > time()){
            exit('{"code":-1,"msg":"1分钟内不可以重复发送短信。"}');
        }
        $ip = real_ip();
        $is = $DB->getRow("SELECT * FROM `pre_logs` WHERE type='短信' AND result='{$ip}' ORDER BY addtime DESC LIMIT 1");
        if($is && $is['result2'] > time()){
            exit('{"code":-1,"msg":"ip：'.$ip.'，1分钟内不可以重复发送短信。"}');
        }
        $row = $DB->getRow("SELECT * FROM `pre_user` WHERE phone='{$phone}' LIMIT 1");
        if(!$row)exit('{"code":-1,"msg":"手机号还没绑定平台账号"}');
        $newpwd = random(6,1);
        $ret = send_sms($phone, '亲！密码已帮您重置，新密码：'.$newpwd);
        if($ret['code'] == 1){
            unset($_SESSION['vc_code']);
            unset($_SESSION['validate_key']);
            $DB->exec("UPDATE pre_user SET pwd='{$newpwd}' WHERE phone='{$phone}'");
            $DB->exec("INSERT INTO `pre_logs` (`zid`,`type`,`result`,`result2`,`addtime`) VALUES ('1', '短信', '".$ip."', '".strtotime('+1minute')."', NOW())");
            $_SESSION['send_sms_time'] = strtotime('+1minute');
            $msg = '新密码已发送成功，请注意查收';
        }else{
            $msg = '发送失败<br>'.$ret['msg'];
        }
        exit('{"code":1,"msg":"'.$msg.'"}');        
    }else{
        $row = $DB->getRow("SELECT * FROM `pre_user` WHERE qq='{$qq}' LIMIT 1");
        if(!$row)exit('{"code":-1,"msg":"QQ:'.$qq.'号不存在"}');
        $mail = $qq.'@qq.com';
        $msg = '您好，您的账号信息如下<hr>账号:'.$row['user'].'<br>密码:'.$row['pwd'].'<hr>登录后请自行修改密码。';
        $ret = send_mail($mail,'找回密码',$msg);
        if(intval($ret) == 1){
            unset($_SESSION['vc_code']);
            unset($_SESSION['validate_key']);
            exit('{"code":1,"msg":"账号密码已经发送到'.$mail.',请注意查收"}');
        }else{
            exit('{"code":-1,"msg":"邮件发送失败，请联系管理员找回"}');
        }        
    }
}
$verifycode = 1;
if(!function_exists("imagecreate"))$verifycode=0;
$validate_key = md5(mt_rand(0,999).time());
$_SESSION["validate_key"] = $validate_key;
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>找回密码</title>
    <script src="../assets/js/tailwind.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="min-h-screen bg-gradient-to-br from-indigo-600 via-purple-600 to-pink-600 flex items-center justify-center p-4">
    
    <div class="w-full max-w-xs sm:max-w-sm md:max-w-md">
        <!-- Logo -->
        <div class="text-center mb-5">
            <div class="inline-flex items-center justify-center w-12 h-12 sm:w-14 sm:h-14 bg-white/20 backdrop-blur-xl rounded-xl mb-2 shadow-lg">
                <i class="fas fa-key text-xl sm:text-2xl text-white"></i>
            </div>
            <h1 class="text-lg sm:text-xl font-bold text-white"><?php echo $conf['sitename'] ?? '管理系统'; ?></h1>
            <p class="text-purple-200 text-xs sm:text-sm mt-0.5">稳定高效的云端管理平台</p>
        </div>
        
        <!-- 找回密码卡片 -->
        <div class="bg-white rounded-xl sm:rounded-2xl shadow-2xl p-4 sm:p-6 hover:shadow-2xl/80 transition-shadow">
            <h3 class="text-base sm:text-lg font-bold text-gray-800 mb-3 sm:mb-4 flex items-center gap-1.5">
                <i class="fas fa-key text-indigo-600"></i>
                找回密码
            </h3>
            
            <?php $regphonecode = $conf['regphonecode'] ?? 0; ?>
            <!-- 标签页（仅开启注册手机号时显示手机验证） -->
            <?php if($regphonecode == '1'): ?>
            <div class="mb-4">
                <div class="flex border-b border-gray-200">
                    <button type="button" class="flex-1 py-2 sm:py-2.5 px-3 text-center text-xs sm:text-sm font-medium text-indigo-600 border-b-2 border-indigo-600" id="tab-qq">
                        <i class="fab fa-qq mr-1"></i>QQ邮箱
                    </button>
                    <button type="button" class="flex-1 py-2 sm:py-2.5 px-3 text-center text-xs sm:text-sm font-medium text-gray-500 hover:text-gray-700" id="tab-phone">
                        <i class="fas fa-mobile-alt mr-1"></i>手机验证
                    </button>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- 表单内容 -->
            <div class="space-y-3 sm:space-y-4">
                <!-- QQ邮箱表单 -->
                <div id="form-qq">
                    <form onsubmit="submits(this);return false;" method="post">
                        <input type="hidden" name="key" value="<?php echo $validate_key?>">
                        
                        <div>
                            <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5">QQ账号</label>
                            <div class="relative">
                                <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                                    <i class="fab fa-qq text-sm sm:text-base"></i>
                                </span>
                                <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                                       name="qq" required placeholder="请输入QQ账号">
                            </div>
                        </div>
                        
                        <?php if($verifycode): ?>
                        <div>
                            <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5">验证码</label>
                            <div class="flex gap-2">
                                <div class="flex-1 relative">
                                    <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                                        <i class="fas fa-shield-alt text-sm sm:text-base"></i>
                                    </span>
                                    <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                                           name="verifycode" required placeholder="请输入验证码">
                                </div>
                                <div class="flex-shrink-0">
                                    <img src="./simple_code.php?r=<?php echo time();?>" height="50" class="h-9 sm:h-10 rounded-lg cursor-pointer hover:opacity-90 transition-opacity"
                                         onclick="this.src='./simple_code.php?r='+Math.random();"
                                         title="点击更换验证码">
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="mt-3 sm:mt-4"></div>
                        
                        <button type="submit" 
                                class="w-full py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm md:text-base bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-medium sm:font-semibold rounded-lg sm:rounded-xl shadow transition-all">
                            <i class="fas fa-envelope mr-1"></i>找回密码
                        </button>
                    </form>
                </div>
                
                <!-- 手机验证表单（仅开启注册手机号时显示） -->
                <?php if($regphonecode == '1'): ?>
                <div id="form-phone" class="hidden">
                    <form onsubmit="submits(this);return false;" method="post">
                        <input type="hidden" name="key" value="<?php echo $validate_key?>">
                        <input type="hidden" name="type" value="phone">
                        
                        <div>
                            <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5">手机号码</label>
                            <div class="relative">
                                <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                                    <i class="fas fa-mobile-alt text-sm sm:text-base"></i>
                                </span>
                                <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                                       name="phone" required placeholder="请输入绑定的手机号码">
                            </div>
                        </div>
                        
                        <?php if($verifycode): ?>
                        <div>
                            <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5">验证码</label>
                            <div class="flex gap-2">
                                <div class="flex-1 relative">
                                    <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                                        <i class="fas fa-shield-alt text-sm sm:text-base"></i>
                                    </span>
                                    <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                                           name="verifycode" required placeholder="请输入验证码">
                                </div>
                                <div class="flex-shrink-0">
                                    <img src="./simple_code.php?r=<?php echo time();?>" height="50" class="h-9 sm:h-10 rounded-lg cursor-pointer hover:opacity-90 transition-opacity"
                                         onclick="this.src='./simple_code.php?r='+Math.random();"
                                         title="点击更换验证码">
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="mt-3 sm:mt-4"></div>
                        
                        <button type="submit" 
                                class="w-full py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm md:text-base bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-medium sm:font-semibold rounded-lg sm:rounded-xl shadow transition-all">
                            <i class="fas fa-mobile-alt mr-1"></i>找回密码
                        </button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- 底部链接 -->
            <div class="mt-4 sm:mt-6 text-center text-xs sm:text-sm text-gray-500 space-x-4">
                <a href="./login.php" class="hover:text-indigo-600 transition-colors">
                    <i class="fas fa-sign-in-alt mr-0.5"></i>返回登录
                </a>
                <a href="./" class="hover:text-indigo-600 transition-colors">
                    <i class="fas fa-home mr-0.5"></i>返回首页
                </a>
            </div>
        </div>
        
        <!-- 版权 -->
        <div class="text-center mt-5 text-white/70 text-xs sm:text-sm hover:text-white/90 transition-colors">
            &copy; <?php echo date('Y'); ?> <?php echo $conf['sitename'] ?? '管理系统'; ?>
        </div>
    </div>
    
    <!-- Toast 提示 -->
    <div id="toastWrap" class="fixed top-4 left-1/2 -translate-x-1/2 z-[60] flex flex-col items-center gap-2"></div>
    
    <!-- Loading 遮罩 -->
    <div id="loadingOverlay" class="fixed inset-0 z-50 hidden bg-white/30 flex items-center justify-center">
        <div class="w-8 h-8 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin"></div>
    </div>
    
    <script src="../assets/js/jquery.min.js"></script>
    <script type="text/javascript">
    var regphonecode = <?php echo json_encode($regphonecode ?? '0'); ?>;
    // 标签页切换（仅开启注册手机号时）
    if (regphonecode == '1') {
        document.getElementById('tab-qq').addEventListener('click', function() {
            document.getElementById('tab-qq').classList.add('text-indigo-600', 'border-b-2', 'border-indigo-600');
            document.getElementById('tab-qq').classList.remove('text-gray-500');
            document.getElementById('tab-phone').classList.remove('text-indigo-600', 'border-b-2', 'border-indigo-600');
            document.getElementById('tab-phone').classList.add('text-gray-500');
            document.getElementById('form-qq').classList.remove('hidden');
            document.getElementById('form-phone').classList.add('hidden');
        });
        document.getElementById('tab-phone').addEventListener('click', function() {
            document.getElementById('tab-phone').classList.add('text-indigo-600', 'border-b-2', 'border-indigo-600');
            document.getElementById('tab-phone').classList.remove('text-gray-500');
            document.getElementById('tab-qq').classList.remove('text-indigo-600', 'border-b-2', 'border-indigo-600');
            document.getElementById('tab-qq').classList.add('text-gray-500');
            document.getElementById('form-phone').classList.remove('hidden');
            document.getElementById('form-qq').classList.add('hidden');
        });
    }
    
    // Toast 提示函数
    function showToast(message, type = 'info', duration = 2000) {
        const toastWrap = document.getElementById('toastWrap');
        const toast = document.createElement('div');
        
        let bgClass = 'bg-gray-800';
        if (type === 'success') bgClass = 'bg-green-600';
        if (type === 'error') bgClass = 'bg-red-600';
        if (type === 'warning') bgClass = 'bg-yellow-600';
        
        toast.className = `${bgClass} text-white px-3 py-1.5 text-sm rounded-lg shadow-lg flex items-center gap-1.5 transform transition-all duration-300 ease-in-out opacity-0 translate-y-[-10px]`;
        toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'exclamation' : type === 'warning' ? 'exclamation-triangle' : 'info'}"></i><span>${message}</span>`;
        
        toastWrap.appendChild(toast);
        
        setTimeout(() => {
            toast.classList.remove('opacity-0', 'translate-y-[-10px]');
        }, 10);
        
        setTimeout(() => {
            toast.classList.add('opacity-0', 'translate-y-[-10px]');
            setTimeout(() => {
                toastWrap.removeChild(toast);
            }, 300);
        }, duration);
    }
    
    // Loading 遮罩函数
    function showLoading() {
        document.getElementById('loadingOverlay').classList.remove('hidden');
    }
    
    function hideLoading() {
        document.getElementById('loadingOverlay').classList.add('hidden');
    }
    
    function submits(obj){
        showLoading();
        $.ajax({
            type : 'POST',
            url : '?reg=submits',
            data : $(obj).serialize(),
            dataType : 'json',
            success : function(data) {
                hideLoading();
                showToast(data.msg, data.code == 1 ? 'success' : 'error');
            },
            error:function(data){
                hideLoading();
                showToast('请求超时', 'error');
            }
        });     
    }
    </script>
</body>
</html>
