<?php
/*
 * @author: CloudZA(云之安) <2922619853@qq.com>
 * @hitokoto: 一场秋雨一场凉，秋心酌满泪为霜。
 * Copyright (c) 2022 by CloudZA, All Rights Reserved.
 */

include_once __DIR__ . '/../common/function.php';
$action           = isset($_GET[ 'action' ]) ? purge($_GET[ 'action' ]) : '';
$checkRedisResult = json_decode(CheckRedis::Run(__RedisLimit__ , __RedisInterval__));
try {
    if ( !isset($_COOKIE[ 'authentication' ])) {
        setcookie('authentication' , ' ' , time() - 7 * 24 , '/');
        // throw new Exception('cookie is empty');
    }
}
catch (Exception $e) {
    // echo $e->getMessage();
}
substr($_SERVER[ 'PHP_SELF' ] , strrpos($_SERVER[ 'PHP_SELF' ] , '/') + 1);
//登录验证
if ($action === 'login') {
    // 防抖节流
    if ($redisResult->code === 201) {
        exit(ReturnError($redisResult->msg));
    }
    $username = isset($_POST[ 'user' ]) ? purge($_POST[ 'user' ]) : '';
    $password = isset($_POST[ 'pwd' ]) ? purge($_POST[ 'pwd' ]) : '';
    $res      = Db::table('app_user')
                  ->where('username' , $username)
                  ->find();
    if ($username == '' || $password == '') {
        exit(ReturnError('账号密码不能为空'));
    }

    // 校验用户名和密码
    if ( !checkUsername($username)) {
        exit(ReturnError('用户名只能为4-20位英文、下划线和小数点组成'));
    }

    if ( !checkPassword($password) && !checkPassword($password2)) {
        exit(ReturnError('密码长度为8到20位，只能包含英文字母和数字'));
    }

    $pwd = md5($password);
    if ($username == $res[ 'username' ] && $pwd === $res[ 'password' ] && verifyPassword($pwd , $res[ 'salt' ])) {
        $COOKIE = md5($res[ 'username' ] . $res[ 'password' ] . time());
        // 更新数据库中的Cookie
        if ( !Db::table('app_user')
                ->where('username' , $username)
                ->update(['cookie' => $COOKIE])) {
            exit(ReturnError('Sever Error!'));
        }
        setcookie('authentication' , $COOKIE , time() + 3600 * 24 , '/');
        exit(return_msg('200' , '登录成功' , ['url' => '../index.php']));
    } else {
        exit(ReturnError('账号密码错误'));
    }
}
//退出登录
if ($action === 'logout') {
    setcookie('user' , '' , time() - 7 * 24 , '/');
    setcookie('authentication' , ' ' , time() - 3600 * 24 , '/');
    header('Location:./login.php');
    exit;
}
$res_ck    = Db::table('app_user')
               ->where(['cookie' => $_COOKIE[ 'authentication' ]])
               ->find();
$user_info = $res_ck;
if ($res_ck) {
    $ck = $res_ck[ 'cookie' ];
} else {
    $ck = '';
}
$islogin = false;
if ($_COOKIE[ 'authentication' ] === $ck) {
    $islogin = true;
    setcookie('user' , $res_ck[ 'id' ] , time() - 7 * 24);
}
// 注册用户
if ($action === 'signup') {
    if ($redisResult->code === 201) {
        exit(ReturnError($redisResult->msg));
    }

    if ( !__ALLOW_REGISTRATION__) {
        exit(ReturnError('当前状态不允许注册'));
    }

    $username  = isset($_POST[ 'user' ]) ? purge($_POST[ 'user' ]) : '';
    $email     = isset($_POST[ 'email' ]) ? purge($_POST[ 'email' ]) : '';
    $password  = isset($_POST[ 'pwd' ]) ? purge($_POST[ 'pwd' ]) : '';
    $password2 = isset($_POST[ 'pwd2' ]) ? purge($_POST[ 'pwd2' ]) : '';

    if ( !checkUsername($username)) {
        exit(ReturnError('用户名只能为4-20位英文、下划线和小数点组成'));
    }

    if ( !checkEmail($email)) {
        exit(ReturnError('邮箱不合法'));
    }

    if ( !checkPassword($password) && !checkPassword($password2)) {
        exit(ReturnError('密码长度为8到20位，只能包含英文字母和数字'));
    }

    if ($password !== $password2) {
        exit(ReturnError('两次密码不一致'));
    }

    // 判断是否启用邮箱验证
    if (__ENABLE_EMAIL_VERIFICATION__) {
        // 判断验证码是否正确
        $uuid      = isset($_POST[ 'uuid' ]) ? purge($_POST[ 'uuid' ]) : '';
        $code      = isset($_POST[ 'code' ]) ? purge($_POST[ 'code' ]) : '';
        $check_msg = json_decode(checkEmailCode($uuid , $code) , true);
        if ($check_msg[ 'code' ] !== 200) {
            exit(ReturnError($check_msg[ 'msg' ]));
        }
    }

    $password  = md5($password);
    $password2 = md5($password2);
    if (checkUsernameExistence($username)) {
        exit(ReturnError('用户名已存在，请更换'));
    }
    if (__REG_LIMIT__) {
        $chat_limit = __REG_LIMIT__;
    } else {
        $chat_limit = 0;
    }
    $add = Db::table('app_user')
             ->add([
                 'username'   => $username ,
                 'password'   => $password ,
                 'email'      => $email ,
                 'cookie'     => md5($username . $password . time()) ,
                 'salt'       => encryptPassword($password) ,
                 'chat_limit' => $chat_limit
             ]);
    if ($add) {
        exit(return_msg('200' , '注册成功' , ['url' => '/user/login.php']));
    } else {
        exit(ReturnError('注册失败'));
    }
}
// 发送验证码
if ($action === 'send_code') {
    if ($redisResult->code === 201) {
        exit(ReturnError($redisResult->msg));
    }
    $email = isset($_POST[ 'email' ]) ? purge($_POST[ 'email' ]) : '';

    RandomCode::setRedisConfig(__RedisHost__ , __RedisPort__ , __RedisPass__); // 设置Redis连接信息
    RandomCode::setCodePrefix(__CodeRef__);                                    // 设置验证码前缀
    RandomCode::setCodeLength(__CodeLen__);                                    // 设置验证码长度
    RandomCode::setCodeExpiration(__CodeExp__);                                // 设置验证码有效时间，单位为秒

    $codeInfo = RandomCode::generate(); // 生成验证码

    $sendEmail = send($email , '邮箱验证码 - ' . WEB_NAME , '<table role="presentation" border="0" cellpadding="0" cellspacing="0" style="margin:0 auto;padding:0;table-layout:fixed;background-color:#edf2f7" bgcolor="#edf2f7"><tbody><tr><td><u></u></td></tr><tr style="border-collapse:collapse;border-spacing:0;padding:0;margin:0"><td style="max-width:600px;padding:0;margin:0;width:600px" width="600" align="center"><table role="presentation" border="0" cellpadding="0" cellspacing="0" width="580" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0;max-width:580px;width:580px;"><tbody><tr border="0" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0"><td align="" valign="" bgcolor="" width="" height="" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0"><table role="presentation" width="580" border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0 auto;width:580px;min-width:580px" align="center"><tbody><tr><td width="100%" style="width:100%;text-align:center;padding-top:80px;" align="center" valign="top"><h2>' . WEB_NAME . '</h2></td></tr><tr><td style="padding-bottom:26px;width:100%;padding-left:15px;padding-right:15px;font-family:Google Sans,Roboto,San-Francisco,Helvetica,Arial;font-size:14px;line-height:25px;color:#666666;text-align:center;font-weight:500;direction:ltr" width="100%" dir="ltr">' . WEB_DESC . '</td></tr></tbody></table></td></tr><tr border="0" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0"><td align="" valign="" bgcolor="" width="" height="" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0"><table role="presentation" border="0" cellpadding="0" cellspacing="0" style="width:464px" width="464" align="center"><tbody><tr><td width="464"><table role="presentation" border="0" cellspacing="0" cellpadding="0" width="100%"><tbody><tr><td style="padding:0 8px;border-radius:8px;background-color:#ffffff"><table role="presentation" border="0" cellspacing="0" cellpadding="0" width="100%"><tbody><tr><td align="center" style="color:#3c4043;font-family:Roboto,San-Francisco,Helvetica,Arial;font-size:14px;font-weight:normal;line-height:25px;margin:0;padding:40px;text-align:left;word-break:normal;direction:ltr;color:#454545" dir="ltr"><div style="padding-bottom: 30px">' . WEB_NAME . '用户 [' . $email . '] 您好，您正在注册' . WEB_NAME . '平台账号，如果不是您本人操作，请忽略，您的验证码是：</div><div style="padding-bottom: 40px; text-align:center;"><div rel="noopener" style="text-decoration:none;display:inline-block;text-align:center;padding:0.75575rem 1.3rem;font-size:1.2rem;line-height:2;border-radius:0.35rem;color:#ffffff;background-color:#7239EA;border:0px;margin-right:0.75rem!important;font-weight:600!important;outline:none!important;vertical-align:middle">' . $codeInfo[ "code" ] . '</div></div><div style="padding-bottom: 30px">此邮箱验证码将在 ' . __CodeExp__ . ' 秒后过期。</div><div style="border-bottom: 1px solid #eeeeee; margin-top: 40px;margin-bottom: 30px;"></div><b style="color:#333333;font-size:14px;line-height:20px;">真诚为您服务</b></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr><tr border="0" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0"><td align="" valign="" bgcolor="" width="" height="" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0"><table role="presentation" border="0" cellpadding="0" cellspacing="0" style="width:580px;" width="580"><tbody><tr><td align="center" valign="" width="" height="" style="border-collapse:collapse;border-spacing:0;padding:0;margin:0;width:580px;"><table role="presentation" border="0" cellpadding="0" cellspacing="0" style="width:580px;" width="580"><tbody><tr><td style="font-family:Roboto,San-Francisco,Helvetica,Arial;font-weight:normal;font-size:12px;line-height:16px;color:#9b9b9b;text-align:center;padding:40px;color:#5f6368;line-height:18px;direction:ltr;"><span style="font-size:inherit;color:inherit;font-weight:inherit;font-family:inherit"> Copyright © 2023 <a href="javascript:void(0);" rel="noopener">' . WEB_NAME . '</a></span></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>');
    if ($sendEmail) {
        exit(return_msg(200 , '验证码发送成功' , [
            'uuid' => $codeInfo[ 'uuid' ] ,
            'time' => __CodeExp__
        ]));
    } else {
        exit(ReturnError('验证码发送失败'));
    }
}
// 修改用户信息
if ($action === 'update') {
    $id       = isset($_POST[ 'uid' ]) ? purge($_POST[ 'uid' ]) : '';
    $email    = isset($_POST[ 'useremail' ]) ? purge($_POST[ 'useremail' ]) : '';
    $username = isset($_POST[ 'username' ]) ? purge($_POST[ 'username' ]) : '';
    $password = isset($_POST[ 'password' ]) ? purge($_POST[ 'password' ]) : '';
    $old      = Db::table('app_user')
                  ->where(['id' => $id])
                  ->find();
    if (empty($username)) {
        exit(ReturnError('用户名或者密码不能为空'));
    }

    if ( !checkUsername($username)) {
        exit(ReturnError('用户名只能为4-20位英文、下划线和小数点组成'));
    }

    if ( !checkEmail($email)) {
        exit(ReturnError('邮箱不合法'));
    }

    if ( !array_compare([$old[ 'username' ]] , [$username])) {
        if (checkUsernameExistence($username)) {
            exit(ReturnError('用户名已存在，请更换'));
        }
    }

    if ( !empty($password)) {
        if ( !checkPassword($password)) {
            exit(ReturnError('密码长度为8到20位，只能包含英文字母和数字'));
        }
        $password = md5($password);
        $op       = Db::table('app_user')
                      ->where(['id' => $id])
                      ->update([
                          'username' => $username ,
                          'password' => $password ,
                          'email'    => $email ,
                          'cookie'   => md5($username . $password . time()) ,
                          'salt'     => encryptPassword($password) ,
                      ]);
        if ($op) {
            exit(ReturnSuccess('更新成功，即将重新登录'));
        }
    } else {
        if (array_compare([
            $old[ 'username' ] ,
            $old[ 'email' ]
        ] , [
            $username ,
            $email
        ])) {
            exit(ReturnError('数据相同，跳过更新'));
        }
        $op = Db::table('app_user')
                ->where(['id' => $id])
                ->update([
                    'username' => $username ,
                    'email'    => $email
                ]);
        if ($op) {
            exit(ReturnSuccess('更新成功'));
        } else {
            exit(ReturnError('更新失败'));
        }
    }
}
// 卡密开通会员
if ($action === 'card') {
    $id   = isset($_POST[ 'uuid' ]) ? purge($_POST[ 'uuid' ]) : '';
    $card = isset($_POST[ 'card' ]) ? purge($_POST[ 'card' ]) : '';

    if (empty($card)) {
        exit(ReturnError('请输入卡密信息'));
    }

    $card_plans = getPlanById(( getCouponByCode($card)[ 'plan_id' ] ) ?? '0');
    if ( !$card_plans) {
        exit(ReturnError('卡密不存在'));
    }
    if (openMember($id , $card , $card_plans[ 'id' ])) {
        exit(ReturnSuccess('开通成功'));
    } else {
        exit(ReturnError('开通失败'));
    }

}
// 创建订单
if ($action === 'create_order') {
    if ($redisResult->code === 201) {
        exit(ReturnError($redisResult->msg));
    }
    $uid         = isset($_POST[ 'uid' ]) ? purge($_POST[ 'uid' ]) : '';
    $group_type  = isset($_POST[ 'group_type' ]) ? purge($_POST[ 'group_type' ]) : '';
    $group_id    = isset($_POST[ 'group_id' ]) ? purge($_POST[ 'group_id' ]) : '';
    $group_order = isset($_POST[ 'group_order' ]) ? purge($_POST[ 'group_order' ]) : '';
    $type        = isset($_POST[ 'type' ]) ? purge($_POST[ 'type' ]) : '';
    if (empty($uid) || empty($group_type) || empty($group_id) || empty($group_order)) {
        exit(ReturnError('数据不完整'));
    }
    if (Db::table('app_order')
          ->where(['pay_order' => $group_order])
          ->find()) {
        exit(ReturnError('订单已存在'));
    }
    /**
     * 写入订单信息
     * 步骤：先根据UID获取用户信息，根据{$group_id}获取套餐信息,然后将数据写入pay_content字段中
     */
    $u_info = getUserMemberInfo($uid);
    if ( !$u_info) {
        exit(ReturnError('获取用户信息失败，请重新创建订单'));
    }
    $p_info = getPlanById($group_id);
    if ( !$p_info) {
        exit(ReturnError('获取套餐信息失败，请重新创建订单'));
    }
    $ip = get_ip();
    if ( !$ip || $ip === '0.0.0.0') {
        exit(ReturnError('环境检测异常，请更换网络'));
    }
    // app_order -> pay_content字段内容
    $pay_content = [
        'user_id'          => $u_info[ 'id' ] ,
        'plans_id'         => $p_info[ 'id' ] ,
        'plans_period'     => $p_info[ 'period' ] ,
        'plans_chat_limit' => $p_info[ 'chat_limit' ] ,
        'group_type'       => $group_type
    ];
    $write_order = Db::table('app_order')
                     ->add([
                         'pay_order'   => $group_order ,
                         'pay_type'    => $type ,
                         'pay_name'    => $p_info[ 'name' ] ,
                         'pay_money'   => $p_info[ 'price' ] ,
                         'pay_time'    => date('Y-m-d H:i:s') ,
                         'pay_ip'      => $ip ,
                         'pay_region'  => getIpAddress($ip) ,
                         'pay_content' => json_encode($pay_content , 320) ,
                         'pay_status'  => 0 ,
                     ]);
    if ( !$write_order) {
        exit(ReturnError('订单创建失败，请联系管理员'));
    } else {
        exit(return_msg(200 , '订单创建成功，是否现在前往付款？' , ['success' => 'submit.php?uid=' . $uid . '&order=' . $group_order]));
    }

}
// 取消订单
if ($action === 'cancel_order') {
    $order = isset($_POST[ 'order' ]) ? purge($_POST[ 'order' ]) : '';
    if (empty($order)) {
        exit(return_msg(201 , '数据不完整，请检查'));
    }
    if ( !Db::table('app_order')
            ->where(['pay_order' => $order])
            ->find()) {
        exit(ReturnError('订单信息不存在'));
    }
    $res = Db::table('app_order')
             ->where(['pay_order' => $order])
             ->update(['pay_status' => '2']);
    if ($res) {
        exit(ReturnSuccess('取消订单成功'));
    } else {
        exit(ReturnError('接口请求失败'));
    }
}







