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

include_once '../common/function.php';
$action = isset($_GET[ 'action' ]) ? purge($_GET[ 'action' ]) : '';
try {
    if ( !isset($_COOKIE[ '7a57a5a743894a0e' ])) {
        setcookie('7a57a5a743894a0e' , ' ' , time() - 36000 * 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') {

    // 防抖节流
    $redisResult = json_decode(CheckRedis::Run(__RedisLimit__ , __RedisInterval__));
    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_admin')
                  ->where('username' , $username)
                  ->find();
    if ($username == '' || $password == '') {
        exit(ReturnError('账号密码不能为空'));
    }

    // 校验用户名和密码
    if ( !preg_match('/^[a-zA-Z0-9_]{6,20}$/' , $username)) {
        exit(ReturnError('用户名格式不正确'));
    }
    if ( !preg_match('/^[a-zA-Z0-9_]{6,20}$/' , $password)) {
        exit(ReturnError('密码格式不正确'));
    }
    if ($username == $res[ 'username' ] && md5($password) === $res[ 'password' ] && verifyPassword(md5($password) , $res[ 'salt' ])) {
        $COOKIE = md5($res[ 'username' ] . $res[ 'password' ] . time());
        // 更新数据库中的Cookie
        if ( !Db::table('app_admin')
                ->where('username' , $username)
                ->update(['cookie' => $COOKIE])) {
            exit(ReturnError('Sever Error!'));
        }
        setcookie('7a57a5a743894a0e' , $COOKIE , time() + 3600 * 24 , '/');
        exit(return_msg('200' , '登录成功' , ['url' => '/admin?index']));
    } else {
        exit(ReturnError('账号密码错误'));
    }
}
//退出
if ($action === 'logout') {
    setcookie('7a57a5a743894a0e' , ' ' , time() - 3600 * 24 , '/');
    header('Location:./login.php');
    exit;
}

$res_ck = Db::table('app_admin')
            ->where(['cookie' => $_COOKIE[ '7a57a5a743894a0e' ]])
            ->find();
if ($res_ck) {
    $ck = $res_ck[ 'cookie' ];
} else {
    $ck = '';
}
if ($_COOKIE[ '7a57a5a743894a0e' ] === $ck) {
    $islogin = true;
} else {
    $islogin = false;
}
if ( !$islogin) {
    header('Location:./login.php');
    exit;
}
